Is it possible to change this:
if(String!= null) { callFunction(parameters); } else { // Intentionally left blank }
...to a ternary operator?
The ternary conditional operator ?: allows us to define expressions in Java. It's a condensed form of the if-else statement that also returns a value.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion). Save this answer.
Overall, you should only use ternary statements when the resulting statement is short. Otherwise, write a normal if statement. The purpose of a ternary operator is to make your code more concise and readable. Moving a complex if statement into a ternary operator goes against that goal.
Yes! The second is vastly more readable.
Well, the ternary operator
in Java acts like this...
return_value = (true-false condition) ? (if true expression) : (if false expression);
...Another way of looking at it...
return_value = (true-false condition) ? (if true expression) : (if false expression);
You question is kind of vague and we have to assume here.
If (and only if) callFunction(...)
declares a non-void
return value (Object
, String
, int
, double
, etc..) - it seems like it does not do that via your code - then you could do this...
return_value = (string != null) ? (callFunction(...)) : (null);
If callFunction(...)
does not return a value, then you cannot use the ternary operator! Simple as that. You will be using something that you don't need.
Nonetheless, ternary operator should represent alternative assignments only!! Your code does not seem to do that, so you should not be doing that.
This is how they should work...
if (obj != null) { // If-else statement retVal = obj.getValue(); // One alternative assignment for retVal } else { retVal = ""; // Second alternative assignment for retVale }
This can be converted to...
retVal = (obj != null) ? (obj.getValue()) : ("");
Since it seems like you might be trying to just refactor this code to be a one-liner, I have added the following
Also, if your false-clause is truely empty, then you can do this...
if (string != null) { callFunction(...); } // Take note that there is not false clause because it isn't needed
OR
if (string != null) callFunction(...); // One-liner
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With