Monday, June 29, 2009

if/else vs. switch

When writing code that branches on enum values, instead of if/else blocks, use the switch statement like so:

switch (selectedTab) {
case (Tab.SITES):
//do something for sites
case (Tab.CATEGORY):
//do something for category
case (Tab.DEMOGRAPHIC):
//do something for demographics
case (Tab.ALL_SITES):
//do something for all sites
}


Lengthy and nested methods: Methods should small, atomic and easy to read. Break it up like so:

switch (selectedTab) {
case (Tab.SITES):
renderSitesTab();
case (Tab.CATEGORY):
renderCategoryTab();
case (Tab.DEMOGRAPHIC):
renderDemographicsTab();
case (Tab.ALL_SITES):
renderAllSites();
}

No comments:

Post a Comment