When NOT to use the static keyword in Java?

Two of the greatest evils you will ever encounter in large-scale Java applications are

  • Static methods, except those that are pure functions*
  • Mutable static fields

These ruin the modularity, extensibility and testability of your code to a degree that I realize I cannot possibly hope to convince you of in this limited time and space.

*A “pure function” is any method which does not modify any state and whose result depends on nothing but the parameters provided to it. So, for example, any function that performs I/O (directly or indirectly) is not a pure function, but Math.sqrt(), of course, is.

More blahblah about pure functions (self-link) and why you want to stick to them.

I strongly encourage you to favor the “dependency injection” style of programming, possibly supported by a framework such as Spring or Guice (disclaimer: I am co-author of the latter). If you do this right, you will essentially never need mutable static state or non-pure static methods.

Leave a Comment