Monday 12 December 2011

Some of My Coding Habits

This is a brief description of my coding habits including indentation, new lines and other things that I don't usually see although I think it makes code clearer.

Variable declaration and assignment on separate lines
Example:

JLabel nameLabel;

nameLabel = new JLabel("Name:");
nameLabel.setBackground(Color.RED);

Although I didn't take up SmallTalk seriously I did come away with, among other things a new coding habit.  SmallTalk variables are always declared in pipes i.e. | myVar | before use.  In Java I use this, especially when the object needs one or more method calls after it is created.  It is almost like a paragraph header and allows the code on the left hand side to match up which I find quite easy to read.

Static imports

No need for an example here, I just really like static imports... in moderation.  They are particularly effective for enums where the enum name might be repeated over and over again.  It is also quite safe to use enums in this way because type safety will not allow you to do anything silly such as EnumA.RED == EnumB.RED without giving a compilation error.

Static imports are quite bad for importing primitive constants, it is much easier to make a mistake without the context of the class name from where it came.  For example, two different integers might mean very different things.  A number of cats and a number of dogs which should not be added together. 

It is quite rare for me to write static methods so this isn't usually an issue.

Returning new
Example:

public String findDayName(int dayIndex)
{
  assert dayIndex >= 1 && dayIndex <= 7;

  switch(dayIndex)
  {
    case 1: 
      return "monday";
    case 2: 
      return "tuesday";
    default: 
      return null;
  }

  // and when using an if statement
  if(dayIndex == 1)
    return "monday";
  else if(dayIndex == 2)
    return "tuesday";
  else
    return null;
}

When using a reasonable size switch or if statement I typically bring this out into a separate method with no variables other than the data needed to perform the switch.  Even this is not necessary if the data is a class field. There is no variable that gets assigned to so no need to worry about a name, or maintain the name and the method name make sense together.  If statements also do not have brackets to cut down on needless lines and white space which in this case would just make the code more bulky and difficult to read.

The if statement is reminiscent of Erlang guarded methods.