r/functionalprogramming • u/raulalexo99 • 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
View all comments
Show parent comment
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