I have an abstract base class which looks like this:
public abstract class AbstractConfig {
public String someMethod(List<Params> params) {
if (inputValidationFails()) { /* sanity check of params */
return null;
}
return something;
}
}
And I have subclasses that perform the same input validation.
public class CustomConfig extends AbstractConfig {
@Override
public String someMethod(List<Params> params) {
if (inputValidationFails()) { /*same input validation code*/
return null;
}
return somethingElse;
}
}
How can I avoid having to implement this input validation in base class as well in every subclass?
Implementing [non-private] helper method inputValidationFails()
inAbstractConfig
and calling it in base class and in every sub class doesn't seem particularly good or clean.
I suggest you split your method into two separate method, one public method which you implement in your base class and a protected abstract method which is called by the other method and which is implemented in the sub classes.
This way you can implement things which apply to all subclasses in the base class and avoid code duplication. The resulting base class would look something like this:
public abstract class AbstractConfig {
public String doStuff(List<Params> params) {
if (performErrorChecks()) {
return doTheActualStuff(params);
}
return null;
}
protected abstract String doTheActualStuff(List<Params> params);
}
And the subclasses would just implement doTheActualStuff()
:
public class CustomConfig extends AbstractConfig {
@Override
protected String doTheActualStuff(List<Params> params) {
...
}
}
You can also declare doStuff()
as final
in AbstractConfig
. This would additionally prevent any subclass from overriding doStuff()
and accidentally replacing your common error checking.