How to write beautiful Java
Boring Code
I have recently been exposed to functional Java in my day-to-day job….
I like it and am not (too) ashamed to say so.
I decided to write this post when, during a personal project using Python, I felt a bit uncomfortable, I couldn’t use stream and optional, my new favourite games 😕
Don’t write loops
We often need loops, but loops are boring…
You need to repeat an operation n times or to step through elements in some data structure, that’s usually what loops are for, right?
Well, I think we can do better than this:
final var names = List.of("Peter", "Paul", "Mark", "Pablo", "Penny");
final var result = new ArrayList<String>();
for(int i=0; i<names.size(); ++i){
if(names.get(i).charAt(0) == 'P')
result.add(names.get(i).toUpperCase());
}
We are simply iterating through a list of names, filtering out all names that do not begin with a P, and saving the result in uppercase.
It is easy to follow and rather small,
but the loops can get much more complicated
but I still think the version using the stream is much more satisfying:
final var names = List.of("Peter", "Paul", "Mark", "Pablo", "Penny");
final var result = names.stream()
.filter(name -> name.charAt(0) == 'P')
.map(name -> name.toUpperCase())
.collect(Collectors.toList());
I don’t want to make a post about streams…
…at least not now 👀
But I encourage you to refactor some of your boring loops, you will thank me later.
Streams can help you focus on what to do only,
instead of what to do and how to do it
Don’t check for null
Are you still writing if like the one below?
You should stop, I’m worried about your health.
if(obj == null || obj.isEmpty())
throw new IllegalArgumentException();
// some logic
What about something like this:
Optional.ofNullable(obj)
.filter(o -> !o.isEmpty())
.orElseThrow(() -> new IllegalArgumentException());
I’m falling in love with optional.
If you don’t speak Java well enough, we create an optional on which we can call a chain of filter() and map() that will return an optional in turn.
Eventually, if the optional is empty (because it was filtered) or null (because map() returned null), we can throw an exception or return a default value.
Conclusion
I hope you will try some of these little tricks to refactor your code.
There is a lot more to say, I have barely scratched the surface of what is possible, but I encourage you to dig deeper, you will find so many ways to write things differently that simply make sense.
If you found this post useful, read my other posts, you will not regret it :)