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.

6
  • 1
    How is this related to a ternary assignment operator (whatever that is)? Commented Jan 14, 2021 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. Commented Jan 14, 2021 at 12:12
  • Does this answer your question? Java "?" Operator for checking null - What is it? (Not Ternary!) Commented Jan 14, 2021 at 12:13
  • I tried to say shortened ternary operator or the Elvis operator from @CarlosLópezMarí's comment. Commented Jan 14, 2021 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". Commented Jan 14, 2021 at 12:22

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 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));.
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 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.
@SamiŞahin You can write a generic utility function as static <T> 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.
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), ""));

2 Comments

Can I use this even if my variables are not String? Let's say I'm trying to setQuantity and check if getQuantity returns null or not.
No, it only works in this case (because it produces String).
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(""));

1 Comment

You certainly can do this… but you shouldn’t.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.