architecturebusiness-logicseparation-of-concernsbusiness-logic-layermulti-layer

When Creating/Updating an entity, Should I Pass object to business logic or object values?


When working with an entity, which of the following is recommended? (The following code is in UI Layer. UserManager is in Business Layer)

1-

protected void btnReturn_Click(object sender, EventArgs e)
{
    var user = new User();
    user.Name = txtName.Text;
    user.Address = txtAddress.Text;
    ...
    new UserManager().AddUser(User);
}  

In UserManager:

public void AddUser(User user)  
{
    _repository.Add(user);
    _repository.SaveChanges();
}  

public void DeleteUser(User user)  
{
    _repository.Delete(user);
    _repository.SaveChanges();
}  

2-

protected void btnReturn_Click(object sender, EventArgs e)
{
    new UserManager().AddUser(txtName.Text, txtAddress.Text, ...);
}  

And in UserManager:

public void AddUser(string name, string address,...)  
{
    var user = new User();
    user.Name = name;
    user.Address = address;
    context.Users.Add(user);
    context.SaveChanges();
}  

public void DeleteUser(int userID)  
{
    var user = rep.First(u => u.UserID = userID)
    _repository.Delete(user);
    _repository.SaveChanges();
}  

Solution

  • Choose the first option. Later, when you find out that you have to add n+1 fields to the user form, you can just update the user class to handle the new data. It is nearly always a pain to add those fields as parameters, as you should update every single call to that method to include those fields, even if only one of the calls would actually need the new fields.

    Also, as a rule of thumb, if the number of a method's parameters goes above five, you should consider using an object to pass those parameters.