OO Right Pattern
Two developers have a dispute on which pattern is the right one. I would be very happy if someone could tell me who is right and why.
class a has two functions:
Remove(int item); Save();
a.Remove(1); a.Remove(3); a.Save();
This way you can remove items from it's internal list without saving the changes to the database. As soon as you call a.Save() the internal state of the object will be saved to the database.
class a has only one function
This way you don't have to remember to save and class a can still only save once.
Are there design patterns or other documents which prove the correct way or is it just style?
As it is very synthetic example, it's hard to tell what's the right way winthout knowing of a real context.
In most real cases first solution is better because of the need for reducing of database requests count and duration.
Take a look at Repository and Unit of Work patterns.
Common activity sequence is:
- Create Unit of Work.
- Make some actions with data using Repository (which is mapped to UoW)
- Make another actions with data using Repository
- Commit changes through Unit of Work.
Depending on Unit of Work implementation you may
- Create physical transaction (or connection) at the beginning and push changes immediately. It is flexible equivalent for the second solution.
- Create physical transaction and commit it at the ending with UoW.Commit
- Implement different offline locks (pessimistic or optimistic).
So, it's felxible. Single-method solution is less felxible especially if one time you will need to add another action, i.e.
Talking aboud data access and domain layers, in perspective it may lead to db logic leak and other currently recognized as Anti-patterns (for most cases) things like Active Record.