Monday 27 July 2009

Switch

Hi Readers,

Today I found a bit unusual usage of switch. What if you have different N options and you have to invoke M common commands and N different commands? How you can save some extra typing job for yourself? (Or how to avoid code repetition.)

switch (var) {
case n1:
...
case nN:
common1();
...
commonM();
case n1:
special1();
break;
...
case nN:
specialN();
break;
}

Got it? The trick is using the same case terms multiple times. If you like it check the DRY approach. And of course don't forget about KISS.

Good day,
Peter

No comments:

Post a Comment

Note: only a member of this blog may post a comment.