How to ensure completeness in an enum switch at compile time?

后端 未结 12 1033
悲&欢浪女
悲&欢浪女 2020-11-27 06:25

I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case s

12条回答
  •  佛祖请我去吃肉
    2020-11-27 06:51

    Probably a tool like FindBugs will mark such switches.

    The hard answer would be to refactor:

    Possibility 1: can go Object Oriented

    If feasible, depends on the code in the cases.

    Instead of

    switch (language) {
    case EO: ... break;
    case IL: ... break;
    }
    

    create an abstract method:, say p

    language.p();
    

    or

    switch (p.category()) {
    case 1: // Less cases.
    ...
    }
    

    Possibility 2: higher level

    When having many switches, in an enum like DocumentType, WORD, EXCEL, PDF, ... . Then create a WordDoc, ExcelDoc, PdfDoc extending a base class Doc. And again one can work object oriented.

提交回复
热议问题