Xaisoft
Xaisoft

Reputation: 46651

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 code 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.

Upvotes: 0

Views: 239

Answers (2)

František Žiačik
František Žiačik

Reputation: 7614

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.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

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.

Upvotes: 2

Related Questions