开发者

Default implementation or abstract method?

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 correc开发者_StackOverflow中文版tly 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.


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.


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);
  }
});


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜