r/learnjava • • Mar 05 '24

Which is preferable A == null or A != null ?

        if (A == null)
        1 code block
    else
        2 code block
//or 
        if (A != null)
        2 code block
    else
        1 code block
2 Upvotes

23 comments sorted by

•

u/AutoModerator Mar 05 '24

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full - best also formatted as code block

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

27

u/troru Mar 05 '24

i'd vote for always favoring the simpler "==" at first go but there's some nuance. I also prefer fast function exits and if a "==" leads that situation, all the better. I think choices like this need to be influenced by overall code flow and whatever leads to less indentation/nesting.

10

u/[deleted] Mar 05 '24

This absolutely. Even the sophisticated database of software quality checks from Coverity suggest that you prefer affirmative logical conditions over negative.

2

u/crafty-andi1356 Mar 06 '24

In addition to this answer it’s better to have the null first ( null == A ) when A is indeed null you might encounter a null pointer exception, Junior Java Dev here, but that’s what the Seniors told me. Also I believe that generally it’s a better practice to use Objects.isNull(Object o) function.

1

u/Toby_B_E Mar 08 '24

Putting null (or whatever invariant / literal that you're comparing against) first in checks is known as Yoda conditions (or Yoda notation).

That technique can help with avoiding bugs but there are some things that people criticize about it.

1

u/crafty-andi1356 Mar 08 '24

Thanks for your reply! I don’t engage a lot with the community so it’s nice to have a feedback on my comment. Back to the topic: do they criticize this because of readability? or any other reason?

1

u/Toby_B_E Mar 08 '24

You're welcome.

Yes, readability is the main criticism of the technique but there are a few others.

You can read more about it here: https://en.m.wikipedia.org/wiki/Yoda_conditions

2

u/nomnommish Mar 07 '24

I tend to prefer readability. Our brain processs equality better than it processes inequality.

-2

u/[deleted] Mar 05 '24

👾

12

u/Bunnymancer Mar 05 '24

Whichever you expect.

7

u/MattiDragon Mar 05 '24

You should generally put the case with less code first, especially if it contains a return (or break or continue). If that is the case then you can avoid the else altogether, reducing nesting. Look up guard clauses.

4

u/[deleted] Mar 05 '24

In vacuum not doing the negation is preferable because it's more straight forward, but realistically it always depends on the situation.

3

u/krisko11 Mar 05 '24

Never-nesters usually do the case that leads to clearer and non-nested code. If your function is “if not null then do all that there is no point in making if null return else do all that.

3

u/RunesViper Mar 05 '24

I would recommend to use util class instead, like ObjectUtils, StringUtils etc from Apache.commons jar. But any of the 2 options is fine, but it's a good practice to add null first in the condition, something like if (null == A).

1

u/g00glen00b Mar 05 '24

It depends a lot on the meaning. For example, I do like to handle exception cases first. So if A == null is an exception case, I would prefer the first option. I would probably even remove the else because I would try to return a value or throw an exception from the first code block. So something like:

if (A == null)
    1 code block
    throw an exception
2 code block

If neither branch is an exception case, then it honestly doesn't matter that much. I would take whatever makes most sense to me or just pick whatever I like.

1

u/cookie-exploit Mar 06 '24

In general it is better to use the == in favor of != as the cognitive overload is higher for negated conditions. But it depends also on the specific code if the negated one might be a better choice.

0

u/[deleted] Mar 05 '24

Is there anything you can do to enforce A can't be null before you got here?

0

u/maybegone18 Mar 05 '24

doesnt matter.

0

u/artofnotgivingup Mar 05 '24 edited May 07 '24

Diebdicbt

0

u/Gidrek Mar 06 '24

It's no like Python? Where None (null) is falsy?

if (var) { }

0

u/SftwEngr Mar 06 '24

What about:

if (A) {}

0

u/[deleted] Mar 06 '24

[deleted]

1

u/HyzerFlipr Mar 09 '24

You don't need the else since you are returning if A is null. That would be a code smell.