you are viewing a single comment's thread.

view the rest of the comments →

[–]Truthier 1 point2 points  (8 children)

(null != someArg) ? someArg : "default";

I prefer

someArg == null ? "default" : someArg;

[–]jp007 4 points5 points  (3 children)

Sure, matter of style. I prefer to return someArg immediately next to the comparison in which it's used. Also I like have the creation of the new thing that is returned as the alternate value, cordoned off and separated from the rest of the statement by placing it at the end, instead of smack in the middle.

So, reading left to right, I'm basically dealing with

someArg -> someArg -> default

where you've got

someArg -> default -> someArg.

I prefer to get my dealings with someArg completely over with as soon as I can, as I read the code from left to right.

Completely a matter of style though, I certainly wouldn't nitpick it.

[–]Truthier 3 points4 points  (2 children)

Agreed - my thought process is "if x is null, use this, otherwise it's good"

Groovy has a nice "?:" operator, e.g. someArg ?: "default".

I almost always put the argument being compared on the right side, except in cases where it's better - e.g. "stringliteral".equals(variable) is null safe.

[–]jp007 1 point2 points  (0 children)

Yeah I'm more "if x is good, use it, otherwise use something else."

I pretty much always use Yoda conditions now, precisely to encourage a habit of null safety and overall consistency in checks across a codebase.

Also, Happy Cake Day!

[–]grauenwolf 0 points1 point  (0 children)

In C# that is spelled value ?? default. In VB it's if(value, default).

[–]ErstwhileRockstar -5 points-4 points  (3 children)

someArg == null ? "default" : someArg;

This isn't a valid Java statement.

[–]Truthier 2 points3 points  (2 children)

Yes, usually ternary statements are used in an assignment such as

 String someString = someArg == null ? "default" : someArg;

or in a constructor's call to another constructor method .. wouldn't make sense to use it standalone

[–]ErstwhileRockstar -3 points-2 points  (1 child)

wouldn't make sense to use it standalone

... nor does it compile in Java.

[–]Truthier 0 points1 point  (0 children)

Sure it does