Is there a better way to do an empty check in Java? [duplicate] The 2019 Stack Overflow Developer Survey Results Are In Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceHow to check multiple objects for nullity?Check chains of “get” calls for nullHow better refactor chain of methods that can return null in java?Check if last getter in method chain is not nullTry-Catch Instead of Null Check When Using Several Getterstry/catch vs null check in javaTry Catch Performance JavaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?Fastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What's the simplest way to print a Java array?How do I convert a String to an int in Java?Creating a memory leak with Java

Deal with toxic manager when you can't quit

One-dimensional Japanese puzzle

Can a flute soloist sit?

Sub-subscripts in strings cause different spacings than subscripts

Is there a writing software that you can sort scenes like slides in PowerPoint?

"is" operation returns false even though two objects have same id

University's motivation for having tenure-track positions

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

Does Parliament hold absolute power in the UK?

Was credit for the black hole image misappropriated?

Would an alien lifeform be able to achieve space travel if lacking in vision?

Mortgage adviser recommends a longer term than necessary combined with overpayments

Loose spokes after only a few rides

Python - Fishing Simulator

Simulating Exploding Dice

How to support a colleague who finds meetings extremely tiring?

Can the DM override racial traits?

Identify 80s or 90s comics with ripped creatures (not dwarves)

What do I do when my TA workload is more than expected?

Drawing vertical/oblique lines in Metrical tree (tikz-qtree, tipa)

60's-70's movie: home appliances revolting against the owners

Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?

Button changing its text & action. Good or terrible?

How do spell lists change if the party levels up without taking a long rest?



Is there a better way to do an empty check in Java? [duplicate]



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceHow to check multiple objects for nullity?Check chains of “get” calls for nullHow better refactor chain of methods that can return null in java?Check if last getter in method chain is not nullTry-Catch Instead of Null Check When Using Several Getterstry/catch vs null check in javaTry Catch Performance JavaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?Fastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What's the simplest way to print a Java array?How do I convert a String to an int in Java?Creating a memory leak with Java



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








20
















This question already has an answer here:



  • Check chains of “get” calls for null

    8 answers



  • Check if last getter in method chain is not null

    3 answers



  • How to check multiple objects for nullity?

    5 answers



  • Try-Catch Instead of Null Check When Using Several Getters

    3 answers



  • How better refactor chain of methods that can return null in java?

    10 answers



This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.



The goal is to check the value of a boolean field that is nested under two objects.



private boolean sourceWebsite(Registration registration) 
Application application = registration.getApplication();
if (application == null)
return true;


Metadata metadata = application.getMetadata();
if (metadata == null)
return true;


Boolean source = metadata.getSource();
if (source == null)
return true;


return !source;



I know this could be done in a single if(). I have added multiple ifs here for the sake of readability.



Is there a way that we could simplify the above if statements and have a simple utility class that returns the value of Boolean source if the parent objects or not null?










share|improve this question















marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























    20
















    This question already has an answer here:



    • Check chains of “get” calls for null

      8 answers



    • Check if last getter in method chain is not null

      3 answers



    • How to check multiple objects for nullity?

      5 answers



    • Try-Catch Instead of Null Check When Using Several Getters

      3 answers



    • How better refactor chain of methods that can return null in java?

      10 answers



    This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.



    The goal is to check the value of a boolean field that is nested under two objects.



    private boolean sourceWebsite(Registration registration) 
    Application application = registration.getApplication();
    if (application == null)
    return true;


    Metadata metadata = application.getMetadata();
    if (metadata == null)
    return true;


    Boolean source = metadata.getSource();
    if (source == null)
    return true;


    return !source;



    I know this could be done in a single if(). I have added multiple ifs here for the sake of readability.



    Is there a way that we could simplify the above if statements and have a simple utility class that returns the value of Boolean source if the parent objects or not null?










    share|improve this question















    marked as duplicate by Sotirios Delimanolis java
    Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

    StackExchange.ready(function()
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function()
    $hover.showInfoMessage('',
    messageElement: $msg.clone().show(),
    transient: false,
    position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
    dismissable: false,
    relativeToBody: true
    );
    ,
    function()
    StackExchange.helpers.removeMessages();

    );
    );
    );
    yesterday


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




















      20












      20








      20


      2







      This question already has an answer here:



      • Check chains of “get” calls for null

        8 answers



      • Check if last getter in method chain is not null

        3 answers



      • How to check multiple objects for nullity?

        5 answers



      • Try-Catch Instead of Null Check When Using Several Getters

        3 answers



      • How better refactor chain of methods that can return null in java?

        10 answers



      This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.



      The goal is to check the value of a boolean field that is nested under two objects.



      private boolean sourceWebsite(Registration registration) 
      Application application = registration.getApplication();
      if (application == null)
      return true;


      Metadata metadata = application.getMetadata();
      if (metadata == null)
      return true;


      Boolean source = metadata.getSource();
      if (source == null)
      return true;


      return !source;



      I know this could be done in a single if(). I have added multiple ifs here for the sake of readability.



      Is there a way that we could simplify the above if statements and have a simple utility class that returns the value of Boolean source if the parent objects or not null?










      share|improve this question

















      This question already has an answer here:



      • Check chains of “get” calls for null

        8 answers



      • Check if last getter in method chain is not null

        3 answers



      • How to check multiple objects for nullity?

        5 answers



      • Try-Catch Instead of Null Check When Using Several Getters

        3 answers



      • How better refactor chain of methods that can return null in java?

        10 answers



      This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.



      The goal is to check the value of a boolean field that is nested under two objects.



      private boolean sourceWebsite(Registration registration) 
      Application application = registration.getApplication();
      if (application == null)
      return true;


      Metadata metadata = application.getMetadata();
      if (metadata == null)
      return true;


      Boolean source = metadata.getSource();
      if (source == null)
      return true;


      return !source;



      I know this could be done in a single if(). I have added multiple ifs here for the sake of readability.



      Is there a way that we could simplify the above if statements and have a simple utility class that returns the value of Boolean source if the parent objects or not null?





      This question already has an answer here:



      • Check chains of “get” calls for null

        8 answers



      • Check if last getter in method chain is not null

        3 answers



      • How to check multiple objects for nullity?

        5 answers



      • Try-Catch Instead of Null Check When Using Several Getters

        3 answers



      • How better refactor chain of methods that can return null in java?

        10 answers







      java if-statement conditional






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      Peter Mortensen

      13.9k1987114




      13.9k1987114










      asked yesterday









      codeMancodeMan

      4,44721646




      4,44721646




      marked as duplicate by Sotirios Delimanolis java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      yesterday


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Sotirios Delimanolis java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      yesterday


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























          4 Answers
          4






          active

          oldest

          votes


















          32














          You can use java.util.Optional in this way:



          private boolean sourceWebsite(Registration registration) 
          return Optional.of(registration)
          .map(Registration::getApplication)
          .map(Application::getMetadata)
          .map(Metadata::getSource)
          .map(source -> !source)
          .orElse(Boolean.TRUE);



          In short, this will return true if any of the getters returns null, and !Metadata.source otherwise.






          share|improve this answer




















          • 9





            Boolean.FALSE::equals instead of source -> !source if you really love method reference

            – Adrian
            yesterday






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            yesterday






          • 1





            Sorry, you are right. I've upvoted :)

            – dehasi
            yesterday






          • 1





            Return type is boolean so .orElse(true); would be better.

            – user11153
            yesterday






          • 2





            @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

            – ave4496
            yesterday


















          12














          The following will return true if any one of is null. If all values are not null, it returns !source.



          private boolean sourceWebsite(Registration registration) 
          return registration.getApplication() == null



          Updated :



          If you want that every getter not called more than once then you can declare variable for every object like



          private boolean sourceWebsite(Registration registration) (metadata = application.getMetadata()) == null






          share|improve this answer




















          • 5





            The null-conditional operator (?.) of c# is for shure a nice thing...

            – keuleJ
            yesterday






          • 3





            One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

            – Philipp
            yesterday












          • @Philipp yes. But in general getters are trivial.

            – Khalid Shah
            yesterday






          • 5





            In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

            – Philipp
            yesterday






          • 1





            @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

            – Philipp
            yesterday


















          3














          Another option you can use is a try-catch block. If you get a null pointer exception return true.



          private boolean sourceWebsite(Registration registration) 
          try
          return !registration.getApplication().getMetadata().getSource();

          catch (NullPointerException e)
          return true;







          share|improve this answer










          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.















          • 6





            You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

            – Nzall
            yesterday






          • 1





            In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

            – CaptianObvious
            yesterday






          • 1





            @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

            – Old Nick
            yesterday











          • Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

            – Zoe
            yesterday











          • Until a NPE is thrown much deeper in one of those methods.

            – Koekje
            yesterday


















          -1














          You could do it using a hacky method like this:



          public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException m.length == 0) 
          return null;

          for (String m1 : m)
          o = o.getClass().getMethod(m1).invoke(o);
          if (o == null)
          return null;


          return o;



          And call it like this:



          Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
          return source == null ? false : !source;


          But I wouldn't do it this way in any serious projects.






          share|improve this answer




















          • 2





            This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

            – julodnik
            yesterday












          • It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

            – Eric Duminil
            yesterday

















          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          32














          You can use java.util.Optional in this way:



          private boolean sourceWebsite(Registration registration) 
          return Optional.of(registration)
          .map(Registration::getApplication)
          .map(Application::getMetadata)
          .map(Metadata::getSource)
          .map(source -> !source)
          .orElse(Boolean.TRUE);



          In short, this will return true if any of the getters returns null, and !Metadata.source otherwise.






          share|improve this answer




















          • 9





            Boolean.FALSE::equals instead of source -> !source if you really love method reference

            – Adrian
            yesterday






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            yesterday






          • 1





            Sorry, you are right. I've upvoted :)

            – dehasi
            yesterday






          • 1





            Return type is boolean so .orElse(true); would be better.

            – user11153
            yesterday






          • 2





            @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

            – ave4496
            yesterday















          32














          You can use java.util.Optional in this way:



          private boolean sourceWebsite(Registration registration) 
          return Optional.of(registration)
          .map(Registration::getApplication)
          .map(Application::getMetadata)
          .map(Metadata::getSource)
          .map(source -> !source)
          .orElse(Boolean.TRUE);



          In short, this will return true if any of the getters returns null, and !Metadata.source otherwise.






          share|improve this answer




















          • 9





            Boolean.FALSE::equals instead of source -> !source if you really love method reference

            – Adrian
            yesterday






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            yesterday






          • 1





            Sorry, you are right. I've upvoted :)

            – dehasi
            yesterday






          • 1





            Return type is boolean so .orElse(true); would be better.

            – user11153
            yesterday






          • 2





            @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

            – ave4496
            yesterday













          32












          32








          32







          You can use java.util.Optional in this way:



          private boolean sourceWebsite(Registration registration) 
          return Optional.of(registration)
          .map(Registration::getApplication)
          .map(Application::getMetadata)
          .map(Metadata::getSource)
          .map(source -> !source)
          .orElse(Boolean.TRUE);



          In short, this will return true if any of the getters returns null, and !Metadata.source otherwise.






          share|improve this answer















          You can use java.util.Optional in this way:



          private boolean sourceWebsite(Registration registration) 
          return Optional.of(registration)
          .map(Registration::getApplication)
          .map(Application::getMetadata)
          .map(Metadata::getSource)
          .map(source -> !source)
          .orElse(Boolean.TRUE);



          In short, this will return true if any of the getters returns null, and !Metadata.source otherwise.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday









          Captain Man

          3,29932855




          3,29932855










          answered yesterday









          ernest_kernest_k

          24.9k43151




          24.9k43151







          • 9





            Boolean.FALSE::equals instead of source -> !source if you really love method reference

            – Adrian
            yesterday






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            yesterday






          • 1





            Sorry, you are right. I've upvoted :)

            – dehasi
            yesterday






          • 1





            Return type is boolean so .orElse(true); would be better.

            – user11153
            yesterday






          • 2





            @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

            – ave4496
            yesterday












          • 9





            Boolean.FALSE::equals instead of source -> !source if you really love method reference

            – Adrian
            yesterday






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            yesterday






          • 1





            Sorry, you are right. I've upvoted :)

            – dehasi
            yesterday






          • 1





            Return type is boolean so .orElse(true); would be better.

            – user11153
            yesterday






          • 2





            @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

            – ave4496
            yesterday







          9




          9





          Boolean.FALSE::equals instead of source -> !source if you really love method reference

          – Adrian
          yesterday





          Boolean.FALSE::equals instead of source -> !source if you really love method reference

          – Adrian
          yesterday




          2




          2





          I think you meant ` Optional.ofNullable()`

          – dehasi
          yesterday





          I think you meant ` Optional.ofNullable()`

          – dehasi
          yesterday




          1




          1





          Sorry, you are right. I've upvoted :)

          – dehasi
          yesterday





          Sorry, you are right. I've upvoted :)

          – dehasi
          yesterday




          1




          1





          Return type is boolean so .orElse(true); would be better.

          – user11153
          yesterday





          Return type is boolean so .orElse(true); would be better.

          – user11153
          yesterday




          2




          2





          @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

          – ave4496
          yesterday





          @user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more

          – ave4496
          yesterday













          12














          The following will return true if any one of is null. If all values are not null, it returns !source.



          private boolean sourceWebsite(Registration registration) 
          return registration.getApplication() == null



          Updated :



          If you want that every getter not called more than once then you can declare variable for every object like



          private boolean sourceWebsite(Registration registration) (metadata = application.getMetadata()) == null






          share|improve this answer




















          • 5





            The null-conditional operator (?.) of c# is for shure a nice thing...

            – keuleJ
            yesterday






          • 3





            One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

            – Philipp
            yesterday












          • @Philipp yes. But in general getters are trivial.

            – Khalid Shah
            yesterday






          • 5





            In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

            – Philipp
            yesterday






          • 1





            @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

            – Philipp
            yesterday















          12














          The following will return true if any one of is null. If all values are not null, it returns !source.



          private boolean sourceWebsite(Registration registration) 
          return registration.getApplication() == null



          Updated :



          If you want that every getter not called more than once then you can declare variable for every object like



          private boolean sourceWebsite(Registration registration) (metadata = application.getMetadata()) == null






          share|improve this answer




















          • 5





            The null-conditional operator (?.) of c# is for shure a nice thing...

            – keuleJ
            yesterday






          • 3





            One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

            – Philipp
            yesterday












          • @Philipp yes. But in general getters are trivial.

            – Khalid Shah
            yesterday






          • 5





            In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

            – Philipp
            yesterday






          • 1





            @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

            – Philipp
            yesterday













          12












          12








          12







          The following will return true if any one of is null. If all values are not null, it returns !source.



          private boolean sourceWebsite(Registration registration) 
          return registration.getApplication() == null



          Updated :



          If you want that every getter not called more than once then you can declare variable for every object like



          private boolean sourceWebsite(Registration registration) (metadata = application.getMetadata()) == null






          share|improve this answer















          The following will return true if any one of is null. If all values are not null, it returns !source.



          private boolean sourceWebsite(Registration registration) 
          return registration.getApplication() == null



          Updated :



          If you want that every getter not called more than once then you can declare variable for every object like



          private boolean sourceWebsite(Registration registration) (metadata = application.getMetadata()) == null







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          Khalid ShahKhalid Shah

          2,24021025




          2,24021025







          • 5





            The null-conditional operator (?.) of c# is for shure a nice thing...

            – keuleJ
            yesterday






          • 3





            One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

            – Philipp
            yesterday












          • @Philipp yes. But in general getters are trivial.

            – Khalid Shah
            yesterday






          • 5





            In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

            – Philipp
            yesterday






          • 1





            @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

            – Philipp
            yesterday












          • 5





            The null-conditional operator (?.) of c# is for shure a nice thing...

            – keuleJ
            yesterday






          • 3





            One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

            – Philipp
            yesterday












          • @Philipp yes. But in general getters are trivial.

            – Khalid Shah
            yesterday






          • 5





            In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

            – Philipp
            yesterday






          • 1





            @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

            – Philipp
            yesterday







          5




          5





          The null-conditional operator (?.) of c# is for shure a nice thing...

          – keuleJ
          yesterday





          The null-conditional operator (?.) of c# is for shure a nice thing...

          – keuleJ
          yesterday




          3




          3





          One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

          – Philipp
          yesterday






          One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.

          – Philipp
          yesterday














          @Philipp yes. But in general getters are trivial.

          – Khalid Shah
          yesterday





          @Philipp yes. But in general getters are trivial.

          – Khalid Shah
          yesterday




          5




          5





          In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

          – Philipp
          yesterday





          In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.

          – Philipp
          yesterday




          1




          1





          @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

          – Philipp
          yesterday





          @EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.

          – Philipp
          yesterday











          3














          Another option you can use is a try-catch block. If you get a null pointer exception return true.



          private boolean sourceWebsite(Registration registration) 
          try
          return !registration.getApplication().getMetadata().getSource();

          catch (NullPointerException e)
          return true;







          share|improve this answer










          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.















          • 6





            You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

            – Nzall
            yesterday






          • 1





            In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

            – CaptianObvious
            yesterday






          • 1





            @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

            – Old Nick
            yesterday











          • Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

            – Zoe
            yesterday











          • Until a NPE is thrown much deeper in one of those methods.

            – Koekje
            yesterday















          3














          Another option you can use is a try-catch block. If you get a null pointer exception return true.



          private boolean sourceWebsite(Registration registration) 
          try
          return !registration.getApplication().getMetadata().getSource();

          catch (NullPointerException e)
          return true;







          share|improve this answer










          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.















          • 6





            You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

            – Nzall
            yesterday






          • 1





            In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

            – CaptianObvious
            yesterday






          • 1





            @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

            – Old Nick
            yesterday











          • Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

            – Zoe
            yesterday











          • Until a NPE is thrown much deeper in one of those methods.

            – Koekje
            yesterday













          3












          3








          3







          Another option you can use is a try-catch block. If you get a null pointer exception return true.



          private boolean sourceWebsite(Registration registration) 
          try
          return !registration.getApplication().getMetadata().getSource();

          catch (NullPointerException e)
          return true;







          share|improve this answer










          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.










          Another option you can use is a try-catch block. If you get a null pointer exception return true.



          private boolean sourceWebsite(Registration registration) 
          try
          return !registration.getApplication().getMetadata().getSource();

          catch (NullPointerException e)
          return true;








          share|improve this answer










          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited yesterday





















          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered yesterday









          CaptianObviousCaptianObvious

          5713




          5713




          New contributor




          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          CaptianObvious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.







          • 6





            You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

            – Nzall
            yesterday






          • 1





            In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

            – CaptianObvious
            yesterday






          • 1





            @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

            – Old Nick
            yesterday











          • Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

            – Zoe
            yesterday











          • Until a NPE is thrown much deeper in one of those methods.

            – Koekje
            yesterday












          • 6





            You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

            – Nzall
            yesterday






          • 1





            In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

            – CaptianObvious
            yesterday






          • 1





            @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

            – Old Nick
            yesterday











          • Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

            – Zoe
            yesterday











          • Until a NPE is thrown much deeper in one of those methods.

            – Koekje
            yesterday







          6




          6





          You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

          – Nzall
          yesterday





          You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.

          – Nzall
          yesterday




          1




          1





          In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

          – CaptianObvious
          yesterday





          In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.

          – CaptianObvious
          yesterday




          1




          1





          @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

          – Old Nick
          yesterday





          @Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.

          – Old Nick
          yesterday













          Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

          – Zoe
          yesterday





          Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy

          – Zoe
          yesterday













          Until a NPE is thrown much deeper in one of those methods.

          – Koekje
          yesterday





          Until a NPE is thrown much deeper in one of those methods.

          – Koekje
          yesterday











          -1














          You could do it using a hacky method like this:



          public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException m.length == 0) 
          return null;

          for (String m1 : m)
          o = o.getClass().getMethod(m1).invoke(o);
          if (o == null)
          return null;


          return o;



          And call it like this:



          Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
          return source == null ? false : !source;


          But I wouldn't do it this way in any serious projects.






          share|improve this answer




















          • 2





            This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

            – julodnik
            yesterday












          • It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

            – Eric Duminil
            yesterday















          -1














          You could do it using a hacky method like this:



          public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException m.length == 0) 
          return null;

          for (String m1 : m)
          o = o.getClass().getMethod(m1).invoke(o);
          if (o == null)
          return null;


          return o;



          And call it like this:



          Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
          return source == null ? false : !source;


          But I wouldn't do it this way in any serious projects.






          share|improve this answer




















          • 2





            This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

            – julodnik
            yesterday












          • It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

            – Eric Duminil
            yesterday













          -1












          -1








          -1







          You could do it using a hacky method like this:



          public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException m.length == 0) 
          return null;

          for (String m1 : m)
          o = o.getClass().getMethod(m1).invoke(o);
          if (o == null)
          return null;


          return o;



          And call it like this:



          Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
          return source == null ? false : !source;


          But I wouldn't do it this way in any serious projects.






          share|improve this answer















          You could do it using a hacky method like this:



          public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException m.length == 0) 
          return null;

          for (String m1 : m)
          o = o.getClass().getMethod(m1).invoke(o);
          if (o == null)
          return null;


          return o;



          And call it like this:



          Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
          return source == null ? false : !source;


          But I wouldn't do it this way in any serious projects.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          Mika LammiMika Lammi

          975619




          975619







          • 2





            This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

            – julodnik
            yesterday












          • It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

            – Eric Duminil
            yesterday












          • 2





            This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

            – julodnik
            yesterday












          • It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

            – Eric Duminil
            yesterday







          2




          2





          This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

          – julodnik
          yesterday






          This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.

          – julodnik
          yesterday














          It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

          – Eric Duminil
          yesterday





          It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource) so you might as well use Optional directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.

          – Eric Duminil
          yesterday



          -conditional, if-statement, java

          Popular posts from this blog

          Frič See also Navigation menuinternal link

          Identify plant with long narrow paired leaves and reddish stems Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?What is this plant with long sharp leaves? Is it a weed?What is this 3ft high, stalky plant, with mid sized narrow leaves?What is this young shrub with opposite ovate, crenate leaves and reddish stems?What is this plant with large broad serrated leaves?Identify this upright branching weed with long leaves and reddish stemsPlease help me identify this bulbous plant with long, broad leaves and white flowersWhat is this small annual with narrow gray/green leaves and rust colored daisy-type flowers?What is this chilli plant?Does anyone know what type of chilli plant this is?Help identify this plant

          fontconfig warning: “/etc/fonts/fonts.conf”, line 100: unknown “element blank” The 2019 Stack Overflow Developer Survey Results Are In“tar: unrecognized option --warning” during 'apt-get install'How to fix Fontconfig errorHow do I figure out which font file is chosen for a system generic font alias?Why are some apt-get-installed fonts being ignored by fc-list, xfontsel, etc?Reload settings in /etc/fonts/conf.dTaking 30 seconds longer to boot after upgrade from jessie to stretchHow to match multiple font names with a single <match> element?Adding a custom font to fontconfigRemoving fonts from fontconfig <match> resultsBroken fonts after upgrading Firefox ESR to latest Firefox