# The Amazing FunctionMap!

January 24, 2011

FunctionMap is a handy class that allows a set of object transformations to be mapped at run time without having to define a bunch of extra interfaces and without having to evaluate the transformations at the time the mapping is created. Suppose we have an object:

class NumberPair {
double a;
double b;
}

and we want to define two transformations of the object, “multiplication” and “addition,” and be able to map these transformations to a set of keys. Normally we’d have to define two classes and a common interface:

abstract class NumberPairTransformation {
protected NumberPair numberPair;
NumberPairTransformation(NumberPair numberPair) {
this.numberPair = numberPair;
}
abstract double getValue();
}

class Multiplication extends NumberPairTransformation {
double getValue() { return numberPair.a*numberPair.b; }
}

double getValue() { return numberPair.a+numberPair.b; }
}

and create a map

static Map<String,Double> getNumberPairMapping(NumberPair numberPair) {
Map<String,Double> map = newHashMap();
map.put("multiplication", new Multiplication(numberPair).getValue());
return map;
}

with a FunctionMap we can do the same thing with:

static Map<String,Double> getNumberPairMappingBetter(NumberPair numberPair) {
return FunctionMapFactory.<NumberPair,String,Double>factory()
.withMappedObject(numberPair)
.withMapping("multiplication", new Function<NumberPair,Double>() {
public Double apply(NumberPair numberPair) {
return numberPair.a*numberPair.b;
}
})
}