Reputation: 691
I need to implement two similar processes which basicaly do the same logic but a few parameters/methods may differ. I'm wondering if it would be a good practice to extract the main logic to a parent class and specify a result of a few methods to child classes. Something like:
abstract class Parent{
protected CommonDao commonDao;
protected String specStatus;
protected abstract int getDbResult();
public Parent(CommonDao commonDao){
this.commonDao = commonDao;
}
public String mainLogic(){
if(commonMethod()){
//..
}
int specDbResult = getDbResult();
//some logic here
return specStatus;
}
private boolean commonMethod(){
//..
return true;
}
}
@Service
public Child1 extends Parent(){
@Autowired
public Child1(CommonDao commonDao){
super(commonDao);
super.specStatus = specStatus1;
}
@Override
protected String getDbResult(){
commonDao.getResult1();
}
}
@Service
public Child2 extends Parent(){
@Autowired
public Child2(CommonDao commonDao){
super(commonDao);
super.specStatus = specStatus2;
}
@Override
protected String getDbResult(){
commonDao.getResult2();
}
}
If it doesn't seem to be a clean code, what solution would you recommend in such case? Thanks in advance
Upvotes: 1
Views: 169
Reputation: 155
Using Dependency Injection, composition seems clearly a better approach that inheritance
And dao as an attribute is not enough for a parent child relationship
Please make sure you have understood Item 16 of Effective Java, as any programmer might http://thefinestartist.com/effective-java/16
EDITED as requested:
@Service
public class NotAChild{
@Autowired
CommonOps1 commonOps1;
@Autowired
CommonOps2 commonOps2;
private boolean commonMethod(){
int result1 = commonOps1.getDbResult();
int result2 = commonOps2.getDbResult();
....
return result1 + result2;
}
}
@Component
public class CommonOpS1{
@Autowired
CommonDao commonDao;
protected String getDbResult(){
commonDao.getResult1();
}
}
@Component
public class CommonOpS2{
@Autowired
CommonDao commonDao;
protected String getDbResult(){
commonDao.getResult2();
}
}
All other NotAChildN objects can use the common methods of CommonOps.
So, you won't use inheritance
Upvotes: 0