As the title says i was wondering if there is a way to use ternary operators with multiple statements in Objective C.
I know it can be easily done in some other languages like javascript, php, C etc but i couldn't find a solution for Objective C.
I want to implement something like this:
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
Basically i just want to avoid a lot of if-else blocks to maintain better code readability.
Please also suggest if using ternary operators instead of if-else blocks can harm app performance to a noticeable extent.
The Conditional operator ?: is not a replacement for an if/else block. I'm sure you could tweak the logic to make it work, but that would only obscure the meaning more.
My question is, "what are you saving?"
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
if (a > b) { statement1; statement2; statement3; } else { statement1; statement2; }
The if/else block is a grand total of 7 characters longer.
An even bigger question is, "Can the logic be composed in a better way?"
Look to see if the flow can be done differently with fewer ifs.
Look for places to create sub-routines.
You can easily do this; just be aware that the ternary operator can only include expressions, including comma expressions. So your statements can only be expressions, assignments, method calls etc. but no if / return / while and so on. And the ternary operator wants a result, so the last expressions in each group must have the same type; you can just add (void) 0 at the end of each list.
That said, you are most definitely not making your code more readable. Everyone reading it will start swearing at you and doubt your mental sanity. So don't do it.
The solution for your question (#user3752049) is:
a > b ? ^{ statement1; statement2; statement3;}() : ^{statement1; statement2;}();
Thanks
Related
I used an || operator within the Kotlin IDEA but was throwing an error. This confused me, one of the first queries when searching google was a closed stack overflow thread with a snarky "answer" comment which wasn't helpful.
The first query in google hit is some function "or" gibberish.
My code:
if(inputAmount >= 0 || inputAmount = -99)
I understand what is "wrong". there was some logic errors the second part of the "if" statement should have been inputAmount == -99. In my case, the code needed to further be adjusted because of the actual type that was being used.
if(inputAmount >= 0.0 || inputAmount.toInt() == -99)
This appears to be different then other languages in that other languages just simply allow you to have your "logic" error with the "inputAmount = -99". So the '||' operator is allowed and is similar to most other languages.
So first step if encounter this error is to make sure your logic is correct. (check)
infix functions > sense according to the documentation "or" and "and" are infix functions that don't use the short circuit, is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'?
when referring to the infix 'or' how do people refer to that in Kotlin?
in boolean logic takes statements. A=b is a statement that is always true
No, it isn't. In C, C++ and Java it's an expression, and its value is the value of b. If b is false, it's false, if b is 10, it's 10. And you really don't want to confuse "statements" in programming languages with "statements" in logic; they are entirely different things.
Separately, C and C++ (but not Java) allow || to work on all integral types, and not just booleans (because they didn't originally have booleans as a separate type).
when referring to the infix function 'or' how do Kotlin folk typically refer to that?
Bitwise or for integral types, and I've never actually seen anyone use non-short-circuiting or on booleans, but if I had to I'd call it... well, non-short-circuiting or.
is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'
Both || and or (on booleans) are "logical 'or'" and I don't see any problem with calling them simply 'or'. If you need to distinguish use short-circuiting vs non-short-circuiting. But again, I've never actually ran into a use of the non-short-circuiting version.
Sorry in advance if this has been answered somewhere, but I did look around for a while and didn't find anything.
I'm coding in Objective-C, but this is mostly a general coding question. I'm essentially wondering if there is a proper, professional way to write if else statements involving booleans. Specifically, I would like to know if
There is a "fastest" "best" coding practice for the ordering of if else statments involving booleans
Is there a more aesthetically popular way of writing them?
So, for example, here are three different ways I'm wondering about
Method 1
if (myBool)
{
//Do something
}
else
{
//Do something else
}
Method 2
if (myBool)
{
//Do something
}
else if (!myBool)
{
//Do something else
}
Method 3
if (myBool)
{
//Do something
}
if (!myBool)
{
//Do something else
}
I know this sounds kinda dumb and is really harping on subtle details. I'm mostly wondering about these different methods in terms of code readability. It almost seems like method 2/3 is best to me in terms of readability. This allows you to search for specific cases of that variable, which might be easier in large files. Maybe this is a minute point, and really doesn't matter though.
Method 1 seems like the most common to me, and is what I would pick by default. But for more experienced coders out there, is there a specific way to do this, or just preference?
1. There is a "fastest" "best" coding practice for the ordering of if else statments involving booleans
"Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision...[putting the normal case after the if] puts the focus on reading the main flow rather than on wading through the exceptional cases, so the code is easier to read overall."
Code Complete, 2nd Edition, pages 356-357.
2. Is there a more aesthetically popular way of writing them?
In normal logic flow it is better to use Method 1
One thing to take into consideration is the values you are expecting.
In this case, boolean only has two possible values, and therefore makes sense if we use Method 1 as the most "convenient" way.
Method 2 works effectively when you have more than 2 possible values to be checked.
Method 3 on the other hand is convenient when value of myBool may change after the first [if] condition.
I think Method1 is common and efficient also.
1. In method3 if myBool is true then there is no need of checking 2nd if condition.
2. In method2 there is no need of 2nd if because bool have only 2 values either it is yes/true or no/false. Use else if only there are more than 2 cases.
3. When you are using if else or if else if you should provide condition according to probability. Means condition which satisfied most must be placed first.
A neat way of doing if/else for very simple assignments
int num;
if (isNegative) {
num = -1;
} else {
num = 1;
}
Short hand would be:
int num = isNegative ? -1 : 1; // --> condition ? true : false
I wouldn't suggest this for complex conditions/assignments as can get messy. But I've found it useful for compacting very simple if/else assignments.
I think this is a really general programming question, since boolean syntax is more or less the same in a lot of common languages.
But still my question is for php and javascript mainly.
Suppose I want to write an if statement which returns true if a variable is equal to 2,3, or 5.
And this variable has a very long name, so like this:
if((An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==2)
|| (An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==3)
||(An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==5))
{
return true;
}
and I really want my code look shorter, it is less depressing to read it months after :)
so can I simplify this into something like
if(An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==2||3||5)
Thanks for help !
Cheater way out: For that if statement, assign An_Object_With_A_Long_Name to Object i. (If you plan to have to compare this variable several times, assign Object i the pointer of An_Object_With_A_Long_Name.
Can someone explain the inactive ? #"inactive": #"active"?
The ? : is a boolean conditional structure (wrong term) it seems but I'm not quite getting it. Don't know what it is called so can't look it up.
Seems something like:
someBooleanValue ? if it is false use what is before colon : else use
what is after
I get that it is being used to determine which string to use as the format token (in the code below). I just don't know what this ? : bit is called and what limitations/cautions/abuses there may be with it.
(and isn't ObjC like rilly hard to format in a civilized way)
UIAlertView* av = [[UIAlertView alloc] initWithTitle:#"Hey"
message:[NSString
stringWithFormat:#"While %#, I received a local notification: %#",
inactive ? #"inactive": #"active", n.alertBody]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
This ?: thing is called a conditional operator or a ternary operator.
It's represents a simple condition
if ( CONDITION )
x = a;
else
x = b;
that can be translated to
x = CONDITION ? a : b
From that you can probably derive the functionality you're trying to accomplish/understand. Keep in mind that, although you could probably use it as a substitute to the normal if/else-if/else structure, it is considered bad programming the usage of the ternary operator out of any "assignment related action".
In the wikipedia page for it you can find a great variety of examples of the conditional operators used in different programming languages. Check this one too, the ternary operator page.
Obs: turns out that a ternary operator is not necessarily a conditional expression, but rather any operator that takes three arguments. Since for most of the programming languages the only ternary operator is the inline-if... well, that's what it's usually called.
It is called conditional operator, a kind of ternary operator (as opposed to more familiar binary a+b or unary !flag operators).
Conditional operator takes a condition, evaluates it, and returns its second or third operand depending on that result.
You can read more information here.
The use of this operator can greatly reduce code length when a lot of simple ifs are involved.
It's a ternary operator, but you have it backwards -- if the boolean is true, then do the thing before the colon, otherwise, the one after.
This is called the ternary operator and it works exactly the way you described it:
expression ? value if true : value if false;
For instance, you could use it for something like this to avoid a if - else:
int maxValue = a > b ? a : b;
Edit: #dasblinkenlight is correct, the operator you're talking about is actually called a conditional operator, which is a kind of ternary operator.
Currently, I'm using && and || instead of AND and OR because that's how I was taught. In most languages, however, both are valid syntax. Are there any advantages to one or the other in any language?
I did try to search for this question, but it's a bit hard. It doesn't interpret my input correctly.
You ask “Are there any advantages to one or the other in any language?” This is, of course, dependent on the programming language.
Languages that implement both and and && (and correspondingly or and ||) will do it one of two ways:
Both behave exactly the same way. In which case, there is no advantage provided by the language in using one over the other.
Each behaves differently. In which case, the advantage is that you can get different behaviour by using one or the other.
That all sounds a bit facetious, but it's really as specific as one can get without talking about a specific language. Your question explicitly wants to know about all languages, but it's a question that needs to be answered per language.
Perl has all four of {&& || and or} but they differ in their precedence. "and" and "or" have really low precedence so you can do things like "complex-function-call-here or die $!" and you won't accidentally have "or" slurp up something on its left side that you didn't want it to.
it depends on the language, but on PHP, I'd be careful about using && versus "and". The ones i often use are "&&" and "||"
http://us3.php.net/manual/en/language.operators.logical.php
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
In some languages && will have a higher operator precedence than AND.
If both works fine, then I would say it's really personal preference, in most cases, they are compiled into same binary code like this : 11100010001000101001001010 [not real code, just an example].
&& = two keystrokes of the same key.
AND = three keystrokes of different keys.
I'm not sure what language you are using, but some languages differentiate between a normal boolean operator and a short-circuit operator. For example, the following are normal boolean operators in MATLAB:
C = or(A,B);
C = A | B; % Exactly the same as above
However, this is a short-circuit operator:
C = A || B;
The short-circuit syntax will evaluate the first argument and then, depending on the value, will potentially skip over evaluating the second argument. For example, if A is already true, B doesn't have to be evaluated for an OR operation, since the result is guaranteed to be true. This is helpful when B is replaced with a logical operation that involves some kind of expensive computation.
Here's a wikipedia link discussing short-circuit operators and their syntax for a few languages.
Unless there aren't any precedence issues, I'd say there are differences in readability. Consider the following:
if (&x == &y && &y == &z) {
// ..
}
#define AND &&
if (&x == &y AND &y == &z) {
// ..
}