somecoolname
somecoolname

Reputation: 337

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.

Developer 1:

class a has two functions:

Remove(int item);
Save();

Reasoning:

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.

Developer 2:

class a has only one function

Remove(List<int> items);

Reasoning:

a.Remove(new List<int>{1,2});

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?

Upvotes: 3

Views: 78

Answers (1)

Valentin P.
Valentin P.

Reputation: 1151

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:

  1. Create Unit of Work.
  2. Make some actions with data using Repository (which is mapped to UoW)
  3. Make another actions with data using Repository
  4. Commit changes through Unit of Work.

Depending on Unit of Work implementation you may

  1. Create physical transaction (or connection) at the beginning and push changes immediately. It is flexible equivalent for the second solution.
  2. Create physical transaction and commit it at the ending with UoW.Commit
  3. 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.

Remove(1,2);
Add(5);

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.

Upvotes: 1

Related Questions