Articles NutritionCheckpoint Hangman Survey Says About Steven Cleary

Data Class

A data class is a class that is only used to hold data and sometimes includes setters and getters for that data. A data class is usually a code smell, however it is not always a code smell. Many people do not believe that it is a code smell, see here and here.


To understand what a data class is and how to deal with it first consider why getters and setters are useful. Imagine you designed banking system. You create a bank class and you make the amount of money in the bank public. Then after a month of working on the system the requirements change. Now whenever someone’s bank account amounts to more than $100,000 an email should be sent to a manager. With public fields this becomes a huge task, but with setters this would be an easy task.

But just adding setters and getters doesn't mean they will be implemented correctly. Imagine the same banking system as the last. But this time the programmer is told to use setters, getters, and to not let anyone deposit a negative amount. They could just end up checking the deposit amount outside the bank class every time they make a deposit. Even though they are using setters and getters, they are missing functionality that should be encapsulated.

According to Martin Fowler, data classes are “almost certainly” being used inappropriately by other classes. This is because there is a very high chance that there is duplicate functionality outside of the class. And if there is not, there probably will be if nothing is done. The refactoring methods to solve this are to move functionality to the data class and to remove any unnecessary getters and setters.