Avoiding redundancy in java composition structure

I have two grades A and B. Now I have a relationship B "has a" A

. So, the most trivial for us is the compositional picture. Now one of the fields B is object A. The problem is that some of the fields A and B are common. Thus, in this case, these fields would be redundant. I cannot create an abstract class from common fields and make A and B inherit from it, because they are already extending some abstract class. What would be the best practice in this case?

+3


source to share


2 answers


If A and B cannot share a common base class, then you cannot put common fields in such a class.

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



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

For example, Office

and Person

probably won't have a common base class (except Object

), but suppose they both have properties like street name, city, zip code, etc ... You can easily see that these fields are should be checked out to class Address

.

+3


source


As you said your class A and B are already extended with abstract class, you can try to delegate common fields with 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;
     }
}

      

0


source







All Articles