r/functionalprogramming • • Feb 14 '23

Question Can this method be more functional?

This is some Java code for a GUI component that changes text and color based on the state of an inner linked list. Can it be more functional style?

   private void render() {
        if (listIsEmpty())
            configureLayout(State.EMPTY);

        else if (allEqual())
            configureLayout(State.ALL_EQUAL);

        else if (isSortedAscending())
            configureLayout(State.ASCENDING);

        else if (isSortedDescending())
            configureLayout(State.DESCENDING);

        else
            configureLayout(State.UNSORTED);
    }

EDIT: I refactored the previous code to the following. Is it better already?

   private void render() {
        configureLayout(determineState());
    }

    private State determineState() {
        if (listIsEmpty()) return State.EMPTY;
        if (allEqual()) return State.ALL_EQUAL;
        if (isSortedAscending()) return State.ASCENDING;
        if (isSortedDescending()) return State.DESCENDING;
        return State.UNSORTED;
    }
4 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/raulalexo99 Feb 14 '23

The code already works nice and fine, I am just trying to get better at FP because I find the concepts fascinating. But yes, I have somewhat learned that Java needs a lot of extra setup code to work in a functional manner, compared to Haskell or Clojure.

4

u/[deleted] Feb 14 '23

Then what you could do here is write a method that accepts an array and returns one of the state constants. In functional programming, you don't have global state. You only deal with the values that are given to the function. There's not much else you can do

2

u/raulalexo99 Feb 14 '23

Yeah youre right, thanks