Small Tips

Don’t catch NullPointerException. Check for it.

String concatenation to create a hash key or to store multiple values is easy but fragile. Prefer an object key with a proper hashcode. Prefer an object to store multiple values. Otherwise use a standard such as CSV instead of using your own “dash-separated values”. Use a library to handle escaping problems (a name may also contain a comma).

If you do need to concat Strings, use StringBuilder/StringBuffer. Know the difference between the two.

EclEmma

Emma is a coverage tool.

EclEmma is an Eclipse plugin that generates Emma coverage. It installs via an update site. It executes via the Run Dialog, so any existing run configuration can be easily “coveraged” (including RCP JUnit tests). An additional coverage tab in the Run Dialog allows you to select which packages will be instrumented.

Results are shown graphically in an Eclipse view, grouped by packages. The view allows you to drill into classes and into methods, showing the coverage of each level along the way. Double-clicking in the view brings up the source code, which is color coded to represent which lines were covered.

This is very useful during the personal development process, as individuals can selectively run unit tests to check for coverage in the related modules they are working with. The results are interactive and allows the developer to quickly see which areas require coverage improvement. This is much easier than waiting and going through a Continuous Integration report later (if any). In fact, I have successfully employed this approach to identify areas lacking coverage, and discovering bugs after having test cases for those areas identified.

JTable column headers

A JTable’s column headers are not shown when you add a JTable to the container.

To show the headers, add the table into a JScrollPane before adding it into the container.

If for whatever reason the scroll pane is not desired, use JTable.getTableHeader() to get the column header component, which you can add to the NORTH side of a BorderLayout for example.

JUnit addons

JUnit-addons is a useful library that extends JUnit asserting features. To name a few:

junitx.framework.ArrayAssert: If you’ve written test cases long enough you’ll know that assertEquals won’t work on arrays, and you’ll repeatedly write a loop to assert so. This class takes care of it all.

junitx.util.PrivateAccessor: I’ve always written utility classes to help me set private fields when mocking test objects. Looks like I’m not the only one with the problem.

junitx.framework.Assert.assertNotEquals(): Might be useful in certain cases. Not really recommended because you really want to match the value you’re asserting. It’s too easy to pass a NotEquals() test.

javax.crypto.Mac not threadsafe

Although not explicit, the usage of the class quite obviously shows that multiple threads shouldn’t use the same instance to calculate a hash.

In particular, even if the update() methods were not used and multiple threads call the doFinal() method together, you are likely to get a bad result (which is worse than an Exception).

Something unit test cases cannot catch.

StringBuffer obsession

For those of you who are obsessed with reusing StringBuffers, take a look at this. They’re good for adding strings up, but once you’re done, throw it away and get a new one. There’s no need to clear it and use it again.

Like what I say, too much of anything is no good.

btw this was talking about JDK1.4 in 2003. It’s probably worth a re-investigation 5 years from then, in JDK6 (or 7).

Utility calls

Java is very verbose. Therefore many people have come up with calls to do very common things. For example:

java.util.Arrays.toString(array);
java.util.Arrays.deepToString(nestedArray);

This prints the contents of the array, instead of a cryptic string. This method is available since 1.5.

Another good one is:

org.apache.commons.io.IOUtils.closeQuietly(stream);

Usually used in a finally clause, this one closes streams or readers, ignore IOExceptions, and handles null. This is available in the Apache commons-io library.

Refactoring

I’ve been refactoring some code, and just have some thoughts on common things I’m fixing.

  1. Do the same thing at the same place. If the same snippet of code appears more than twice, e.g. checks if the user is logged in and redirects the user to the login page, it should be extracted. The fewer the control points, the easier it is to debug or change its implementation. IDEs will also allow you to easily trace who is using this functionality, which may help you access the risk of change. “More than twice” is a general guideline. You might see the potential of extraction even if the code only appears once or twice. Sometimes its not suitable for extraction even if it appears more than twice.
  2. Reduce condition nesting by quickly eliminating alternative flows. Leave the rest of the method for the happy/main flow. e.g. If you detect the user is not logged in, call the redirect and return. Using the return avoids needing an “else” after the if. Adding a comment here helps to understand the alternative condition (see point 5).
  3. Learn the lazy loading pattern. Helps reduce nesting as well if you understand how to apply ifs.
  4. Coherence and Coupling. Standard OOAD.
  5. Comments. Not easy to see good commented code. School only tell us to write comments. Who teaches how to write good comments at appropriate places? There’s no need to comment every line. Nor is it good to be comment-less.