Search code examples
javagetter

Performant selection of correct getter based on a string


I have a list of strings which relate to particular values to be retrieved (e.g. volume, weight,...). I receive this list from a query received via an HTTP API endpoint.

Also, there is a class which not only stores volume and weight but also size and time. The class has getters for all these fields.

I am looking for a generic method to collect a value based on the string in the list.

So far, I did:

public double getValue(String fieldName) {
switch(fieldName) {
case "volume":
    return getVolume();
case "weight":
    return getWeight();
case "size":
    return getSize();
case "time":
    return getTime();
default:
    throw new IllegalArgumentException("error");
}

Is there a better way to dynamically return a value given a string? Performance is crucial because this generic method is invoked at high frequencies.


Solution

  • You can put the values in a Map:

        Map<String, Double> fieldValues = new HashMap<>();
        fieldValues.put("volume", getVolume());
        fieldValues.put("weight", getWeight());
        fieldValues.put("size", getSize());
        fieldValues.put("time", getTime());
    

    and then retrieve them by id:

    public double getValue(String fieldName) {
        return fieldValues.get(fieldName);
    }
    

    If values change a better approach as Jon suggested is to use a supplier:

    Map<String, Supplier<Double>> fieldValues = new HashMap<>();
    fieldValues.put("volume", () -> getVolume());
    fieldValues.put("weight", () -> getWeight());
    fieldValues.put("size", () -> getSize());
    fieldValues.put("time", () -> getTime());
    
    public double getValue(String fieldName) {
    
        if (!fieldValues.containsKey(fieldName)) {
            throw new IllegalArgumentException("error");
        }
    
        return fieldValues.get(fieldName).get();
    }