74H1R
74H1R

Reputation: 3514

Is it a good practice to call Struts action through constructor in another action?

I have two Struts2 actions. I want to use a public method of a action in another action. Is it Ok that I can call an action through new operator and call its public method? (For the sake of reusing some common functionality)

public class OneAction extends ActionSupport{
public void doSomeThing(){
    // some code
}

public String execute(){
    // some code
}
}

 public class AnotherAction extends ActionSupport{

public String execute(){
    /* is it ok?*/
    new OneAction().doSomeThing();
}
}

Upvotes: 2

Views: 861

Answers (2)

Dave Newton
Dave Newton

Reputation: 160251

I plus-oned @duffymo's answer, but here's some more food for thought.

If the functionality is common across actions, it belongs in either a base action (if web-related), or a utility class (either web-related or not). Which makes the most sense depends a lot on context.

Along those contextual lines, depending on the actual functionality you're talking about, it might make more sense yet somewhere else--in an interceptor, an aspect, a mixin (how to do that depends on the implementation language), etc. Without knowing details, it's difficult to be more specific.

Upvotes: 2

duffymo
duffymo

Reputation: 308918

(shudder) I would not. I'd refactor the common functionality into a separate class that both can call. But that class would be a POJO, not an Action.

I'd be careful about embedding functionality in Actions. I think they're firmly in the web tier camp. You should do little more than validate and bind parameters into objects, hand them off to POJOs for processing, and package results for return.

Upvotes: 4

Related Questions