Yes but that's the most trivial case. For example, experiment with your Option code when the original code has else's.
-- Cédric On Thu, Jul 26, 2012 at 5:30 PM, clay <[email protected]> wrote: > 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 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.
