Is there a better way to do an empty check in Java? [duplicate] Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!How 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

51k Euros annually for a family of 4 in Berlin: Is it enough?

If a contract sometimes uses the wrong name, is it still valid?

Seeking colloquialism for “just because”

What would be the ideal power source for a cybernetic eye?

List *all* the tuples!

Why did the Falcon Heavy center core fall off the ASDS OCISLY barge?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

How does the particle を relate to the verb 行く in the structure「A を + B に行く」?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

At the end of Thor: Ragnarok why don't the Asgardians turn and head for the Bifrost as per their original plan?

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

Why aren't air breathing engines used as small first stages

What causes the vertical darker bands in my photo?

porting install scripts : can rpm replace apt?

How do I stop a creek from eroding my steep embankment?

How to deal with a team lead who never gives me credit?

Coloring maths inside a tcolorbox

Can any chord be converted to its roman numeral equivalent?

Is there a problem creating Diff Backups every hour instead of Logs and DIffs?

How can I make names more distinctive without making them longer?

Dating a Former Employee

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

How to bypass password on Windows XP account?

What is a non-alternating simple group with big order, but relatively few conjugacy classes?



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



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!How 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();

);
);
);
Apr 11 at 16:09


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();

    );
    );
    );
    Apr 11 at 16:09


    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 Apr 11 at 12:13









      Peter Mortensen

      13.9k1987114




      13.9k1987114










      asked Apr 11 at 10:42









      codeMancodeMan

      4,45321646




      4,45321646




      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();

      );
      );
      );
      Apr 11 at 16:09


      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();

      );
      );
      );
      Apr 11 at 16:09


      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


















          35














          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
            Apr 11 at 11:15






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            Apr 11 at 12:15






          • 1





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

            – dehasi
            Apr 11 at 12:17






          • 1





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

            – user11153
            Apr 11 at 12:54






          • 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
            Apr 11 at 14:07


















          13














          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) registration.getApplication().getMetadata() == 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) 





          share|improve this answer




















          • 5





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

            – keuleJ
            Apr 11 at 10:52






          • 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
            Apr 11 at 11:45












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

            – Khalid Shah
            Apr 11 at 11:47






          • 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
            Apr 11 at 11:49






          • 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
            Apr 11 at 15:25


















          1














          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
            Apr 11 at 13:46






          • 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
            Apr 11 at 13:53






          • 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
            Apr 11 at 15:00











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

            – Zoe
            Apr 11 at 15:08











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

            – Koekje
            Apr 11 at 15:56


















          -2














          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
            Apr 11 at 14:56












          • 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
            Apr 11 at 16:38

















          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          35














          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
            Apr 11 at 11:15






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            Apr 11 at 12:15






          • 1





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

            – dehasi
            Apr 11 at 12:17






          • 1





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

            – user11153
            Apr 11 at 12:54






          • 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
            Apr 11 at 14:07















          35














          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
            Apr 11 at 11:15






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            Apr 11 at 12:15






          • 1





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

            – dehasi
            Apr 11 at 12:17






          • 1





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

            – user11153
            Apr 11 at 12:54






          • 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
            Apr 11 at 14:07













          35












          35








          35







          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 Apr 11 at 16:00









          Captain Man

          3,29932855




          3,29932855










          answered Apr 11 at 10:49









          ernest_kernest_k

          24.9k43151




          24.9k43151







          • 9





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

            – Adrian
            Apr 11 at 11:15






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            Apr 11 at 12:15






          • 1





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

            – dehasi
            Apr 11 at 12:17






          • 1





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

            – user11153
            Apr 11 at 12:54






          • 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
            Apr 11 at 14:07












          • 9





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

            – Adrian
            Apr 11 at 11:15






          • 2





            I think you meant ` Optional.ofNullable()`

            – dehasi
            Apr 11 at 12:15






          • 1





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

            – dehasi
            Apr 11 at 12:17






          • 1





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

            – user11153
            Apr 11 at 12:54






          • 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
            Apr 11 at 14:07







          9




          9





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

          – Adrian
          Apr 11 at 11:15





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

          – Adrian
          Apr 11 at 11:15




          2




          2





          I think you meant ` Optional.ofNullable()`

          – dehasi
          Apr 11 at 12:15





          I think you meant ` Optional.ofNullable()`

          – dehasi
          Apr 11 at 12:15




          1




          1





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

          – dehasi
          Apr 11 at 12:17





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

          – dehasi
          Apr 11 at 12:17




          1




          1





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

          – user11153
          Apr 11 at 12:54





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

          – user11153
          Apr 11 at 12:54




          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
          Apr 11 at 14:07





          @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
          Apr 11 at 14:07













          13














          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) registration.getApplication().getMetadata() == 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) 





          share|improve this answer




















          • 5





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

            – keuleJ
            Apr 11 at 10:52






          • 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
            Apr 11 at 11:45












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

            – Khalid Shah
            Apr 11 at 11:47






          • 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
            Apr 11 at 11:49






          • 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
            Apr 11 at 15:25















          13














          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) registration.getApplication().getMetadata() == 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) 





          share|improve this answer




















          • 5





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

            – keuleJ
            Apr 11 at 10:52






          • 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
            Apr 11 at 11:45












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

            – Khalid Shah
            Apr 11 at 11:47






          • 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
            Apr 11 at 11:49






          • 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
            Apr 11 at 15:25













          13












          13








          13







          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) registration.getApplication().getMetadata() == 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) 





          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) registration.getApplication().getMetadata() == 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) 






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered Apr 11 at 10:50









          Khalid ShahKhalid Shah

          2,29821025




          2,29821025







          • 5





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

            – keuleJ
            Apr 11 at 10:52






          • 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
            Apr 11 at 11:45












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

            – Khalid Shah
            Apr 11 at 11:47






          • 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
            Apr 11 at 11:49






          • 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
            Apr 11 at 15:25












          • 5





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

            – keuleJ
            Apr 11 at 10:52






          • 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
            Apr 11 at 11:45












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

            – Khalid Shah
            Apr 11 at 11:47






          • 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
            Apr 11 at 11:49






          • 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
            Apr 11 at 15:25







          5




          5





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

          – keuleJ
          Apr 11 at 10:52





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

          – keuleJ
          Apr 11 at 10:52




          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
          Apr 11 at 11:45






          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
          Apr 11 at 11:45














          @Philipp yes. But in general getters are trivial.

          – Khalid Shah
          Apr 11 at 11:47





          @Philipp yes. But in general getters are trivial.

          – Khalid Shah
          Apr 11 at 11:47




          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
          Apr 11 at 11:49





          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
          Apr 11 at 11:49




          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
          Apr 11 at 15:25





          @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
          Apr 11 at 15:25











          1














          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
            Apr 11 at 13:46






          • 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
            Apr 11 at 13:53






          • 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
            Apr 11 at 15:00











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

            – Zoe
            Apr 11 at 15:08











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

            – Koekje
            Apr 11 at 15:56















          1














          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
            Apr 11 at 13:46






          • 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
            Apr 11 at 13:53






          • 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
            Apr 11 at 15:00











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

            – Zoe
            Apr 11 at 15:08











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

            – Koekje
            Apr 11 at 15:56













          1












          1








          1







          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 Apr 11 at 14:23





















          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 Apr 11 at 13:41









          CaptianObviousCaptianObvious

          5313




          5313




          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
            Apr 11 at 13:46






          • 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
            Apr 11 at 13:53






          • 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
            Apr 11 at 15:00











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

            – Zoe
            Apr 11 at 15:08











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

            – Koekje
            Apr 11 at 15:56












          • 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
            Apr 11 at 13:46






          • 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
            Apr 11 at 13:53






          • 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
            Apr 11 at 15:00











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

            – Zoe
            Apr 11 at 15:08











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

            – Koekje
            Apr 11 at 15:56







          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
          Apr 11 at 13:46





          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
          Apr 11 at 13:46




          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
          Apr 11 at 13:53





          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
          Apr 11 at 13:53




          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
          Apr 11 at 15:00





          @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
          Apr 11 at 15:00













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

          – Zoe
          Apr 11 at 15:08





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

          – Zoe
          Apr 11 at 15:08













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

          – Koekje
          Apr 11 at 15:56





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

          – Koekje
          Apr 11 at 15:56











          -2














          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
            Apr 11 at 14:56












          • 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
            Apr 11 at 16:38















          -2














          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
            Apr 11 at 14:56












          • 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
            Apr 11 at 16:38













          -2












          -2








          -2







          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 Apr 11 at 13:15

























          answered Apr 11 at 13:03









          Mika LammiMika Lammi

          973619




          973619







          • 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
            Apr 11 at 14:56












          • 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
            Apr 11 at 16:38












          • 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
            Apr 11 at 14:56












          • 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
            Apr 11 at 16:38







          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
          Apr 11 at 14:56






          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
          Apr 11 at 14:56














          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
          Apr 11 at 16:38





          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
          Apr 11 at 16:38



          Popular posts from this blog

          Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

          Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

          Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020