When it comes to OO database access you see two common approaches – the first is to provide a class (say “Customer”) with methods such as Retrieve(), Update(), Delete(), etc. The other is to keep the Customer class fairly lightweight (essentially just properties) and perform the database access elsewhere, e.g. using a repository.
This choice of approaches doesn’t just apply to database access, it can crop up in many different OOD scenarios. So I was wondering if one way is preferable over the other (although I suspect the answer will be “it depends”)!
Another dev on our team argues that to be truly OO the class should be “self-contained”, i.e. providing all the methods necessary to manipulate and interact with that object. I personally prefer the repository approach – I don’t like bloating the Customer class with all that functionality, and I feel it results in cleaner code having it elsewhere, but I can’t help thinking I’m seriously violating core OO concepts!
And what about memory implications? If I retrieve thousands of Customer objects I’m assuming those with the data access methods will take up a lot more memory than the property-only objects?
1
One of the major principles of good OOP design is Separation Of Concerns.
Persistence – the loading and saving of object data is a separate concern to the business concerns of the object, the thing it is modelling.
As such, persistence concerns should be handled by a separate object – one often used pattern that you have mentioned is indeed the repository pattern.
2