I'm hoping someone can help explain the law of demeter to me. If I have a class which I'm assuming is an aggregate root and within that have a collection of child classes is it illegal to update the properties of those child classes by accessing them through the aggregate root?
e.g.
public class Company
{
// company has a number of employees
public List<Employee> Employees {get; set;}
}
public class Employee
{
// each employee has a lastname
public int Id {get; set;}
public string LastName {get; set;}
// other properties of employee
}
lets say I have a client that is accessing the Company class firstly would it be violating the law of demeter with something like.
Employee e = aCompany.Employees.Where(e => e.Id == 1).Single();
e.LastName = "MarriedName";
Or should this always be delegated to Company
public class Company
{
public UpdateEmployeeLastName(int employeeId, string newName)
{
Employee e = Employees.Where(e => e.Id == employeeId).Single();
e.LastName = newName;
}
}
in the client
aCompany.UpdateEmployeeLastName(1, "Marriedname");
The second one seems better but is there anything wrong with the client having to know the id of the Employee it wants to update?
This seems like it could start to get complicated where you have a number of nested aggregates.
Thanks