3 ms·
> I don't want to have to tell my class how to write a record to the DB You don’t need inheritance to achieve this. Your User class contains data and probably
by fooyc 8y ago
> I don't want to have to tell my class how to write a record to the DB
You don’t need inheritance to achieve this.
Your User class contains data and probably some business logic. The fact that it’s going to be persisted in a database at some point is a detail that the class shouldn’t know.
Consider using the data mapper pattern (or an ORM implementing this pattern). In this pattern, your User object doesn’t even know it will be persisted. It doesn’t have any parent class. You just manipulate your entities like a graph of plain objects, and when you have finished you ask the data mapper to persist them. In my experience this is much better than what you are describing, which look like the Active Record pattern.
> If a class does two broad things
Doing this is a violation of one very commonly accepted principle: The single responsibility principle.
- spdionis 8y agoActive Record should be considered an anti-pattern and is definitely in violation of single responsibility at the least. Myself, I wouldn't even put any business logic in the User object, except maybe representational logic (e.g. have a couple of helper methods that return multiple representation of the same piece of data). One of the best things to do is separate behavior from data in the first place, which feels kind anti-OO philosophy, but is definitely easier to reason about and work with.
- maemilius 8y agoMy understanding of SRP is that the _implementation_ of those two things should be separate, not the interface.
- humanrebar 8y agoWell, the I in SOLID is Interface Segregation, so there's a problem there too.