Compute the max in Java: how ugly can it be?

The problem is simple: we need to compute the max among a bunch (more than two) integer values. Let’s assume I need to compute it over three values, a, b and c:

int computedMax = Math.max( a,
                     Math.max( b, c ) );


In the above piece of code, there are two nested function call to the static method max. That’s ugly because if you add other values, you need to add more nested function call too.
And before complaining, yes, there are a few ways to make the code simpler. Such way ranges from statically import the method (so that Math.max can be simply written as max), build a list and use an external library (e.g., Collections.max), and so on.
But the real problem remains: Java have no builtin reduction operator, as well as it has no way to quickly aggregate scalars into structures (e.g., arrays or lists).
How does Raku implements this? It is as simple as:

max $a, $b, $c;


Now, max in Raku is not a reduction operator, rather a method that accepts a list, and the comma operator builds a list. This in short, is the explaination why the above code works and why adding other values does not make the code less readable.

This is the real topic behind this example: you can do whatever you want in pretty much any language, but how you express the alghoritm is what makes a language different from another. And no, providing libraries does not make your language more expressive, it gives you a way to express something long and difficult in a shorter and readable way, but does not change your language.

You can, of course, find other situations other this simple max “problem” where Java requires you to write much code than you really need.
It must be noted that recent versions of Java provide a way to streamline and reduce sequence-like structures, even if I don’t think they provide the same expressivity that other languages provide.

Conclusions

I think Java is a great language, but it clearly suffers from a few design decisions that are making it more ugly every day.
Having experienced other expressive languages, I developed hate against Java, even if I’m using in every day development.

The article Compute the max in Java: how ugly can it be? has been posted by Luca Ferrari on September 29, 2021