Avoiding redundancy in Composition pattern java

315 views Asked by At

I have two classes A and B. Now, I have B "has a" A relationship. So, the most trivial thing to follow here is the Composition pattern. Now, one of the field of B is an object of A. The problem is some of the fields of A and B are common. So, in this case, those fields will be redundant. I can't create an abstract class out of the common fields and make A and B inherit it because they are already extending some abstract class. What would be the best practice in this case?

2

There are 2 answers

0
Eran On BEST ANSWER

If A and B can't have a common base class, you can't put the common fields in such a class.

One way to avoid the redundancy is to create a third class C that contains the common fields of A and B, and let both A and B have a member of class C.

Such a re-factoring would make sense only if the common fields make sense as a separate class (i.e. that class would represent some real life object or concept and not just an arbitrary group of fields). Otherwise I'll keep the redundant fields.

For example, an Office and a Person probably wouldn't have a common base class (other than Object), but suppose both of them have properties such as street name, city, zip code, etc... You can easily see that these fields should be extracted to an Address class.

0
Dickens A S On

As you said that your A and B class already extended with an abstract class, You can try delegate the common fields with a non common function to differentiate it

For example

class B extends AbstractB {
     private String myField;
     public String getMyField(){
           return myField;
     }
}

class A extends AbstractA {
     private String myField;
     private B b;
     public A(B b){
        this.b = b;
     }
     public String getMyField(){
           return myField;
     }
     public String getMyBField(){
           return b.myField;
     }
}