Static is bad!!

Static is bad!!

Are static methods or variables bad? While the answer is subjective but overuse of it is definitely bad as static represents a global state and its difficult to reason about and hard to test.

Recently I was refactoring an old and found that there were multiple instances of ObjectMappper and everywhere it was like this.

private static final Static ObjectMapper MAPPER = new ObjectMapper();

Clearly there were a lot of duplicate instances of ObjectMapper which was not only violating the principle of reusability but also in the Spring world it was ignoring Dependency injection.

A simple solution to fix this problem was to create a singleton instance of ObjectMapper and inject it through DI. As the first step, I made this variable non-static and injected it through autowire. Now, it looks like this,

@Bean
public ObjectMapper objectMapper(){
    return new ObjectMapper();
}
@Autowired
private ObjectMapper mapper;

Wait a minute, am I making another mistake? Yes, constructor-based injection is recommended for required dependencies allowing them to be immutable and preventing them to be null. A Setter-based injection is recommended for optional dependencies.

private final ObjectMappper mapper;
@Autowired
public Constructor(ObjectMapper objectMapper){
      this.objectMapper = objectMapper;
}

Everything looks good now, but I see a compilation error non-static variable MAPPER cannot be referenced from a static context There is a static inner class that is using a mapper instance which was static earlier. To fix this all we have to do it is declare this inner class as non-static. Mission accomplished, evil is no more alive.

This was just one instance where static was used in the wrong way resulting in code duplication and objects which is bad. Another bad practice I've seen is an excessive obsession with static utility classes when they should be part of object.

In object-oriented programming, each object has its own state, represented by instance (non-static) variables. Static variables represent state across instances which can be much more difficult to unit test. This is mainly because it is more difficult to isolate changes to static variables to a single test.

That being said, it is important to make a distinction between regular static variables (generally considered bad), and final static variables (AKA constants; not so bad).