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:
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:
  "\n" + paths.size() + " paths and " +
  ac.getAtomCount() + " atoms left."
you can write:
  "\n", paths.size(), " paths and ",
  ac.getAtomCount(), " atoms left."

1 comment:

  1. That is nice note. Pity that neither log4j nor slf4j support this. For for them one can use:

    if (logger.isDebugEnabled()) {
    logger.debug("Message" + ...);

    but this code is difficult/lazy to cover with tests if you intend also to cover all branches.