I have a class that represents a row in a table. I want to add a function that manipulate the data in the row. Where should I add the function?
1) inside the class because it is related to the class
2) outside the class in a separate helper class?
In the past I would have always picked number 1. I am starting to think that number 2 is a better answer, because it separates out logic into its own encapsulated class and reduces complexity of the data class. I am thinking the data class should be left as bare as possible and just contain data members with absolutely no logic.
What is the most agile/best way to do this?
The Single Responsibility Principle has been stated as “There should only be one reason for an object to change.” With your option 1, there are two reasons the object could change: you could change what data is stored in the object, or you could change to a different database system (e.g. mySQL to PostgrSQL).
Of course, like everything, it’s a trade-off. There’s some benefit to having all the code in one place. If it’s unlikely that you’ll switch to a different RDBMS in the future, then combining everything into one class might be a good call.
But if you do anticipate switching to a different database in the future — or even supporting multiple database backends — then you’ll probably be better off putting persistence in a separate class.