Sharing code between Action classes is easy if you use Inheritance and put all the common code and properties into a Base class. As a best practice, I think the rule of thumb is to prefer composition over inheritance. I'm finding it extremely hard to apply this concept to Action classes, though. Perhaps I'm not doing it right.
For instance, I have 3 different Action classes. They all handle different ways a user may register (A user can register from more than 1 form) They all ultimately call the same service method and need to handle the errors the same way. The common code would like something like:
public class RegisterAction1 {
public String execute() {
...Leaving out code here....
try {
registrationService.register(user);
} catch (BusinessException e) {
if(e.getErrors().containsKey("someError3)){
return "Case1";
}
else if (e.getErrors().containsKey("someError1")) {
session.put(Constants.SESSION_REGISTERVO, registerVO);
return "Case2";
} else if(e.getErrors().containsKey("someError2")) {
this.addFieldError("aliasName", this.getText("some.error"));
} else if(ce.getErrors().containsKey("someError3")) {
this.someFieldThatMustBeSetForView1 = true;
this.someFieldThatMustBeSetForView2 = true;
this.addFieldError("addressLine1", null);
this.addFieldError("addressLine2", null);
this.addFieldError("city", null);
}
}
...Leaving out code here....
return "Success";
}
}
To use composition I would think that you would move this piece of logic into a "Helper" class and have a reference to that Helper in the Action class. If you were to create a "callService" method in this helper class which implemented this common code, how would you handle the fact that a lot of the code is actually modifying fields on the class ... i.e., do you pass a reference to the Action to the helper method like the following? And if so, how do you handle the fact that it could be 1 of three different action classes (i.e., RegisterAction1, RegisterAction2, RegisterAction3)?
public String callService(RegisterAction1 registerAction) {