Tuesday, November 23, 2010

Use compiler to catch new enum value not covered in "switch"

This old trick shines more and more when our project's code base grew over million+ lines. I have to put it on the web one more time just in case there is a developer out there haven't seen this.

Basically you can set the compiler to generate compilation errors when there are enum values not covered in switch block. So that when a new value is added to an enum class, every switch statement on this enum class will get a compilation error. This way it is easier to find and add corresponding cases, and it is impossible to ignore them. :)

To make this work, you have to do (or not do) two things:

  1. DO NOT use "default" case when you do switch on enum values.
  2. Set your compiler to generate ERROR instead of ignore enum values not covered in switch. In eclipse (the greatest IDE), it is here: