Posts tagged ‘clarity’

Switches should include all cases

It would probably be useful if all switch statements contained labels corresponding to every possible value of the switched variable rather than using the default case to pick up all the missing cases.

This means you end up writing code like this:

switch(var)

{

case ONE:

     ...case UNHANDLED1:

case UNHANDLED2:

case UNHANDLED2:

default:

    ... ((deal with default case))

}

The advantage to this approach is that a reader can tell when a case has been unintentionally left out or not yet implemented at a glance. Also, as a side effect, when programming in this manner one is less likely to forget about cases – since one is listing all case.

This is an example of a more general idea of programming so as to make one’s intent clear… you just have to bear in mind that making one’s intent clear is secondary to making something that works.

Advertisements

December 21, 2007 at 3:07 pm Leave a comment


October 2018
M T W T F S S
« Nov    
1234567
891011121314
15161718192021
22232425262728
293031