Monday, June 29, 2009

A rule of thumb when writing comments in code


When you're writing code, ask yourself if someone else could come in behind you and understand it. If not, refactor the code and/or add comments to explain what you're doing.

Protected vs. Private methods in Java

Unless you have a specific reason to make the method private - like you expressly want to prevent subclasses from accessing the method - methods should be protected. This way we can subclass this tag.

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();
}

Comparison in Enums

Tip on Enums

Instead of using id to do equality comparisons for enums, use the enum itself.

Example: Instead of
if (selectedTab.getId() == Tab.SITES.getId()) {
use:
if (selectedTab.equals(Tab.SITES)) {

StringBuilder vs. StringBuffer

A tip on StringBuilder vs. StringBuffer

  • We should be using StringBuilder over StringBuffer. It’s a drop-in replacement, all the method names and arguments are the same.

  • StringBuilder is not synchronized and therefore doesn’t require object locks everytime a method is called. The only time we’d use StringBuffer is when it’s a member variable with a possibility of multiple threads writing to it.