开发者

Would an abstract class be better than an interface in the following case?

I have one interface that contains four functions. I have about 20 classes that implement this interface. Throughout each class, I see a lot of duplicate code, for example, there are constants declared at the beginning that are in every class. The method implementations (logic) of the interface are mostly the same. It contains duplicate structures. Is this a case where I can eliminate a lot of duplicate classes by implementing an abstract class instead of an interface. What I am striving for is too be able to put common methods from the abstract class as non-abstract methods and then methods that need their own implementation would be marked over-ridable. Can I put consts and structures in abstract classes? If so, that would eliminate a lot of duplicate co开发者_运维百科de across the classes. Is there anything else I should look out for in the classes as a sign that I probably should be use an abstract class instead of an interface.


Actually, in most cases, it makes sense to do both. Create an interface and write all client code to talk to the interface, but also create an abstract class that implements the interface. SUbclasses can extend the abstract class if they want to, or not. That way you get the flexibility of the interface, and the convenience of the abstract class.


It is always a good idea to eliminate duplicate code. So yes, you should put the common consts into an abstract class (which still can and should implement interface). However, you should consider whether the constants are really common for all the derived classes.

One should never put a constant into abstract class just because some of the inheritors need it. That would be a signal that another abstract class could be needed in the inheritance tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜