0

I'm fairly new to Java and I'm trying to check if a variable is null and use its value if its not. Previous developer wrote something like this:

xModel.setName(xService.getName(xID) != null ? xService.getName(xID) : "");

And I would like to refactor it so I wouldn't have to use xService twice to just get the name.

I know I can store the value beforehand but this is just an example. I just wonder if there is a way to do this in Java?

Thanks.

  • 1
    How is this related to a ternary assignment operator (whatever that is)? – Sweeper Jan 14 '21 at 12:11
  • 6
    Just assign it to a variable first, as you suggested. Don't try to cram too much into one line. Even if there are other ways, it's always better to just keep things as simple as possible, i.e. the solution you've already established. Otherwise, you're just leaving it to the next developer after you to ask questions on what a "ternary assignment" is and how it works. – Ted Klein Bergman Jan 14 '21 at 12:12
  • Does this answer your question? [Java "?" Operator for checking null - What is it? (Not Ternary!)](https://stackoverflow.com/questions/4390141/java-operator-for-checking-null-what-is-it-not-ternary) – Carlos López Marí Jan 14 '21 at 12:13
  • I tried to say shortened ternary operator or the Elvis operator from @CarlosLópezMarí's comment. – Sami Şahin Jan 14 '21 at 12:17
  • It's more a "ternary expression" than a "ternary operator". `a?b:c` is an expression that will result in `b` or `c` what you do with `b` or `c` afterwards is for you to decide. You can use it in asdignments (`x=a?b:c`) or instantiations (`x=a?new B(): new C()`) or anywhere you like. But there is no actual "ternary assignment operator". – GameDroids Jan 14 '21 at 12:22
  • @GameDroids It is called *ternary operator*, a specific kind of *conditional operator*, in the [Java Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html). To quote: This operator is also known as the ternary operator because it uses three operands. – Basil Bourque Jan 14 '21 at 20:24

3 Answers3

7

I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.

Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.

String name = xService.getName(xID);
xModel.setName(name != null ? name : "");

This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • Yeah you are right, I would do it like this too but there isn't only 1 line so I would have to double the number of lines of the whole method. – Sami Şahin Jan 14 '21 at 12:27
  • @SamiŞahin Then create a utility function. Something like (but probably with better names and maybe other parameters depending on your actual context) `String getName(int id, Service service) { String name = service.getName(xID); return name != null ? name : ""; }` Then all your lines would be `xModel.setName(getName(xID, xService));`. – Ted Klein Bergman Jan 14 '21 at 12:29
  • Sorry if I couldn't express myself clear enough but there are multiple get and set operations in the method that are using multiple different variables including Strings, integers, dates etc. Can 1 utility function cover multiple variable types? – Sami Şahin Jan 14 '21 at 12:37
  • @SamiŞahin Okay, then I misunderstood. Well, you could with generics, but then we're most likely back at unnecessary complexity (not certainly, it depends on your actual context). I'd suggest to write it as I suggested in the code above. Sure, it's two lines instead of one, but I still feel it's better than alternatives. It's simple, readable, doesn't rely on a version-dependent standard library, and is sometimes even shorter than the other solutions in terms of characters. – Ted Klein Bergman Jan 14 '21 at 12:56
  • @SamiŞahin You can write a generic utility function as `static T getOrElse(T value, T other) { return value != null ? value : other; }` and call your functions with `xModel.setName(getOrElse(xService.getName(xID), ""))`, but then you're more or less just implementing same functionality as Optionals, which is mentioned in the [answer below](https://stackoverflow.com/a/65718771/6486738). – Ted Klein Bergman Jan 14 '21 at 13:03
2

Objects.toString​( Object o, String nullDefault )

In this particular case you can use java.util.Objects.toString. Second argument is a default value to use in case of a null in the first argument.

xModel.setName(Objects.toString(xService.getName(x.ID), ""));
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Thilo
  • 257,207
  • 101
  • 511
  • 656
1

What you have is already the best core Java can do pre Java 8. From 8 onwards, you may use optionals:

xModel.setName(Optional.ofNullable(xService.getName(xID)).orElse(""));
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360