Pages

Wednesday, March 17, 2010

Cleaner CDK Code #2: String.contains() and logger messages

Second in the series (see #1), with two rather small tips.

Use String.contains() instead of String.indexOf("foo") != -1
Java 5 introduced the method public boolean contains(CharSequence s), which can replace the more cryptic use of indexOf() != -1.

Instead of:
System.getProperty("java.version").indexOf("1.6") != -1
you can write:
System.getProperty("java.version").contains("1.6")
More efficient use of the LoggingTool
Quite a long time ago, Jmol developer Miguel introduced me to a nice performance hint with respect to using logging tools. Each debug(), info(), warn(), etc method should take more than one parameter, so that only when debugging (or the debug level) is turned on, the objects are concatenated. It indeed gave a considerable performance boost to things. The CDK supports this too, and you should not concatenate Strings and other objects, but let the LoggingTool do that.

Instead of:
logger.debug(
  "\n" + paths.size() + " paths and " +
  ac.getAtomCount() + " atoms left."
);
you can write:
logger.debug(
  "\n", paths.size(), " paths and ",
  ac.getAtomCount(), " atoms left."
);