Is this UML diagram violating the Interface Segregation Principle?

132 views Asked by At

I have created this UML diagram which applies the Template method design pattern: UML diagram

Both concrete classes share a lot of the logic whithin the template methods createTask and completeTask, with small variations for each concrete implementation, so I went for the Template method design pattern. However, one of the concrete classes does not need validation, so it implements the abstract method performValidations as an empty void method.

Is this violating the Interface Segregation Principle? Or would it be OK in this situation to leave the implementation of this abstract method in the concrete class empty?

2

There are 2 answers

3
atish.s On

The basic idea of Interface Segregation Principle is that the concrete classes implementing the interface/extending an abstract class must not be forced to proivde an implementation for methods that are not relevant to them. In your case, performValidations is not exactly relevant for all the subclasses but yet they need to provide an implementation for it; so it is indeed violating that principle.

Without having much context on the use case of your domain, this would be my recommendation.

You could promote performValidations to be implemented with an empty implementation body in the abstract class itself. Whoever needs to do some validation just overrides the method performValidations and provide their own implementation.

Maybe a neater solution would be to have an interface Task as such which defines the basic idea of a Task.

public interface Task {
    /**
     * Perform steps required to create a task
     * @return true if all the steps have executed successfully.
     */
    boolean createTask();

    /**
     * Perform validations required for a task.
     * @return true if validations are successful.
     */
    default boolean validateTask(){
      return true;   
    }

    /**
     * Perform steps required to complete a task
     * @return true if all the steps have executed successfully.
     */
    boolean completeTask();
}

Introducing a method executeTask would make sense as well.

2
StepUp On

Is this violating the Interface Segregation Principle? Or would it be OK in this situation to leave the implementation of this abstract method in the concrete class empty?

No, it is not the violation of the Interface Segregation Principle. What you have implemented is also known as hook in Template Method design pattern.

Hook is:

A hook is an optional step with an empty body. A template method would work even if a hook isn’t overridden. Usually, hooks are placed before and after crucial steps of algorithms, providing subclasses with additional extension points for an algorithm