Java has often been accused of being too verbose. This has advantages and disadvantages. Its verbosity means that humans do not need to interpret what the code does - it is obvious for all to see.
Our anonymous inner classes are rather verbose. In the ORIGINAL_SCRAMBLER
, we
already know that we are making a Scrambler
, because that is the type of the
field declared on the left-hand side. So why do we have to repeat it? We also
know that if there is only a single abstract method in the interface, it is
very likely going to be this one that we are implementing. So why do we have
to repeat the name of the interface in new Scrambler()
and why do we need to
explicitly state the name of the method scramble(char[] letters)
when it is
obvious that this would be the only method we could be implementing. We can
deduce all that by just seeing that the type of the field is a
Scrambler
.
Since we have only one abstract method in our interface, we can replace the anonymous type with a lambda.
When making the lambda for the ORIGINAL_SCRAMBLER
, we notice that we cannot
put the curly braces and the comment on a single line. The reason is that when
we write a comment with //
anything on the right side of that is considered a
comment, even our closing curly brace. This type of comment is called an
end-of-line comment. We can also use a "traditional comment", which is like in
C where we start with /*
and end with */
. By changing the comment we are able
to wrap the comment with braces on a single line.
We also change the RANDOM_SCRAMBLER
and the SORTED_SCRAMBLER
to use lambdas
instead of anonymous types.
We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...