mercredi 6 janvier 2016

How to avoid having different methods looping the same list?

I have a class that is mapped from a xml. To make it simple, let's imagine this class is something like:

class Employee implements EmployeeIF {
    Map<AttributeIF,Object> attribute = new HashMap<>();
    @Override
    public Map<AttributeIF,Object> getAttributes() { return attribute; }
}

This is something I cannot change.

Now, the existing code is full of methods like:

public int getSalary(EmployeeIF employee) {
    for(Entry<AttributeIF,Object> entry : employee.getAttributes()) {
        if(entry.getKey().getName().equals("salary")) return (Integer)entry.getValue();
    }
    return 0;
}

public int getAddress(EmployeeIF employee) {
    for(Entry<AttributeIF,Object> entry : employee.getAttributes()) {
        if(entry.getKey().getName().equals("address")) return (String)entry.getValue();
    }
    return "";
}

... and so on. Surely you got the idea.

I need to include a new method to return a new attribute from the employee, but as I feel this is horrible to mantain, I refuse to just add a new method there. I am thinking on using the action pattern to somehow avoiding at least repeating againg and again the for loop but I have to say that I cannot find a smart solution for this.

What would be your choices?

Thanks, Dani.

P.D Yes I tried something like

private Object getAttribute(EmployeeIF employee, String attribute)

Aucun commentaire:

Enregistrer un commentaire