Domanda

I'm implementing a service class having a method like this:

public void makeSomething() {

    // some logic...

    // [optional logic]

    // some other logic...
}

This is a concrete class and it can be instantiated and used "as is", but I somethimes need to extend it and override the makeSomething() method adding some additional logic (in the middle). I mean: I need to use the same logic in parent method, but i need to extend logic before return.

My first idea was to add an "optional" method in the middle of the original method:

public void makeSomething() {

    // some logic...

    optionalOperation();

    // some other logic...
}

and eventually override the optionalOperation() method in extending classes. But I don't like this: I will have an empty method doing nothing in my original class...

So, is there a better way to design my method? Is there some design pattern addressing my issue?

È stato utile?

Soluzione

The design pattern is called Template method and it works exactly the way you don't like, I'm afraid.

For example, Spring's code is full of such empty protected methods waiting for you to add something custom into them.

Altri suggerimenti

i can think of 2 ways:

  • inheritance and common 'lifecycle' aka Template Method. it's very problematic to maintain when it's in the middle of your business logic
  • strategy pattern. try to refactor and pass strategy to the method or object owning this method. if you can use any functional language you can take it to the extreme and instead of passing strategy use a function composition: define 'makeSomething' as a function of other functions. and one of 'makeSomething' will contain also 'optionalOperation' in it's definition. but it may require really heavy refactoring

A simple solution would be this:

public class AClass {

    public void makeSomething() {
        someLogic();
        someOtherLogic();
    }

    protected void someLogic() {
        System.out.println("some logic");
    }

    protected void someOtherLogic() {
        System.out.println("some other logic");
    }

}


public class AnEnhancedClass extends AClass {

    @Override
    public void makeSomething() {
        someLogic();
        System.out.println("optional operation");
        someOtherLogic();
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top