Should the method of finding an object be in the parent object, or like finding an object?

What is the best object-oriented design?

Class User { 
   id {get;set} 
}
Class Office { 
   id {get;set}  
   List<User> Managers(){  }//search for users, return list of them
}

      

or this

Class User { 
   id {get;set} 
   List<User> Managers(){ }//search for users, return list of them 
}
Class Office { 
   id {get;set}  
}

      

0


a source to share


4 answers


User john;
List<User> managers = fred.Managers(); //get managers of this user

Office london;
List<User> managers = london.Managers(); //get managers of this office

      



If it's not a static method, make it a method of the class to which you have an instance: you don't need to make getUsers a non-stationary method of the User class, because then you need a user instance to call the getUsers method.

+2


a source


The first solution is better because it User

doesn't / doesn't know how it works Office

and how to get the list of managers.



+3


a source


Like the other answers, I prefer the first solution. After all, what does a user have to do with finding a collection? How will the client get access to the user to search in the first place?

+2


a source


I personally like the first one. A user is an object, not a collection. Office is the one that contains managers.

I am probably also creating a UserList class.

public class UserList : List<User>
{}

class User 
{ 
  public int id {get; set;} 
  public bool IsManager { get; set;}
}

class Office {
    private UserList _users;
    UserList Managers
    {
        get { return (UserList) _users.FindAll(x => x.IsManager);}
    }
}

      

+1


a source







All Articles