Replacing Conditional Getters With Functional Programming in Java

1. Introduction

In this small article, we will have a look at how to efficiently write a code that runs a getter (or any other method) based on some input using functional programming.

2. Problem

Instead of explaining it in words, let me show you the code directly:

private int normalMethod(MyPojo pojo, Actions action) {
    if (action == Actions.ACTION1) {
        return pojo.getActionOne();
    } else if (action == Actions.ACTION2) {
        return pojo.getActionTwo();
    } else if (action == Actions.ACTION3) {
        return pojo.getActionThree();
    } else {
        return pojo.getActionFour();

As we can see, we are calling the appropriate getter based on the Action that we get in the input. This seems to be pretty decent at the moment, but as and when there are new actions/getters, we need to modify the code and the chain can grow longer.

3. Solution

One good solution to this is to make use of functional programming in Java. For this, we need to create a mapping of the Actions to method references:

public static final Map<Actions, Function<MyPojo, Integer>> GETTERS_MAP = new HashMap<>();
GETTERS_MAP.put(Actions.ACTION1, MyPojo::getActionOne);
GETTERS_MAP.put(Actions.ACTION2, MyPojo::getActionTwo);
GETTERS_MAP.put(Actions.ACTION3, MyPojo::getActionThree);
GETTERS_MAP.put(Actions.ACTION4, MyPojo::getActionFour);

As we can see, we have mapped every Action to the corresponding getters. Once this is done, our long if-else chain now reduces to only a couple of lines:

private Integer functionalMethod(MyPojo pojo, Actions action) {
    Function<MyPojo, Integer> getter = MyPojo.GETTERS_MAP.get(action);
    return getter.apply(pojo);

And that’s it. Even if we need to add another Actions/getters, we just need to add an entry in the Map. The method above doesn’t need to be modified.

4. Conclusion

We have observed that functional programming opens new doors of creativity. Please find the full source code of this article on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *