Experimenting with my code I was wondering is there any way to "compress" it more (one-liner is an ultimate goal).
vanilla java:
public void setUsingSwitch(Field field, String value) {
switch (field) {
case FIRST_NAME:
setFirstName(value);
break;
case LAST_NAME:
setLastName(value);
break;
default:
throw new IndexOutOfBoundsException("Unknow field " + field);
}
}
"compressed":
public void setUsingConsumer(Field field, String value) {
Consumer<String> setter = field == FIRST_NAME ? this::setFirstName : field == LAST_NAME ? this::setLastName : v -> {
throw new IndexOutOfBoundsException("Unknow field " + field);
};
setter.accept(value);
}
For both used:
public static enum Field { FIRST_NAME, LAST_NAME }
void setFirstName(String value) { }
void setLastName(String value) { }
Of course it is just scientific interest for me but is there any way to write even smaller code?
Here's an alternative approach which is not shorter, but sometimes preferable: