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