Are data classes a code smell?

There are two type of classes, regular classes and data classes.

Regular classes abstract reality, use encapsulation, hide fields, do things and are smart.

Data classes only have fields, getters an setters. Maybe an occasional semi-smart getter. They are dumb, don.t do anything and are used by smart classes.

Uncle Bob thinks data classes are a regular and legitimate part of programming.

Martin Foler in Refactoring considers them a code smell to be avoided:

“Data Class

These are classes that have fields, getting and setting methods for the fields, and nothing else. Such classes are dumb data holders and are almost certainly being manipulated in far too much detail by other classes. In early stages these classes may have public fields. If so, you should immediately apply Encapsulate Field (206) before anyone notices. If you have collection fields, check to see whether they are properly encapsulated and apply Encapsulate Collection (208) if they aren’t. Use Remove Setting Method (300) on any field that should not be changed. Look for where these getting and setting methods are used by other classes. Try to use Move Method (142) to move behavior into the data class. If you can’t move a whole method, use Extract Method (110) to create a method that can be moved. After a while you can start using Hide Method (303) on the getters and setters. Data classes are like children. They are okay as a starting point, but to participate as a grownup object, they need to take some responsibility.”

I strongly feel that Data Classes are ok. It.s ok to have Data Classes for parameter objects, data transfer objects, model objects and whatever else you would need them for.

Just keep in mind the difference between data classes and regular classes and keep them separated.

In a perfect world we wouldn’t have data classes. But the world of programming is not a perfect world.

Leave a Reply

Your email address will not be published. Required fields are marked *