javavariablesmethodsgeneralization

Generalizing same set of methods to different variables


Greetings StackOverflow,

I have a question for you guys whether it is possible, and if so how, to generalize same set of methods do different set of variables?

Let's illustrate this with an example: assume we have variables, which ALL have the same methods declared. In this simple case, let's say that 2 variables have setters and getters set such as this:

private LinkedList football = new LinkedList();
private LinkedList jogging = new LinkedList();

public LinkedList getFootball() {
    return football;
}
public void setFootball(LinkedList football) {
    this.football = football;
}
public LinkedList getJogging() {
    return jogging;
}
public void setJogging(LinkedList jogging) {
   this.jogging = jogging;
}

Now let's say that there is a certain type of input which determines which of this variables will be taken and their methods invoked. It is crucial to mention that these methods have the same action, only to a different variable. One way (the simplest) how to do this would be via if-statement as follows:

String input;

if (input.equals("football")) {
    getFootball();
}

if (input.equals("jogging")) {
    getJogging();
} 

If we have a long list of variables, this code becomes long and rather tedious. Is there a way to generalize this code and make it less repetitive, for example something simmilar as this (I realize this won't work):

String input = X;
if (getX == true) {
     return X;

Thank you for your answers!


Solution

  • The easiest way to do this would be using a map:

    public static final String footballStr = "football";
    public static final String joggingStr = "jogging";
    
    private Map<String, LinkedList> sports = new HashMap<>();
    {
        sports.put(footballStr, new LinkedList());
        sports.put(joggingStr, new LinkedList());
    }
    
    public LinkedList getSportsByInput(String key)
    {
        if (sports.containsKey(key))
        {
            LinkedList ll = sports.get(key);
    
            //...
        }
    }
    

    Like this the user of this class can use the static strings (fixed strings reduce error possibilities) and you can add new sports easily


    Sidenote:

    LinkedList<> works with generics and should be parameterized. (like LinkedList<String> or whatever class they're holding)