Here is a simple example that illustrates the benefit of Option beyond 
avoiding null exceptions:

Here is a traditional piece of logic using traditional null if-checks. This 
is using Scala syntax but would be equivalent in Java.

val variableAMayBeNull: A = methodThatMayProduceA();
if (variableAMayBeNull != null) {
val variableBMayBeNull: B = tryToGetBFromA(variableAMayBeNull);

if (variableBMayBeNull != null) {
doSomethingWithNonNullB(variableBMayBeNull);
}
}

Same logic using Option. This is Scala syntax. Java can do this but not as 
nicely until it gets lambdas.

val variableAMayBeNull: Option[A] = methodThatMayProduceA();
val variableBMayBeNull: Option[B] = 
variableAMayBeNull.flatMap(tryToGetBFromA);
variableBMayBeNull.foreach(doSomethingWithNonNullB);

Both blocks are logically equivalent, but the Option route is much more 
concise, elegant, and maintainable. The if-logic is moved from the end 
application code to inside of the Option class. Since this type of logic is 
so common in application code, the code simplification benefits are quite 
large.

 

-- 
You received this message because you are subscribed to the Google Groups "Java 
Posse" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/javaposse/-/EK9-k_9gDkkJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/javaposse?hl=en.

Reply via email to