Friday, May 7, 2010

When a value is final, treat it that way.

The fragment:

StringBuffer sb = new StringBuffer();
...
method1sb.toString().substring( 0, sb.length() - 1 ) );
method2sb.toString().substring( 0, sb.length() - 1 ) );

The problems:
  • In context, the StringBuffer value has been finalized and will not be changed.  There is no reason for it to still be a StringBuffer.
  • In context, the substring operation is to eliminate a trailing comma.  The StringBuffer load appends "<item>," which could have been done in a way that avoids the trailing comma, but that will be covered in another post.  For now, the point is, again, the value has been finalized and subsequent references should not be required to do identical operations to redetermine the unchanging value.

Better:

StringBuffer sb = new StringBuffer();
...
String s = sb.toString().substring( 0, sb.length() - 1 ) );
method1( s );
method2( s );

No comments:

Post a Comment