2

I have a class containing nested and inner classes. And in some program, i am check for the null values of the object using equal operator in the legacy java way. The following is my code snippet:

class Outer {
    Nested nested;
    Nested getNested() {
        return nested;
    }
}
class Nested {
    Inner inner;
    Inner getInner() {
        return inner;
    }
}
class Inner {
    String foo;
    String getFoo() {
        return foo;
    }
}

And here is how i am doing the null checks on the reference variables:

Outer outer = new Outer();
if (outer != null && outer.nested != null && outer.nested.inner != null) {
    System.out.println(outer.nested.inner.foo);
}

I know this can also be done using the Optional class of java 8, but i am not getting a way for doing the same above particular scenario. Any suggestion?

2 Answers 2

8

The follwoing code worked well for me:

Optional.of(new Outer())
    .map(Outer::getNested)
    .map(Nested::getInner)
    .map(Inner::getFoo)
    .ifPresent(System.out::println);
Sign up to request clarification or add additional context in comments.

1 Comment

and that's good code, you can totally answer your own questions here, even accept them. +1
6

I highly suggest you watch the recent Devoxx Belgium presentation "Optional - The Mother of All Bikesheds" by Stuart Marks. Stuart is describing what was the initial intent, best practices and bad practices using it.

In particular using Optional in fields, quoting from the presentation slide:

  • Why Not Use Optional in Fields?
    • More a style issue than a correctness issue
    • use of Optional in fields often arises from slavish desire to eliminate nullable fields.
    • remember, eliminating nulls isn't a goal of Optional
  • Using Optional in fields..
    • creates another object for every field
    • introduces a dependent load from memory on every field read
    • clutters up your code
    • to what benefit? ability to chain methods?

To your example in particular:

  1. why outer != null check? it's just got created!
  2. if Nested instance needs to be part of Outer and Inner part of Nested have them part of the constructors and guard with some @NotNull code or check programmatically.

1 Comment

Thanks for bringing such insight to the java community!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.