Default implementation or abstract method?
Asked Answered
T

5

36

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?

Trave answered 29/8, 2010 at 17:11 Comment(0)
M
21

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.

Manipular answered 29/8, 2010 at 17:16 Comment(2)
What does 'no-op' mean? Sorry, this is a language barrier to a non-native speaker like me.Yeomanry
@ShadowGames: I would suggest searching when you see a technical term you don't understand. The top search result I got seems pretty reasonable here: noop.com.au/noop-meaningManipular
C
1

It sounds like you are concerned about setting that boolean variable when the event happens. If the user overrides eventHasOccurred(), then the boolean variable will not be set and isFinished() will not return the correct value. To do this, you can have one abstract method which the user overrides to handle the event and another method which calls the abstract method and sets the boolean value (see the code sample below).

Also, instead of putting the eventHasOccurred() method in the HaltingCondition class, you can just have the classes that need to handle events extend a class which defines this method (like the class below). Any class that does not need to handle events can just extend HaltingCondition:

public abstract class EventHaltingCondition extends HaltingCondition{
  private boolean eventHasOccurred = false;

  //child class implements this
  //notice how it has protected access to ensure that the public eventHasOccurred() method is called
  protected abstract void handleEvent(Event e);

  //program calls this when the event happens
  public final void eventHasOccurred(Event e){
    eventHasOccurred = true; //boolean is set so that isFinished() returns the proper value
    handleEvent(e); //child class' custom code is executed
  }

  @Override
  public boolean isFinished(){
    return eventHasOcccurred;
  }
}

EDIT (see comments):

final EventHaltingCondition condition = new EventHaltingCondition(){
  @Override
  protected void handleEvent(Event e){
    //...
  }
};
JButton button = new JButton("click me");
button.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent actionEvent){
    //runs when the button is clicked

    Event event = //...
    condition.eventHasOccurred(event);
  }
});
Climax answered 29/8, 2010 at 17:35 Comment(4)
That's a nice solution, but not to the problem I have. I'm not worried about access to a particular field - it's ensuring that an event is handled. That might be by setting a flag, or it might be doing something else - starting a timer, for instance. In short, it's entirely implementation-specific.Trave
What kind of events are we talking about? For example, if the event were a button press, then you would simply call eventHasOccured() in the button's ActionListener (see edited answer for code example).Climax
The events are fairly arbitrary. An example might be when the program starts processing or a particular stage of processing is reached. They're unlikely to be UI actions. I like the idea of attaching it as an observer before stuffing it down the chain, although it wouldn't be able to survive serialisation.Trave
I guess I don't really understand your problem. My understanding is that you could simply call eventHasOccurred() whenever the event has happened. For example, in the event of the program starting some processing task like you suggested, you would call this method right before the processing takes place. To make a class serializable, you just have to have it implement the java.io.Serializable interface.Climax
C
1

If you are going to put any implementation in the abstract base class, it should be the code for the sub-classes that use the no-op implementation, since this is an implementation that makes sense for the base class as well. If there were no sensible implementation for the base class (e.g., if there was no sensible no-op for the method you're discussing here), then I'd suggest leaving it abstract.

With respect to duplicated code, if there are "families" of classes that all use the same implementation of the method and you don't want to duplicate the code across all classes in the family, you might simply use helper classes per family that supply these implementations. In your example, a helper for classes that pass down the events, a helper for classes accept and record the event, etc.

Currie answered 29/8, 2010 at 17:39 Comment(0)
Z
1

I encountered a similar scenario when I created the basic outline (class hierarchy) of an application I was developing together with others at work. My choice for placing a method abstract (and consequently to force its implementation) was for communication purposes.

Basically the other team mates had somehow to explicitly implement the method and therefore first of all notice its presence and second agree on what they return there, even if it is just the default implementation.

Default implementations in base classes often get overlooked.

Zuckerman answered 30/8, 2010 at 19:9 Comment(0)
G
0

If you are leaving the super class method abstract you may want to look into utilizing an Interface (not to be confused with an interface). As the Interface is one that does not provide a concrete implementation.

Scott

To expand, when we as programmers are instructed to code to an interface often times new, and sometimes experienced, developers will assume incorrectly that it is in reference to the keyword Interface wherein no implementation details may be found. However, the more clear way of saying this is that any top level object can be treated as an interface which can be interacted with. For instance an abstract class called Animal would be an interface would a class called Cat that would inherit from Animal.

Gynecocracy answered 29/8, 2010 at 17:28 Comment(6)
I am not familiar with an "Interface" (not to be confused with an "interface" which I am familiar with). Can u provide a link?Unity
Please do expand. The only Java interfaces I know of cannot provide any implementations.Trave
I don't see an Interface class anywhere in the API.Climax
@mangst Interface is a java keyword to denote a certain object wherein no method implementations may be provided.Gynecocracy
Re: expansion. I take it you mean polymorphism i.e. the ability of an object to be treated as if it is a member of another class - typically a superclass. I don't see how this solves the problem of where to put the implementation. Arguably, it's the source of it.Trave
Scott: I don't mean it to be polymorphism, at least in the purest sense of the term interface. In my example I could see how it is perceived to be polymorphism. In the sense of where to put the implementation isn't really a problem per se as each object should have specialized functionality as needed, however if it is possible to allow an object to represent an interface than obviously that is where the implementation should go.Gynecocracy

© 2022 - 2024 — McMap. All rights reserved.