lundi 12 juin 2023

Decouple parent class dependencies from child's dependencies

I have a parent class, let's call it BaseClass

And I have multiple child classes extending this BaseClass. These child classes overrides some of the methods of the BaseClass.

public class BaseClass {

}

public class ChildA extends BaseClass{

}
....

public class ChildN extends BaseClass{

}

Now, I have logic in BaseClass which keeps on changing quite often. This usually leads to adding dependencies for the BaseClass - the constructor arguments of this BaseClass keeps on increasing.

public class BaseClass {
  public BaseClass(BaseDependencyOne one, BaseDependencyTwo two...., BaseDependencyN n) {
  }
}

public class ChildA {
  public ChildA (BaseDependencyOne one, BaseDependencyTwo two,..., BaseDependencyN n){
    super(one, two,..., n);
  }
}

Since, the BaseClass constructor is modified to accommodate more dependencies, the child classes also have to accommodate these dependencies. This involves making change in all child classes, which are very large in number. This in turn results in a huge change for a single addition of dependency in BaseClass

I thought of making the parent BaseClass as a dependency for all child classes. It will decouple the dependency of parent from child. But, this will break the parent-child relation ship, therefore, I won't have the overriding behaviour of child.

Aucun commentaire:

Enregistrer un commentaire