This articles describes what’s bad about dumb data holding classes. It describes how to refactor Data Classes. Also Code Smells are introduced briefly, of which Data Class is one.
My daily posts still take too long to write, so I choose an even simpler topic for today: Data Classes.
What are Code Smells?
Code Smells are indications, that something may be wrong with your code. They are no hard proofs to point at. Instead they give you hints and serve as examples how to do it not.
Code Smells apply to object-oriented code only. One of these Code Smells is called Data Class.
What are Data Classes?
Data Classes are classes, which only contain fields, getters and setters. Or even worse: only public fields. They are just dumb data holders.
Are they really so bad?
When you do some quick prototyping and need to store and transfer data without too much coding effort, they are sometimes a good compromise.
But when your project grows, you should fix this to accomplish one major goal of object orientation: Low Coupling between classes. You want as few dependencies between your classes as possible. But currently everything that’s done with your data, is done in other classes:
What to do about it?
To achieve a low coupling and a high cohesion you need to put the methods in the classes they’re working on most. If you already introduced a Data Class you either need to move the methods closer to the fields or vice versa:
This eliminates the dependencies and thus lowers the coupling between the classes.
If no more class accesses the fields, you can even remove their getters and setters and leave them private:
Now our DataClass no longer smells like a Data Class. We reduced the coupling and from this point we could change the ex-DataClass without effecting the other classes. Enjoy your great code 🙂