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
11
u/[deleted] Feb 14 '23 edited Feb 14 '23
You're dealing with state in Java. I don't know if there's a less appropriate place to attempt a functional approach. Java is so unfriendly to functional programming, they created scala
Can you articulate the problem you have with the code?
Edit: Java isn't just unfriendly to functional programming. It's anti-functional. There probably are some, but i can't think of a language more hostile to functional concepts, at least not with such widespread adoption....i guess C comes close but it's not as explicitly intentional as Java
8
u/ImaginaryKarmaPoints Feb 14 '23
There's a variety of approaches you could take.
One would be to define a Test Function -> State mapping list.
Your various test functions look like globals, I would change them to accept the list as input. (In general, functions and data should be decoupled by having the functions accept all needed data as inputs)
I'm not familiar with Java, but in Javascript I might do something like:
You could take things further and make determineState more generic, accepting both the test array and the list as inputs, then curry it to allow creating the more specific function, e.g.
3
u/OleAndreasER Feb 14 '23
listIsEmpty()
5
u/acute_elbows Feb 14 '23
FP zealots will say that Java is anti-FP but FP isn’t a religion, it’s a series of programming practices that when combined tend to produce code that is easier to reason about and less prone to bugs.
So yes Java isn’t aligned well with FP, but we can still extract elements of FP as best practices for Java. For instance: it’s best to avoid mutating objects that are passed between contexts so as to avoid side effects. There are a lot of places in Java that this is unavoidable, but you can practice it in your code.
3
u/Rogntudjuuuu Feb 15 '23
Have a look at Kevlin Henney's talk about refactoring to immutability. Immutability is at the core of FP, although not a necessity. It will force you to think in FP.
Try to make a for-loop with immutable variables, then you'll understand.
https://youtu.be/APUCMSPiNh4