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
3
u/raulalexo99 Feb 14 '23 edited Feb 14 '23
Okay thanks to your answer I came up with a somewhat FP equivalent of this in Java. It requires a lot of code but it is kinda what I was looking for. This may not be worth it because of the amount of code and I think I might just use the easy multi - if method. Anyways for those interested, here is the solution:
This is the full code of the class inside my project for anyone interested: https://github.com/AlexAnguloMtz/Linked-Lists-Desktop-GUI/blob/master/src/main/java/com/demo/list/view/components/SortingState.java
It works but it looks kinda cluttered... but hey, it's Java