A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a abstract enum in the base class to be used for checking the type of the subclass, or if you should use the is operator.
Alt 1.
public abstract class Document{
}
public class PDF:Document{
}
Check: If (myobj is PDF)
Alt 2.
public abstract class Document{
public abstract DucumentType TypeOfDocument {get;}
}
public class PDF:Document{
public DucumentType TypeOfDocument { get{return DucumentType.PDF };}
}
public enum DucumentType{
PDF, Word
}
Check: If (myobj.TypeOfDocument == DucumentType.PDF)
The ones for Alt1. ment that Alt2 slightly breaks SRP, you don’t take advantage of OO, Your repeating the abstraction. Since inheritance is the hardest connection between classes you cannot avoid knowing of them, and if you must go thru with inheritance minimize the impact. Alt2 also breaks DRY
The ones for Alt2 ment that Alt2 will be removing type checking entirely and replacing it with the option of checking this enum instead. Removing all hard connections to all subclasses, and the value of the enum itself does not say anything about which concrete implementation thats currently beeing operated on.
Whats your opinion about the two alternatives? 开发者_C百科
No discussion of inheritance vs. composition etcetera, that’s another question!
Why do you need to know in the first place? I agree that it's occasionally necessary, but where possible you should make the Document type have appropriate abstract functionality to allow the specialization to be done through inheritance rather than the caller having to treat it differently.
I would only use the enum approach if different subclasses may share document types but withotu wanting to share an inheritance hierarchy. This would be pretty rare, IME.
IMO you should use the is operator. It gives you the same result without tainting the (abstract) class code.
I've got a similar situation, except that in my case, the DocumentType enum needs to grow as various types are added. By using the Enum, type checking is much better, but it requires that the "generic" base class be recompiled every time a new DocumentType is added.
The alternative I'm currently pondering is to use an interface property to return the type as a STRING. It's not great for type checking, but the rest of my code has the necessary validation to prevent rogue DocumentType objects. I would prefer a different solution, but nothing comes to mind.
精彩评论