PickAnElement.java
is really too smelly, let’s improve it a bit
(and check for nulls … but then one would have to test this also in the streamified version inside the lambda in the code on the next page: filter(name -> name!=null && name.startsWith(startingLetter))
, nulls
are such a pain even if Rich Hickey is unconvinced by Optional
which mainly comes from the fact that Clojure has no typing at all and thus one cannot profit from compiler warnings about lack of handling of Optional
, but I digress…)
(I also suggest shortening startingLetter
do that the method definition first on one line in the book, easier to read)
Instead of:
public static void pickName(final List<String> names, final String startingLetter) {
String foundName = null;
for(String name : names) {
if(name.startsWith(startingLetter)) {
foundName = name;
break;
}
}
System.out.print(String.format("A name starting with %s: ", startingLetter));
if(foundName != null) {
System.out.println(foundName);
} else {
System.out.println("No name found");
}
}
why not at least
public static void pickName(final List<String> names, final String startingLetter) {
String foundName = null;
for(String name : names) {
if(name!=null && name.startsWith(startingLetter)) { // null safe
foundName = name;
break;
}
}
String result = foundName == null ? "No name found" : foundName;
System.out.println(String.format("A name starting with %s: %s", startingLetter, result));
}