Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repository pattern vs DTO pattern approach

We can have these two approaches to send data to Data Access Layer or any other source:

Approach 1: Repository way:

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class UserRepository
{
    public static void Add(User user)
    {
        // Add user logic
    }
    public static void Delete(User user)
    {
        // Delete user logic
    }
    public static User Get(int userid)
    {
        // Get user logic
    }
}

Usage:

var user = new User
    {
        FirstName = "FirstName",
        LastName = "LastName",
        Age = 20
    };
UserRepository.Add(user);

Above, you have seen that I have kept the User class simple. It is not having any behavior.The behavior is added in a separate class UserRepository.

Second approach: Keeping Add/Delete/Get etc in User.cs only:

   public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public void Add()
        {
            // Add user logic
        }
        public void Delete()
        {
            // Delete user logic
        }
        public User Get()
        {
            // Get user logic
        }
    }

Usage:

var user = new User
    {
        FirstName = "FirstName",
        LastName = "LastName",
        Age = 20
    };
user.Add();

Above I have kept the behavior in User.cs only. Both of the two approaches is serving the purpose of adding, deleting etc. the user. Can you let me know

  1. Which approach is better?

  2. When to decide which of the above two approach we have to opt?

  3. If I have to add other methods too like FindAllUsers, FindUserByUserId, DeleteUserByUserId which approach should I go for?

like image 252
Rocky Singh Avatar asked Aug 28 '12 10:08

Rocky Singh


1 Answers

The first approach is far better as you are separating concerns i.e. the domain entity User and persistence to the database.

One of the most important things that is often talked about in Domain Driven Design is "persistence ignorance" See What are the benefits of Persistence Ignorance?

By using the repository pattern, the way you save /get your entity is kept out of the entity code, i.e. your domain keeping it cleaner and in essence achieving persistence ignorance (or going a long way towards it anyway)

So answers:

  1. The repository approch is much better
  2. Always go for option 1
  3. Add these methods to the repository class
like image 82
bstack Avatar answered Oct 16 '22 03:10

bstack