Method Call Using Ternary Operator

Method Call using Ternary Operator

The reason why the above statement does not work was provided by the other users and effectively did not answer my true question.

After playing around some more, I figured out that you CAN use this operator to do the above statement, but it results in some bad code.

If I were to change the above statement to;

int a = 5;
int b = 10;
int result = a == b ? doThis() : doThat();

private int doThis()
{
MessageBox.Show("Did this");
return 0;
}
private int doThat()
{
MessageBox.Show("Did that");
return 1;
}

This code will compile and execute the way it should. However, if these methods were not originally intended to return anything, and referenced other areas in the code, you now have to handle a return object each time to call these methods.

Otherwise, you now can use a ternary operator for a one-line method chooser and even know which method it called in the next line using the result.

int result = a == b ? doThis() : doThat();

if (result == 0)
MessageBox.Show("You called doThis()!");

Now, this code is absolutely pointless and could be easily done by a If Else, but I just wanted to know if it could be done, and what you had to do to get it to work.

Now that I know that you can effectively return any type in these methods, this might become a little more useful. It may be considered a "Bad Coding Practice" but might become very useful in situations it was never MEANT for.

You could get access to one object or another based on any condition and that might be very useful in one line of code.

UserPrivileges result = user.Group == Group.Admin ? GiveAdminPrivileges() : GiveUserPrivileges();

private UserPrivileges GiveAdminPrivileges()
{
//Enter code here
return var;
}
private UserPrivileges GiveUserPrivileges()
{
//Enter code here
return var;
}

Sure, this can be done by an If Statement, but I think that using the Ternary Operator for other uses makes programming fun. Now, this may not be as efficient as an If Else statement, in which case, I would never use this.

JAVA calling a method using a ternary operator

This will not work, as it is not the intended use of the ternary operator.

If you really want it to be 1 line, you can write:

if (x==1) doThisMethod(); else doThatMethod();

Use ternary alike method for calling methods

You can only write

testString.equals("test") ? doSomething() : doSomethingElse();

if doSomething() and doSomethingElse() both return something, and those somethings have either exactly the same type, or are covariant types. Setting both functions to return a boolean would be sufficient.

This is because the entire thing is an expression, and an expression has a value as well as a well-defined type.

If you are not wanting to do anything with the return value, then use an if statement.

Conditional ternary with method call to db

Yes, it will always be two calls. The fact is between the first call and the second call, the result of fetchFromDb() can change. There is no way for the compiler to predict that change in value, unless it is a well known deterministic function. Deterministic being the key word here. Even then there may not be compiler optimization for such things.

Using a ternary condition with methods is not bad practice per se, but it is less readable than a simple if statement.

The only way to guarantee a single call is to code a single call.

var result;
var fetchResult = fetchFromDb();
if (fetchResult == null) {
result = defaultValue;
} else {
result = result.property;
}

Or if you insist on using a ternary

var fetchResult = fetchFromDb()
var result = (fetchResult == null) ? defaultValue : result.property;

I really think this is much clearer than a ternary. Having code on a single line does not infer beautiful code.

Can Java's ternary/conditional operator (?:) be used to call methods instead of assigning values?

Think of ternary operators like a method in this case. Saying a ? b : c is (for the intents and purposes you're considering, see lasseespeholt's comment) equivalent to calling the pseudocode method:

ternary(a, b, c)
if a
return b
else
return c

which is why people can say things like x = a ? b : c; it's basically like saying x = ternary(a, b, c). When you say (condition) ? doThis() : doThat(), you're in effect saying:

if condition
return doThis()
else
return doThat()

Look what happens if we try to substitute the methods for what they return

 if condition
return ???
else
return ???

It doesn't even make sense to consider it. doThis() and doThat() don't return anything, because void isn't an instantiable type, so the ternary method can't return anything either, so Java doesn't know what to do with your statement and complains.

There are ways around this, but they're all bad practice (you could modify your methods to have a return value but don't do anything with what they return, you could create new methods that call your methods and then return null, etc.). You're much better off just using an if statement in this case.

EDIT Furthermore, there's an even bigger issue. Even if you were returning values, Java does not consider a ? b : c a statement in any sense.

Calling functions in C# ternary operator

The ternary operator is used to return values and those values must be assigned.

If you want to invoke void methods in a ternary operator, you can use delegates like this:

String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();

How to have two function calls inside ternary operator in JSX?

You could return an array of components:

{
views === "monthly"
? [this.renderDays(), this.renderCells()]
: null
}

Or if the methods return arrays itself, just spread them:

 {
views === "monthly"
? [...this.renderDays(), ...this.renderCells()]
: null
}

Decide which member function to call by ternary operator

You can use member function pointers, but you need special syntax to call the function via the pointer:

struct X {
void foo() {}
void bar() {}
};

int main() {
X thisThing;
bool b = false;
(thisThing.*(b ? &X::foo : &X::bar))();
}

However, I would not recommend to actually use it like this (unless there are reasons not shown in the question). Note that it won't work like this when foo or bar are overloaded.

Anyhow, in my opinion also your other examples are not good use-cases for the conditional operator. The conditional operator is not just a equivalent replacement for if-else. It has slightly different use-cases. Sometimes one uses the conditional operator to determine the common type of two expressions. Sometimes you cannot use an if-else. For example when initializing a reference:

 int& x = a ? c : d;   // cannot be done with if/else

My advice is: Don't use the conditional operator to save on typing compared to an if-else. The difference between if-else and the conditional operator is almost never the amount of code you have to write only.

Using ternary operators in a function with javascript

I am curious as to if it can be rewritten inside of the function call.

Yes, it can. But, if you do it there, then there is no need for a variable. You would be passing the function's argument directly inline.

Having said that, you can't pass that MSys.alert() statement as the "else" value because it will be executed in all cases. You'd have to pass a value there that the function can use as its input argument

send_command(MSys.inShip ? 'ship launch' : 'some other string');

Here's an example:

function foo(x){

console.log(x);

}

// If a random number is even, pass "even". If not, pass "odd"

foo(Math.floor(Math.random() * 10) % 2 === 0 ? "even" : "odd");


Related Topics



Leave a reply



Submit