问题描述:

I have a scenario in which I need advice on. I have an application where there are two kinds of users Student and Teacher. Student and Teacher share some of the common properties like FirstName, LastName, Email, UserName, Password etc. For this reason I derive Student and Teacher classes from User.

Now, the problem is that there are times where I don't really know that if the user is student or teacher. Like when implementing a custom membership provider and in the GetUser function. GetUser takes userName but now I lost that what should I return.

For Student functions I have created IStudent and ITeacher for teachers. But sometimes I just want to return a User and do not care about if he is student or teacher. But then returning base class does not seems like a good idea too.

UPDATE:

I think it is good idea to return User and not even have Student and Teacher classes. Student and Teacher are simply the roles and can be managed by StudentServices and TeacherServices.

网友答案:

A classic scenario and a classic runaway from the problem. Yes there is always pain to work with inheritance as they constrain. But benefits occur when you inject behavior into your class(es). Now it seems like you have decided for jut using User class and not having User as a base and child classes Teacher and Student. It can be a good idea if you make Teacher and Student as roles, but handling them in separate services... well it smells i my opinion. You'll likely end up with duplicate code in these services since they both need to handle User logics.

The fact is if you start to fend off difficulties like this by compensate in service layer, that's the road to an anemic domain model where logic leaks out from domain layer to gui or service layer. What is unique with teacher and student and what logic/behavior differs should be represented in domain layer.

You can use inheritance (maybe the best solution) or making these as a role where you actually make Role as a custom Enum - Look at (I Think) Jimmy Bogard for how to extend a custom Enum with behavior.

相关阅读:
Top