Java Reference
In-Depth Information
8.1.1. Improving code readability
What does it mean to improve the readability of code? It's hard to define what good readability
means, because it can be very subjective. The general view is that it means “how easily this code
can be understood by another human.” Improving code readability means ensuring your code is
understandable and maintainable by people besides you. There are a few steps you can take to
make sure your code is understandable by other people, such as making sure your code is well
documented and follows coding standards.
Java 8 features can also help improve code readability compared to previous versions:
You can reduce the verbosity of your code, making it easier to understand.
You can improve the intent of your code by using method references and the Streams API.
We describe three simple refactorings that use lambdas, method references, and streams, which
you can apply to your code to improve its readability:
Refactoring anonymous classes to lambda expressions
Refactoring lambda expressions to method references
Refactoring imperative-style data processing to streams
8.1.2. From anonymous classes to lambda expressions
The first simple refactoring you should consider is converting uses of anonymous classes
implementing one single abstract method to lambda expressions. Why? We hope we convinced
you in earlier chapters that anonymous classes are extremely verbose and error-prone. By
adopting lambda expressions, you produce code that is more succinct and readable. For example,
as shown in chapter 3 , here's an anonymous class for creating a Runnable object and its lambda
expression counterpart:
But converting anonymous classes to lambda expressions can be a difficult process in certain
situations. [ 1 ] First, the meanings of this and super are different for anonymous classes and
lambda expressions. Inside an anonymous class, this refers to the anonymous class itself, but
inside a lambda it refers to the enclosing class. Second, anonymous classes are allowed to
 
Search WWH ::




Custom Search