I see a lot of examples where for example
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
can we use any variableName in these lambda expressions?
I thought variable names have conventions and is good to use proper names for readability.
For instance if I use w as Widget in pre-java8, the code would be shunned as not readable. What has changed with the advent of java 8?
for(Widget w : widgets)
{
if(w.getColor() == RED) {
sum += w.getWeight();
}
}
Why can't the code be written like this:
int sum = widgets.stream()
.filter(widget -> widget.getColor() == RED)
.mapToInt(widget -> widget.getWeight())
.sum();
Maybe the code above is doing something straight-forward, and only on widget in the list of widgets. So, something more:
Which is better readable:
return requestHolder.getRequests()
.stream()
.map(request -> request.getErrorHolder())
.flatMap(errorData -> errorData.getErrors().stream())
.collect(toList());
or
return requestHolder.getRequests()
.stream()
.map(t -> t.getErrorHolder())
.flatMap(r -> r.getErrors().stream())
.collect(toList());
Maybe I am missing something. Could you explain?
The tacit convention is: name your variables so the code is pleasant and easy to read.
In my opinion, a very short name or a dummy name is preferable when the scope of the variable is limited. It makes the code more readable, lighter and also indicates that the function of the variable is limited.
Explicit names are to be preferred when the variable is used extensively in the code and you want to avoid to have it confused with other variables.
for(int i = 0 ; i < max ; ++i) {
int myExplicitVar = myArray[i];
// rest of the code using myExplicitVar several times
}
For lambdas, the scope of the variable is usually extremely limited and I find it easier to read when the name is short so only the important parts of the code remains, which was the point of lambda expressions in the first place.
In your examples, I find the short names more straight to the point.
Short variable name makes the code less bloated but can lead to confusions in rich contexts.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments