Reduce code duplication without subclass inheritance

I play with subclassing and interfaces and composition. I ended up getting confused in a few things when it comes to code duplication. As we all know, there are many scenarios in which subclasses and inheritance are simply not suitable, but they are effective in terms of reducing code duplication.

The interfaces are strong and give excellent readability if everything is done correctly, but I can’t wrap my head in that it really doesn’t help me with reducing code duplication. We may find ourselves in scenarios where the subclassification is not effective. But the possibilities of expanding the program are great, and whenever we do this, trying to maintain an open private director, we end up doing implementations / implementations of interfaces in absurd amounts of copy paste the code where it can probably be avoided with a subclass (from the point view of code duplication).

How do we create great strategies with interfaces and composition, where we avoid repeating the same methods? Thus, we can maintain modularity and adhere to the open closed principle at the same time. Do we have any recommendations on how we can quickly and efficiently decide if code duplication is really worth it?

Greetings

</WallOfText>

+4
source share
2 answers

Object-oriented modeling is very subjective, but the only thing I can say here is the old discussion of Inheritance and composition : https://www.thoughtworks.com/pt/insights/blog/composition-vs-inheritance-how-choose

, , , , . , , , is-a (.. - , - , - --). Java , , .

, , , -i-want-to-reuse, ().

, : - . , , Mammals ( ). , hunt() Mammals.

: Mammals < - HuntingMammals. : , . , , , .

, . , , , Hunter Dog, Lion (). (), CanHunt .

:

class Hunter {
   void hunt(){
       System.out.println("i'm hunting...");
   }
}

interface CanHunt{
   Hunter getHunter();
}

class Dog extends Mammals implements CanHunt{
   ...
   Hunter hunter = new Hunter();

   @Override
   Hunter getHunter(){
       return hunter;
   }      
   ...
}


class Lion extends Mammals implements CanHunt{
   ...
   Hunter hunter = new Hunter();

   @Override
   Hunter getHunter(){
       return hunter;
   }      
   ...
}

, , :

...
List<CanHunt> hunters = new LinkedList();
hunters.add(new Dog());
hunters.add(new Lion());

for(CanHunt h:hunters){
  h.getHunter().hunt(); //we don't know if it a dog or a lion here...
}
...

, . , , . , , - , .

+1

, , , , " ", , , .

- , -, , , , , . , "" .

, , @AntoineDubuis. , .

0

Source: https://habr.com/ru/post/1692888/


All Articles