I have some repetitive code that is used by a few of my actions in Struts 2.
Ne开发者_StackOverflowedless to say I want to have this code only exist in one place, so I will collect it up into a method and put it ... where?
What is the best practice? Do I create a helper class for each type of helper method? One big helper method? One big static class? A few static classes?
I'm using MVC.
I've read other answers on stackoverflow and none seem to quite answer my question.
Many thanks for your help.
EDIT update with examples, as requested:
For instance:
I have a couple of lines of code that adds an arraylist to the session, which stores when a certain object has been 'rated' (for that session). Its called in a few actions across the application.
Also, I have a view component that is included on multiple JSP pages, and needs to be loaded with some data from the model. I would need to copy/paste the code into each action (obviously want to avoid this).
Hope that clarifies. Please let me know if it does not.
My general rule is that if the methods are computational, in other words if they just perform a function (like math), I will create a class with static methods and use it all over the place.
I have a utility package that I include in a lot of my projects as a jar with string manipulation and validation functions for instance because they rarely change.
String validation is a good example. I have a Validation class that I use a lot to check for null or empty strings and return a boolean. I just call it from my action classes like:
if(Validation.string(value)){
// do magic - huzzah
}
I try to group utility methods into classes especially if I use then all over the place. It tends to save me from re-typing, searching through classes for a good idea I had whenever, and provides a single instance of the code in case I need to update, modify, overload, or override.
For view components included in multiple JSP pages and objects saved to session, I've created a base action class and sub-action classes to avoid repetitive code.
public class BaseAction extends ActionSupport implements SessionAware {
protected Map session;
protected ResourceBundle rb;
// common getters for shared view components and common setters
...
}
--
public class SubAction extends BaseAction {
...
精彩评论