Do-er classes and static utilities

Say you have a FileReader class with a read method.

I understand that class attributes can justify having an instance. However, what stops the creation of the equivalent ReaderUtils class by pulling the same attributes inside the scope of the corresponding static read method?

In short, what exactly does the Doer class justify for static utilities?

+7
source share
3 answers

The essence of OOP is to encapsulate state / data along with appropriate behavior. The static methods of the utility are akin to global functions in the procedural language - you separate the behavior (static method) from the state (parameters to this method), thereby breaking encapsulation.

What does this mean in practice? Instead of calling reader.read() , you should call ReaderUtils.read(file) , which means that you are now closely connected with the implementation - you made the implicit assumption that you will always use ReaderUtils and always transfer the file.

If you use a common Reader interface, you can use FileReader today, but replace it with DatabaseReader or HttpReader tomorrow without having to change any other code - all reader.read() calls will continue to work the same.

+2
source

Interfaces cannot be implemented statically - implemented interface methods must be instance methods. Thus, this prohibits injection or JNDI searching for a β€œutility class” as an implementation of execution to execute some service β€” it must be an instance of the class. This is one of the main reasons why doer classes exist.

Utilities are cool if the implementation is known at compile time and, being static methods, are more likely to be inactive (just make sure that any static fields are immutable / unstable), which is required for typical servers serving requests at the same time.

+2
source

This is a matter of preference. In general, Java supports nouns (because people think it's more OO), which is why FileReader is.

As Jeffrey notes, sometimes the obsession of a noun leads to unnecessary verbosity in which point calls are wrapped in static methods.

+1
source

All Articles