Is it better to put a default implementation of a method in a superclass, and override it when subclasses want to deviate from this, or should you just leave the superclass method abstract, and have the normal implementation repeated across many subclasses?
For example, a project I am involved in has a class that is used to specify the conditions in which it should halt. The abstract class is as follows:
public abstract class HaltingCondition{
public abstract boolean isFinished(State s);
}
A trivial implementation might be:
public class AlwaysHaltingCondition extends HaltingCondition{
public boolean isFinished(State s){
return true;
}
}
The reason we do this with objects is that we can then arbitrarily compose these objects together. For instance:
public class ConjunctionHaltingCondition extends HaltingCondition{
private Set<HaltingCondition> conditions;
public void isFinished(State s){
boolean finished = true;
Iterator<HaltingCondition> it = conditions.iterator();
while(it.hasNext()){
finished = finished && it.next().isFinished(s);
}
return finished;
}
}
However, we have some halting conditions that need to be notified that events have occurred. For instance:
public class HaltAfterAnyEventHaltingCondition extends HaltingCondition{
private boolean eventHasOccurred = false;
public void eventHasOccurred(Event e){
eventHasOccurred = true;
}
public boolean isFinished(State s){
return eventHasOccurred;
}
}
How should we best represent eventHasOccurred(Event e)
in the abstract superclass? Most subclasses can have a no-op implementation of this method (e.g. AlwaysHaltingCondition
), while some require a significant implementation to operate correctly (e.g. HaltAfterAnyEventHaltingCondition
) and others do not need to do anything with the message, but must pass it on to their subordinates so that they will operate correctly (e.g. ConjunctionHaltingCondition
).
We could have a default implementation, which would reduce code duplication, but would cause some subclasses to compile yet not operate correctly if it wasn't overridden, or we could have the method declared as abstract, which would require the author of every subclass to think about the implementation they were providing, although nine times out of ten it would be a no-op implementation. What are the other pros and cons of these strategies? Is one much better than the other?
One option is to have another abstract subclass, to use as the superclass for all implementations which do want to use the default implementation.
Personally I usually leave non-final methods abstract in an abstract class (or just use interfaces instead) but it definitely depends on the situation. If you have an interface with many methods, and you want to be able to just opt in to some of them, for example, then an abstract class which implements the interface in a no-op way for every method is fine.
You need to evaluate each case on its merits, basically.