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
Which approach is better?
When to decide which of the above two approach we have to opt?
If I have to add other methods too like FindAllUsers, FindUserByUserId, DeleteUserByUserId which approach should I go for?