Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Do nothing" using ternary operator [duplicate]

Tags:

java

android

I want to use the ternary operator like this - checking only the true part of the statement:

foo() ? bar() : /* Do nothing */; 

Is it possible to exclude the logic of the "else" part of this statement? I tried using return; but the compiler gives the error. Basically all I want to achieve is a statement using ternary operator which would look like this:

foo() ? bar(); 

Is this achievable?

like image 317
domi Avatar asked Jun 15 '15 22:06

domi


People also ask

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.

How do you do nothing in a ternary?

A ternary operator doesn't have a do nothing option for either the true or false path since the entire ternary command returns a value and so both paths must set a value. The “do nothing” value will depend on what value you want the ternary operator to return to indicate “do nothing”.

Is it good practice to use ternary operator?

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.

Is ternary operator better than if else?

Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.


2 Answers

The ternary operator is usually used to immediately assign a value.

String a = bar() ? foo() : null; 

For your usecase, you can simply use an if construct:

if (foo())     bar(); 
like image 128
wvdz Avatar answered Oct 03 '22 00:10

wvdz


If it would work like that we wouldn't call it ternary anymore. I think the only way is that do something which does nothing. for example call a method which has empty body, or if you assign a value from this operation to a variable just assign a default value.

like image 27
A.v Avatar answered Oct 03 '22 01:10

A.v