Friday, May 6, 2011

Should an object searcher method be in the a parent object, or the same as the object beign searched?

Which constitutes better 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 one

Class User { 
   id {get;set} 
   List<User> Managers(){ }//search for users, return list of them 
}
Class Office { 
   id {get;set}  
}
From stackoverflow
  • I personally like the first one. User is an entity not a collection. Office is the one that contains Managers.

    I probably also would create 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);}
        }
    }
    
  • The first solution is the better one, because User does not/should not know how Office works and how to obtain a list of managers.

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

    Unless it's a static method, make it a method of a class of which you have an instance: no point in making getUsers a non-static method of the User class, because then you'd need a user instance in order to invoke the getUsers method.

  • Similar to the other answers, I prefer the first solution. After all, what relationship does one user have to the collection being searched? How would the client get hold of a user to search with in the first place?

0 comments:

Post a Comment