|
|
|
|
|
by mark242
3428 days ago
|
|
Your very first method has a return buried in the middle of your code. That is a gigantic red flag. Look, what you're trying to do is simple. getNumbers.fold(println("Failed to load numbers"))(nums => nums.foreach(println))
That's the Scala version, but I'm sure there's a Java version of the same code. This code assumes that getNumbers returns Option[List[Int]], which your compiler can guarantee. If you want something that's a little bit more readable, try this: getNumbers match {
case Some(nums) => nums.foreach(println)
case None => println("Failed to load numbers")
}
No null check, no loops, just very simple easy-to-read bulletproof code. This code cannot generate a NPE at all, ever. |
|
The second option, as I have stated many times in this thread, is far preferable to null. Java does not support it but when it does I will like it.
"* No null check, no loops, just very simple easy-to-read bulletproof code. This code cannot generate a NPE at all, ever.*"
The NPE isn't the illness, it's the symptom. It's the symptom of a far larger problem in your program: unhandled or otherwise unexpected state. That's why I like the match example. It forces you to expect all of the states of your program. The first example does neither. It hides flow and operation in a single (ever-expanding) line. Far from ideal in any case in my book.
As soon as Match is supported in Java I'll change my opinion. Until then I'm stuck. You get nothing better from the Java version in terms of readability.