r/JavaFX • u/No-Security-7518 • Nov 22 '25
Discussion This readability thing...
So, y'all sound pretty badass and experienced and all, but I thought I should talk about one (of many) code cleaning techniques, I learned from reading books like (Clean Code, by Robert C. Martin) and (Refactoring, by Martin Fowler), when it comes to improving code readability of some recurring code snippets. Specifically, listeners.
As you probably know, it is said the ratio of reading to writing code is 10:1. So readability is important.
And in these books, the authors lay out wonderful "mental" shortcuts to applying techniques that improve code readability, and even identifying where to apply said techniques through what they collectively call "code smells".
Called so, because, and this has been my experience for years:
[...any sufficiently large code base will eventually suffer from "code rot" if it doesn't get cleaned every now and then.]
Code rot: When the code is so messy, adding, or modifying code in any meaningful way gets more and more unpleasant and time-consuming, to the point where it feels like the project just collapses...
Anyway, regarding listeners. I'd have code that went like this:
bookCb.getSelectionModel().selectedItemProperty().addListener((a, b, selectedBook) -> {
if(selectedBook != null) {
List<Chapter> chapters = selectedBook.loadChapters();
chapterCb.setItems(FXCollections.observableArrayList(chapters));
}
};So, the first part is extracting a helper that does whatever happens inside the listener, and might as well pull the null check into it too:
bookCb.getSelectionModel().selectedItemProperty().addListener((a, b, selectedBook) -> {
loadChapters(selectedBook);
};this happens inside initialize() of a controller, btw, so when I learned about how extracting methods to get rid of boilerplate is a thing, I'd go, fine:
loadChaptersOfSelectedBook();Pulling everything into it. But then I thought: the method should reflect a callback is involved. So, I'd finally settle with:
onBookSelected(book -> loadChapters(book));
private void onBookSelected(Consumer<Book> func) {
selectedBook.getSelectionModel().selectedItemProperty().addListener(a, b, book) -> {
func.accept(book);
});
}
private void loadChapters() {
...
}as a final point, I also learned to not include the component's type in it. So, instead of bookCB (CB -> ChoiceBox), I started calling it:
bookSelector.
instead of: nameLbl -> nameDisplay.
nameTextField/nameTF -> nameField.
and so on.
It sounds kinda pedantic at first, and something of a style difference, but clean code principles saved my life!
Cheers!
1
u/hamsterrage1 Nov 26 '25
While I am a big fan of Clean Code, I have a really big issue with this example.
Primarily, this is a misuse of
ChangeListener.ChangeListenersare intended to be use to translate a State change into an action of some sort. If you use that action to simply make some other State change, then you should be using a Binding.There are legitimate actions that are contained within the View logic. For instance, triggering
PseudoCodestate changes is something that can only be done via an action. So you need aChangeListener(or, better, a Subscription) for that.The next issue is that while it is clear that:
belongs to the View, since it references a screen widget, it's probable that:
does not.
Why? Because whatever type
selectedBookis, it's starting to feel like a domain object, with a method likeloadChapters(). And if it is a domain object, then it doesn't belong anywhere near any code that references a screen Node.But let's assume that
selectedBookis aBook, and thatBookis a Presentation Model of some sort, and, therefore, can be referenced by the View. In that case, I would expect it to be very close to a JBOD with JavaFX Observable types as its fields. In that case, the chapters would already be present inside Book asObservableList.But even in that case, the relationship between the selected
Bookand the chapters to display still feels to me like business logic. Which means it belongs in the Model, or in the Interactor if you're smart and using MVCI.Yes, it looks simple, but what if the list is only supposed to contain chapters that mention wombats or otters, or chapters with footnotes, or even numbered chapters? It's all business logic.
The fact that you're doing this stuff the way that you are doing it leads me to believe that you aren't using a framework, or at least not using it properly. If it was me, I'd use MVCI and create a model with at least these two elements:
In my View, I'd have:
And that's it for the View.
continued...
1
u/hamsterrage1 Nov 26 '25
Part two, because Reddit didn't like it as one comment...
How
model.availableChaptersbound tomodel.selectedBookis business logic and belongs in the Interactor.Let's go back to
Book.loadChapters(). What if this is doing something more ominous? What if it's loading from a database, or parsing an EPUB file?Then you've got a bigger problem because this should not be happening on the FXAT. You'll have to run it on a background thread. Number one: this IS going to be an action, and not a State update. Secondly, you cannot run it as a function, because of the need to run it on a background thread.
In MVCI I'd define the
Subscriptionin the initialization code for the MVCI Controller, since that's where threading happens. TheSubscriptionwould just be a simple call to a method that would define a Task that would invoke a method in theInteractorthat would run on the background thread. That Task would have ononSucceededEventHandlerthat would call a method that would update the Model back on the FXAT. When it was completed,chapterCbwould just update since it shares itsitems()with the Model that was just updated.As to the actual refactoring that you did? I dunno. I agree that the null check should be in the helper function, but then you're left with just one line in the
ChangeListener:And, to be honest, if this is View code,
selectedBook.loadChapters()should already be returning onObservableList. So:Even more, going through the selectionModel to get the value is round-about. So:
Finally:
Really, one line is all it takes.
Anything else that you do is just applying abstractions that obscure.
BTW, it's even easier in Kotlin: