Switches should include all cases

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

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

Entry filed under: Uncategorized. Tags: , , .

Refactoring – An analysis of intent (Part I)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


December 2007
M T W T F S S
    Jan »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

%d bloggers like this: