Why doesn't Kotlin support "ternary operator" [closed] - ternary-operator

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Explain: This question is more about the design intentions of Kotlin. Many expression languages support both Ternary operator and if expression [e.g., Ruby, Groovy.]
First of all, I know Groovy supports both Ternary operator and Elvis operator: Ternary operator in Groovy. So I don't think it's a syntax problem.
Then the official documents said:
In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
And this doesn't convince me. Because Kotlin support Elvis operator which ordinary if works just fine in that role either.
I think ternary operator is sometimes better than ordinary if, though I wonder why doesn't Kotlin just support ternary operator?

In languages which have ternary operator you use it like this
String value = condition ? foo : bar;
In Kotlin you can do the same thing using if and else
var value = if(condition) foo else bar;
Its bit verbose than the ternary operator. But designers of Kotlin have thought it is ok. You can use if-else like this because in Kotlin if is an expression and returns a value
Elvis operator is essentially a compressed version of ternary conditional statement and equivalent to following in Kotlin.
var value = if(foo != null) foo else bar;
But if Elvis operator is used it simplify as follows
var value = foo ?: bar;
This is considerable simplification and Kotlin decided to keep it.

Because if .. else .. works fine. Take a look:
fun main(args: Array<String>) {
var i = 2
println("i ${ if(i == 1) "equals 1" else "not equals 1" }")
}

Ternary operator has its problems, for example it is hard to read with big expressions. Here is a line from my C++ project where I used ternary operator:
const long offset = (comm_rank > 0) ? task_size_mod + (comm_rank - 1) * task_size : 0;
I would rather use an if else expression here since it is so much more visible.
Answering you question, I am aware of two reasons why ternary operator was not implemented in Kotlin:
1) Since if else is an expression anyway, it can replace ? :
2) Experience from other languages (C++) shows that ? : provokes hard-to-read code, so it is better to be left out

Programmers at some point, have to make a decision to execute a block of code, this is known as Control Flow. If statement is most basic way to control flow in Kotlin. Important point to note that in Kotlin, If is an expression not a statement as it is Java.
Statement: A statement is an executed line which does not return a
value. As a result, statement cannot sit right side of an equal
sign.
Expression: An expression returns a value.So the result of a Kolin
If expression can be assigned to a variable.
Because of this the ternary expression would be redundant and does not exists in Kotlin. In Java we would write (Here is the answer of your question)
For Example
Ternary Operator in Java
int lowest = (a < b) ? a : b;
In Kotlin we can write something similar using the if expression.
val lowest = if(a < b) a else b
NOTE:
When If is used as an expression it must contain an else clause. The expression must have a value in all case.

Because if-else is an expression in Kotlin :
String check = number % 2 == 0 ? "even" : "odd" // Java
if (number % 2 == 0) "even else "odd" // Kotlin
So that's why there are no ternary operator in Kotlin, Moreover you can use when expressions too, it's so handy if you want to provide a lot of possible execution paths

Related

Groovy compareTo for CustomClass and numbers/strings

I am building DSL and try to define a custom class CustomClass that you can use in expressions like
def result = customInstance >= 100 ? 'a' : 'b'
if (customInstance == 'hello') {...}
Groovy doesn't call == when your class defines equals and implements Comparable (defines compareTo) at the same time.
Instead Groovy calls compareToWithEqualityCheck which has a branching logic. And unless your custom DSL class is assignable from String or Number your custom compareTo won't be called for the example above.
You can't extend CustomClass with String.
I feel like I am missing something. Hope you can help me figure out how to implement a simple case like I showed above.
Here is a short answer first: You could extend GString for the CustomClass. Then its compareTo method will be called in both cases - when you check for equality and when you actually compare.
Edit: Considering the following cases, it will work for 1 and 2, but not for 3.
customInstance >= 100 // case 1
customInstance == 'hallo' // case 2
customInstance == 10 // case 3
Now I will explain what I understand from the implementation in Groovy's ScriptBytecodeAdapter and DefaultTypeTransformation.
For the == operator, in case Comparable is implemented (and there is no simple identity), it tries to use the interface method compareTo, hence the same logic that is used for other comparison operators. Only if Comparable is not implemented it tries to determine equality based on some smart type adjustments and as an ultima ratio falls back to calling the equals method. This happens in DefaultTypeTransformation.compareEqual#L603-L608
For all other comparison operators such as >=, Groovy delegates to the compareToWithEqualityCheck method. Now this method is called with the equalityCheckOnly flag set to false, while it is set to true for the first case when it the invocation originates from the == operator. Again there is some Groovy smartness happening based on the type of the left side if it is Number, Character, or String. If none applies it ends up calling the compareTo method in DefaultTypeTransformation.compareToWithEqualityCheck#L584-L586.
Now, this happens only if
!equalityCheckOnly || left.getClass().isAssignableFrom(right.getClass())
|| (right.getClass() != Object.class && right.getClass().isAssignableFrom(left.getClass())) //GROOVY-4046
|| (left instanceof GString && right instanceof String)
There are some restrictions for the case of equalityCheckOnly, hence when we come from the == operator. While I can not explain all of those I believe these are to prevent exceptions to be thrown under specific circumstances, such as the issue mentioned in the comment.
For brevity I omitted above that there are also cases that are handled upfront in the ScriptBytecodeAdapter and delegated to equals right away, if left and right hand side are both of the same type and one of Integer, Double or Long.

Statements vs Expressions in Haskell, Ocaml, Javascript

In Haskell, afaik, there are no statements, just expressions. That is, unlike in an imperative language like Javascript, you cannot simply execute code line after line, i.e.
let a = 1
let b = 2
let c = a + b
print(c)
Instead, everything is an expression and nothing can simply modify state and return nothing (i.e. a statement). On top of that, everything would be wrapped in a function such that, in order to mimic such an action as above, you'd use the monadic do syntax and thereby hide the underlying nested functions.
Is this the same in OCAML/F# or can you just have imperative statements?
This is a bit of a complicated topic. Technically, in ML-style languages, everything is an expression. However, there is some syntactic sugar to make it read more like statements. For example, the sample you gave in F# would be:
let a = 1
let b = 2
let c = a + b
printfn "%d" c
However, the compiler silently turns those "statements" into the following expression for you:
let a = 1 in
let b = 2 in
let c = a + b in
printfn "%d" c
Now, the last line here is going to do IO, and unlike in Haskell, it won't change the type of the expression to IO. The type of the expression here is unit. unit is the F# way of expressing "this function doesn't really have result" in the type system. Of course, if the function doesn't have a result, in a purely functional language it would be pointless to call it. The only reason to call it would be for some side-effect, and since Haskell doesn't allow side-effects, they use the IO monad to encode the fact the function has an IO producing side-effect into the type system.
F# and other ML-based languages do allow side-effects like IO, so they have the unit type to represent functions that only do side-effects, like printing. When designing your application, you will generally want to avoid having unit-returning functions except for things like logging or printing. If you feel so inclined, you can even use F#'s moand-ish feature, Computation Expressions, to encapsulate your side-effects for you.
Not to be picky, but there's no language OCaml/F# :-)
To answer for OCaml: OCaml is not a pure functional language. It supports side effects directly through mutability, I/O, and exceptions. In many cases it treats such constructs as expressions with the value (), the single value of type unit.
Expressions of type unit can appear in a sequence separated by ;:
let s = ref 0 in
while !s < 10 do
Printf.printf "%d\n" !s; (* This has type unit *)
incr s (* This has type unit *)
done (* The while as a whole has type unit *)
Update
More specifically, ; ignores the value of the first expression and returns the value of the second expression. The first expression should have type unit but this isn't absolutely required.
# print_endline "hello"; 44 ;;
hello
- : int = 44
# 43 ; 44 ;;
Warning 10: this expression should have type unit.
- : int = 44
The ; operator is right associative, so you can write a ;-separated sequence of expressions without extra parentheses. It has the value of the last (rightmost) expression.
To answer the question we need to define what is an expression and what is a statement.
Distinction between expressions and statements
In layman terms, an expression is something that evaluates (reduces) to a value. It is basically something, that may occur on the right-hand side of the assignment operator. Contrary, a statement is some directive that doesn't produce directly a value.
For example, in Python, the ternary operator builds expressions, e.g.,
'odd' if x % 2 else 'even'
is an expression, so you can assign it to a variable, print, etc
While the following is a statement:
if x % 2:
'odd'
else:
'even'
It is not reduced to a value by Python, it couldn't be printed, assigned to a value, etc.
So far we were focusing more on the semantical differences between expressions and statements. But for a casual user, they are more noticeable on the syntactic level. I.e., there are places where a statement is expected and places where expressions are expected. For example, you can put a statement to the right of the assignment operator.
OCaml/Reason/Haskell/F# story
In OCaml, Reason, and F# such constructs as if, while, print etc are expressions. They all evaluate to values and can occur on the right-hand side of the assignment operator. So it looks like that there is no distinction between statements and expressions. Indeed, there are no statements in OCaml grammar at all. I believe, that F# and Reason are also not using word statement to exclude confusion. However, there are syntactic forms that are not expressions, for example:
open Core_kernel
it is not an expression, definitely, and
type students = student list
is not an expression.
So what is that? In the OCaml parlance, they are called definitions, and they are syntactic constructs that can appear in the module on the, so called, top-level. For example, in OCaml, there are value definitions, that look like this
let harry = student "Harry"
let larry = student "Larry"
let group = [harry; larry]
Every line above is a definition. And every line contains an expression on the right-hand side of the = symbol. In OCaml there is also a let expression, that has form let <v> = <exp> in <exp> that should not be confused with the top-level let definition.
Roughly the same is true for F# and Reason. It is also true for Haskell, that has a distinction between expressions and declarations. It actually should be true to probably every real-world language (i.e., excluding brainfuck and other toy languages).
Summary
So, all these languages have syntactic forms that are not expressions. They are not called statements per se, but we can treat them as statements. So there is a distinction between statements and expressions. The main difference from common imperative languages is that some well-known statements (e.g., if, while, for) are expressions in OCaml/F#/Reason/Haskell, and this is why people commonly say that there is no distinction between expressions and statements.

Ternary Operations for 2 variables

I'd like to ask what is the general opinion about using 2 Ternary operators instead of an if/else block for 2 variables.
Giving an example to make it clearer,
The if/else block:
var foo;
var bar;
if (boolean_expression) {
foo = value1;
bar = value2;
} else {
foo = value3;
bar = value4;
}
Using 2 Ternary Operations:
var foo = (boolean_expression) ? value1 : value3;
var bar= (boolean_expression) ? value2 : value4;
Obviously the if/else block is more efficient, since it only evaluates the boolean_expression once, whereas the 2 ternary operations evaluate it twice.
However, using ternary operations is, in my opinion, so much cleaner and readable, that I've recently decided on sacrificing the minimal efficiency difference between the two of them to improve my code's readability. (Provided the code isn't critical or executed too frequently)
Also, I would weakly argue the same for 3 variables.
Am I doing a horrible thing to my code, or is there a better way I'm not aware?
I'm coding in c#, but I guess this question matters for any language that has the ternary operation.
I guess this question matters for any language that has the ternary
operation
Some languages provide this:
(foo, bar) = (boolean_expression) ? (value1, value2) : (value3, value4);

What's the name of this programming feature?

In some dynamic languages I have seen this kind of syntax:
myValue = if (this.IsValidObject)
{
UpdateGraph();
UpdateCount();
this.Name;
}
else
{
Debug.Log (Exceptions.UninitializedObject);
3;
}
Basically being able to return the last statement in a branch as the return value for a variable, not necessarily only for method returns, but they could be achieved as well.
What's the name of this feature?
Can this also be achieved in staticly typed languages such as C#? I know C# has ternary operator, but I mean using if statements, switch statements as shown above.
It is called "conditional-branches-are-expressions" or "death to the statement/expression divide".
See Conditional If Expressions:
Many languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which just perform an action).
That is, if (expr) { ... } is an expression (could possible be an expression or a statement depending upon context) in the language grammar just as ?: is an expression in languages like C, C# or Java.
This form is common in functional programming languages (which eschew side-effects) -- however, it is not "functional programming" per se and exists in other language that accept/allow a "functional like syntax" while still utilizing heavy side-effects and other paradigms (e.g. Ruby).
Some languages like Perl allow this behavior to be simulated. That is, $x = eval { if (true) { "hello world!" } else { "goodbye" } }; print $x will display "hello world!" because the eval expression evaluates to the last value evaluated inside even though the if grammar production itself is not an expression. ($x = if ... is a syntax error in Perl).
Happy coding.
To answer your other question:
Can this also be achieved in staticly typed languages such as C#?
Is it a thing the language supports? No. Can it be achieved? Kind of.
C# --like C++, Java, and all that ilk-- has expressions and statements. Statements, like if-then and switch-case, don't return values and there fore can't be used as expressions. Also, as a slight aside, your example assigns myValue to either a string or an integer, which C# can't do because it is strongly typed. You'd either have to use object myValue and then accept the casting and boxing costs, use var myValue (which is still static typed, just inferred), or some other bizarre cleverness.
Anyway, so if if-then is a statement, how do you do that in C#? You'd have to build a method to accomplish the goal of if-then-else. You could use a static method as an extension to bools, to model the Smalltalk way of doing it:
public static T IfTrue(this bool value, Action doThen, Action doElse )
{
if(value)
return doThen();
else
return doElse();
}
To use this, you'd do something like
var myVal = (6 < 7).IfTrue(() => return "Less than", () => return "Greater than");
Disclaimer: I tested none of that, so it may not quite work due to typos, but I think the principle is correct.
The new IfTrue() function checks the boolean it is attached to and executes one of two delegates passed into it. They must have the same return type, and neither accepts arguments (use closures, so it won't matter).
Now, should you do that? No, almost certainly not. Its not the proper C# way of doing things so it's confusing, and its much less efficient than using an if-then. You're trading off something like 1 IL instruction for a complex mess of classes and method calls that .NET will build behind the scenes to support that.
It is a ternary conditional.
In C you can use, for example:
printf("Debug? %s\n", debug?"yes":"no");
Edited:
A compound statement list can be evaluated as a expression in C. The last statement should be a expression and the whole compound statement surrounded by braces.
For example:
#include <stdio.h>
int main(void)
{
int a=0, b=1;
a=({
printf("testing compound statement\n");
if(b==a)
printf("equals\n");
b+1;
});
printf("a=%d\n", a);
return 0;
}
So the name of the characteristic you are doing is assigning to a (local) variable a compound statement. Now I think this helps you a little bit more. For more, please visit this source:
http://www.chemie.fu-berlin.de/chemnet/use/info/gcc/gcc_8.html
Take care,
Beco.
PS. This example makes more sense in the context of your question:
a=({
int c;
if(b==a)
c=b+1;
else
c=a-1;
c;
});
In addition to returning the value of the last expression in a branch, it's likely (depending on the language) that myValue is being assigned to an anonymous function -- or in Smalltalk / Ruby, code blocks:
A block of code (an anonymous function) can be expressed as a literal value (which is an object, since all values are objects.)
In this case, since myValue is actually pointing to a function that gets invoked only when myValue is used, the language probably implements them as closures, which are originally a feature of functional languages.
Because closures are first-class functions with free variables, closures exist in C#. However, the implicit return does not occur; in C# they're simply anonymous delegates! Consider:
Func<Object> myValue = delegate()
{
if (this.IsValidObject)
{
UpdateGraph();
UpdateCount();
return this.Name;
}
else
{
Debug.Log (Exceptions.UninitializedObject);
return 3;
}
};
This can also be done in C# using lambda expressions:
Func<Object> myValue = () =>
{
if (this.IsValidObject) { ... }
else { ... }
};
I realize your question is asking about the implicit return value, but I am trying to illustrate that there is more than just "conditional branches are expressions" going on here.
Can this also be achieved in staticly
typed languages?
Sure, the types of the involved expressions can be statically and strictly checked. There seems to be nothing dependent on dynamic typing in the "if-as-expression" approach.
For example, Haskell--a strict statically typed language with a rich system of types:
$ ghci
Prelude> let x = if True then "a" else "b" in x
"a"
(the example expression could be simpler, I just wanted to reflect the assignment from your question, but the expression to demonstrate the feature could be simlpler:
Prelude> if True then "a" else "b"
"a"
.)

To ternary or not to ternary? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm personally an advocate of the ternary operator: () ? :
I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.
What are your feelings on it? What interesting code have you seen using it?
Use it for simple expressions only:
int a = (b > 10) ? c : d;
Don't chain or nest ternary operators as it hard to read and confusing:
int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;
Moreover, when using ternary operator, consider formatting the code in a way that improves readability:
int a = (b > 10) ? some_value
: another_value;
It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.
I love them, especially in type-safe languages.
I don't see how this:
int count = (condition) ? 1 : 0;
is any harder than this:
int count;
if (condition)
{
count = 1;
}
else
{
count = 0;
}
I'd argue that ternary operators make everything less complex and more neat than the alternative.
Chained I'm fine with - nested, not so much.
I tend to use them more in C simply because they're an if statement that has value, so it cuts down on unnecessary repetition or variables:
x = (y < 100) ? "dog" :
(y < 150) ? "cat" :
(y < 300) ? "bar" : "baz";
rather than
if (y < 100) { x = "dog"; }
else if (y < 150) { x = "cat"; }
else if (y < 300) { x = "bar"; }
else { x = "baz"; }
In assignments like this, I find it's less to refactor, and clearer.
When I'm working in ruby on the other hand, I'm more likely to use if...else...end because it's an expression too.
x = if (y < 100) then "dog"
elif (y < 150) then "cat"
elif (y < 300) then "bar"
else "baz"
end
(Although, admittedly, for something this simple, I might just use the ternary operator anyway.)
The ternary ?: operator is merely a functional equivalent of the procedural if construct. So as long as you are not using nested ?: expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).
But there are plenty of situations where conservative use of the ?: operator can result in code that is actually easier to read than otherwise. For example:
int compareTo(Object object) {
if((isLessThan(object) && reverseOrder) || (isGreaterThan(object) && !reverseOrder)) {
return 1;
if((isLessThan(object) && !reverseOrder) || (isGreaterThan(object) && reverseOrder)) {
return -1;
else
return 0;
}
Now compare that with this:
int compareTo(Object object) {
if(isLessThan(object))
return reverseOrder ? 1 : -1;
else(isGreaterThan(object))
return reverseOrder ? -1 : 1;
else
return 0;
}
As the code is more compact, there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the reverseOrder property) the end result isn't particularly terse.
It's a question of style, really; the subconscious rules I tend to follow are:
Only evaluate 1 expression - so foo = (bar > baz) ? true : false, but NOT foo = (bar > baz && lotto && someArray.Contains(someValue)) ? true : false
If I'm using it for display logic, e.g. <%= (foo) ? "Yes" : "No" %>
Only really use it for assignment; never flow logic (so never (foo) ? FooIsTrue(foo) : FooIsALie(foo) ) Flow logic in ternary is itself a lie, ignore that last point.
I like it because it's concise and elegant for simple assignment operations.
Like so many opinion questions, the answer is inevitably: it depends
For something like:
return x ? "Yes" : "No";
I think that is much more concise (and quicker for me to parse) than:
if (x) {
return "Yes";
} else {
return "No";
}
Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:
x && y && z >= 10 && s.Length == 0 || !foo
is not a good candidate for the ternary operator.
As an aside, if you are a C programmer, GCC actually has an extension that allows you to exclude the if-true portion of the ternary, like this:
/* 'y' is a char * */
const char *x = y ? : "Not set";
Which will set x to y assuming y is not NULL. Good stuff.
In my mind, it only makes sense to use the ternary operator in cases where an expression is needed.
In other cases, it seems like the ternary operator decreases clarity.
I use the ternary operator wherever I can, unless it makes the code extremely hard to read, but then that's usually just an indication that my code could use a little refactoring.
It always puzzles me how some people think the ternary operator is a "hidden" feature or is somewhat mysterious. It's one of the first things I learnt when I start programming in C, and I don't think it decreases readability at all. It's a natural part of the language.
By the measure of cyclomatic complexity, the use of if statements or the ternary operator are equivalent. So by that measure, the answer is no, the complexity would be exactly the same as before.
By other measures such as readability, maintainability, and DRY (don't repeat yourself), either choice may prove better than the other.
I use it quite often in places where I'm constrained to work in a constructor - for example, the new .NET 3.5 LINQ to XML constructs - to define default values when an optional parameter is null.
Contrived example:
var e = new XElement("Something",
param == null ? new XElement("Value", "Default")
: new XElement("Value", param.ToString())
);
or (thanks asterite)
var e = new XElement("Something",
new XElement("Value",
param == null ? "Default"
: param.ToString()
)
);
No matter whether you use the ternary operator or not, making sure your code is readable is the important thing. Any construct can be made unreadable.
I agree with jmulder: it shouldn't be used in place of a if, but it has its place for return expression or inside an expression:
echo "Result: " + n + " meter" + (n != 1 ? "s" : "");
return a == null ? "null" : a;
The former is just an example, and better internationalisation and localisation support of plural should be used!
If you're using the ternary operator for a simple conditional assignment I think it's fine. I've seen it (ab)used to control program flow without even making an assignment, and I think that should be avoided. Use an if statement in these cases.
(Hack of the day)
#define IF(x) x ?
#define ELSE :
Then you can do if-then-else as expression:
int b = IF(condition1) res1
ELSE IF(condition2) res2
ELSE IF(conditions3) res3
ELSE res4;
I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:
return (a>0)?a:0;
Compared to:
if(a>0) return a;
else return 0;
You also have the case where the solution is between the ternary operator and creating a function. For example in Python:
l = [ i if i > 0 else 0 for i in lst ]
The alternative is:
def cap(value):
if value > 0:
return value
return 0
l = [ cap(i) for i in lst ]
It is needed enough that in Python (as an example), such an idiom could be seen regularly:
l = [ ((i>0 and [i]) or [0])[0] for i in lst ]
this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.
I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):
isLeapYear =
((yyyy % 400) == 0)
? 1
: ((yyyy % 100) == 0)
? 0
: ((yyyy % 4) == 0)
? 1
: 0;
where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).
I don't mind it for small things like:
reportedAge = (isFemale && (Age >= 21)) ? 21 + (Age - 21) / 3 : Age;
or even slightly tricky things like:
printf ("Deleted %d file%s\n", n, (n == 1) ? "" : "s");
I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.
int result = do_something();
if( result != 0 )
{
debug_printf("Error while doing something, code %x (%s)\n", result,
result == 7 ? "ERROR_YES" :
result == 8 ? "ERROR_NO" :
result == 9 ? "ERROR_FILE_NOT_FOUND" :
"Unknown");
}
I almost never use the ternary operator, because whenever I do use it, it always makes me think a lot more than I have to later when I try to maintain it.
I like to avoid verbosity, but when it makes the code a lot easier to pick up, I will go for the verbosity.
Consider:
String name = firstName;
if (middleName != null) {
name += " " + middleName;
}
name += " " + lastName;
Now, that is a bit verbose, but I find it a lot more readable than:
String name = firstName + (middleName == null ? "" : " " + middleName)
+ " " + lastName;
Or:
String name = firstName;
name += (middleName == null ? "" : " " + middleName);
name += " " + lastName;
It just seems to compress too much information into too little space, without making it clear what's going on. Every time I saw the ternary operator used, I have always found an alternative that seemed much easier to read... then again, that is an extremely subjective opinion, so if you and your colleagues find ternary very readable, go for it.
I like them. I don't know why, but I feel very cool when I use the ternary expression.
I treat ternary operators a lot like GOTO. They have their place, but they are something which you should usually avoid to make the code easier to understand.
Well, the syntax for it is horrid. I find functional ifs very useful, and they often makes code more readable.
I would suggest making a macro to make it more readable, but I'm sure someone can come up with a horrible edge case (as there always is with C++).
I typically use it in things like this:
before:
if(isheader)
drawtext(x, y, WHITE, string);
else
drawtext(x, y, BLUE, string);
after:
drawtext(x, y, isheader == true ? WHITE : BLUE, string);
As others have pointed out they are nice for short simple conditions. I especially like them for defaults (kind of like the || and or usage in JavaScript and Python), e.g.
int repCount = pRepCountIn ? *pRepCountIn : defaultRepCount;
Another common use is to initialize a reference in C++. Since references have to be declared and initialized in the same statement you can't use an if statement.
SomeType& ref = pInput ? *pInput : somethingElse;
I like Groovy's special case of the ternary operator, called the Elvis operator: ?:
expr ?: default
This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.
I recently saw a variation on ternary operators (well, sort of) that make the standard "() ? :" variant seem to be a paragon of clarity:
var Result = [CaseIfFalse, CaseIfTrue][(boolean expression)]
or, to give a more tangible example:
var Name = ['Jane', 'John'][Gender == 'm'];
Mind you, this is JavaScript, so things like that might not be possible in other languages (thankfully).
Only when:
$var = (simple > test ? simple_result_1 : simple_result_2);
KISS.
For simple if cases, I like to use it. Actually it's much easier to read/code for instance as parameters for functions or things like that. Also to avoid the new line I like to keep with all my if/else.
Nesting it would be a big no-no in my book.
So, resuming, for a single if/else I'll use the ternary operator. For other cases, a regular if/else if/else (or switch).
For simple tasks, like assigning a different value depending on a condition, they're great. I wouldn't use them when there are longer expressions depending on the condition though.
If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.
The only time I think ternary operators make code harder to understand is when you have more than three or foyr in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.
As so many answers have said, it depends. I find that if the ternary comparison is not visible in a quick scan down the code, then it should not be used.
As a side issue, I might also note that its very existence is actually a bit of an anomaly due to the fact that in C, comparison testing is a statement. In Icon, the if construct (like most of Icon) is actually an expression. So you can do things like:
x[if y > 5 then 5 else y] := "Y"
... which I find much more readable than a ternary comparison operator. :-)
There was a discussion recently about the possibility of adding the ?: operator to Icon, but several people correctly pointed out that there was absolutely no need because of the way if works.
Which means that if you could do that in C (or any of the other languages that have the ternary operator), then you wouldn't, in fact, need the ternary operator at all.

Resources