dimanche 1 septembre 2019

Pros/cons of either implementaion

Say i am implementing a simple interface like Animal. Broadly speaking, there are two ways to go about doing that:

  1. implement the interface's method in the abstract class, and create abstract methods for any implementation specific logic needed.
  2. implement the interface method in the concrete classes, and move the common logic in the abstract class with protected access.

I'd like to understand if there are any objective benefits of one way over the other in terms of design.

public interface Animal {
    void makeSound();
}


public abstract class BaseAnimal {
    @Override
    public void makeSound() {
        //do something which is common for all implementaions
        doSomeImplementaionSpecificStuff();
    }

    public abstract void doSomeImplementaionSpecificStuff();
}

public class Dog extends BaseAnimal implements Animal {
    public void doSomeImplementationSpecificStuff(){
       //do something specific to a dog
    }
}

public abstract class BaseAnimal {
    public void doCommonStuff() {
        //any common logic that can be shared between concrete  implementation goes here
    }
}

public class Dog extends BaseAnimal implements Animal {
    @Override
    public void makeSound() {
       doCommonStuff();
       //do something specific to a dog
    }
}


Aucun commentaire:

Enregistrer un commentaire