4

Let's say we have an interface Foo with a method "public void someMethod()", and we have one or multiple abstract classes that "implement" Foo but don't necessarily themselves provide an implementation for someMethod().

Would it be good design to put for example "public abstract void someMethod()" in these abstract classes, or would it just be more effort for no good reason?

P.S. My programming language in question is Java, just in case that influences the answer.

2
  • 3
    It can reaffirm what needs to be implemented in the subclass without requiring the programmer to look through all interfaces to see what is missing Jan 5, 2015 at 13:01
  • 1
    @ratchetfreak While this is true, modern IDEs tend to have a facility to generate stubs for abstract methods in the superclass, which means the programmer rarely needs this information himself these days.
    – Jules
    Jan 6, 2015 at 10:09

2 Answers 2

6

No. This is just duplicate code that provides no benefit, unless you're specializing the interface for that abstract base class.

It could be argued that by having the method explicitly declared helps things be more readable, but I would argue that it should be clear by the interface declaration what is going on. If it's not, then your interface needs a better name and/or your abstract base class is doing too many things.

If all you're doing is duplicated code then you cause yourself more work up front, more work when it changes, and make it more likely that the abstract class gets out of sync with the interface, leading to two very similar distinct methods.

1
  • I have to agree with you for the most part. There is however one remedy against your statement about the abstract class getting out of sync, but that's only possible in my case because I use Java: the @Override annotation. In a more general sense this is of course not a solution.
    – dammkewl
    Jan 5, 2015 at 14:20
2

There are cases where it could be appropriate.

Consider an abstract base class that contains a default implementation of InitializeSomeMethod(), and that method calls someMethod() but there exists no default implementation for someMethod. The base class can define someMethod as abstract, and thereby allowing it to be called by InitializeSomeMethod().

However if you access the object through it's interfaces and not the base class, and the base class does not need to access those methods or properties, then it isn't necessary to define them as abstract.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.