Enumerations: Why? When?

后端 未结 7 1098
梦如初夏
梦如初夏 2020-11-30 08:37

I am an almost-graduating computer science student, and throughout my coding career, I\'ve found very few instances where enumerations, except for canonical cases such as re

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 08:59

    Consider some simple code:

    without enums:

     int OPT_A_ON = 1;
     int OPT_A_OFF = 0;
    
     int OPT_B_ON = 1;
     int OPT_B_OFF = 0;
    
     SetOption(OPT_A_ON, OPT_B_OFF);    // Declaration: SetOption(int, int)
    

    That look fine, right? Except SetOptions() wants Option B first and then Option A. This will go through the compiler just fine, but when run, sets the options backwards.

    Now, with enums:

      enum OptA {On =1, Off = 0};
      enum OptB {On =1, Off = 0};
    
      SetOption(OptA.On, OptB.Off);// Declaration: SetOption(OptB, OptA)
    

    Now we make the same error, but this time, since enums are different types, the mistake is caught by the compiler.

    (NOTE: I'm not really a Java programmer, so please forgive minor syntax errors)

提交回复
热议问题