Tag Archives: anti-patterns

Java Anti-Patterns

“Odi” has an excellent article about Java Anti-Patterns.

Some things I found interesting, learnt/realised or think others could do with knowing are below, with my comments and exclamations in some cases:

  • When initialising a StringBuilder, specify a length if you can in order to avoid unnecessary resizing.
  • Use String.valueOf(int) instead of “” + int
  • Don’t create needless objects, e.g. new Boolean, new Integer – use constants or valueOf.
  • Do not attempt to parse, manipulate or create XML via string processing! Also goes for JSON.
  • Specify encodings for readers and writers – don’t rely on the platform default.
  • Use buffers with streams.
  • Think about handling exceptions. Catch, log and carry on is often not the correct thing to do!
  • Always log the exception, not just it’s message!
  • Don’t re-wrap RuntimeException for throwing.
  • When re-throwing, pass getMessage() of the cause rather than just the cause – the latter uses the toString() of the cause as the message for the new exception, which ┬ácan get unwieldy as it includes the fully qualified name of the cause.
  • When catching, either log or throw. Not both. Usually that is, sometimes the caller is outside your control and might neglect to log it.
  • Take care with nulls in finally blocks that close streams etc. – if there are many involved and opening the first one failed, the others will be null when you try to close them.
  • Don’t swallow exceptions that “never happen”! The thrower might change in the future. Catch and throw a runtime exception instead.
  • Use Thread.currentThread().getContextClassLoader(), not getClass().getClassLoader() in application servers to get the right one.
  • SomeClass.class.isAssigableFrom(x) is reverse of instanceof – tells you if you can assign x to a variable of type SomeClass.
  • When passing a capacity to collection constructors, you need to take into account the point at which they auto-grow – this is less than the capacity! e.g. for HashMap it’s 1 + (numOfThingsYoureGoingToPutIn / 0.75).
  • Setters should not modify what they’re given!
  • Date manipulation is generally crazy and misunderstood.
  • SimpleDateFormat is not thread-safe. Use ThreadLocal.
  • Check for overflows before casting longs to ints.
  • Don’t use == with floats and doubles.
  • Timers keep tasks around until they expire, even after they get cancelled.