当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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}

}

网友答案:
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.

网友答案:

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.

网友答案:

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?

网友答案:

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);}
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: