## Tuesday, April 6, 2010

### Ternary operator idioms

I'm sure others have done something similar, but these are the idioms I use for ternary operators:
```return what ? yes : no;

return what ? yes
: noooooooooooooooooooooooo
;

return whaaaaatttttttttt
? yeeessss : noooooo
;

return whaaaaatttttttttt
? yeeeeeeeeesssssssssssssss
: noooooooooooooooooooooooo
;

return
thisWay ? thisThing :
thatWay ? thatThing :
otherThing
;
```
Variation include NOT having the semicolon on its own line, and of course `return` can be replaced by other grammatical possibilities (e.g. variable declaration and initialization), but these are the idioms in my standard repertoire that I've developed over the years.

I'm not sure how common these idioms are (the people at stackoverflow often complain of unreadability), but I'd like to think that these are very useful idioms, and very readable once you get used to it.

```// reverse("Hello World", "") -> "olleH dlroW"
String reverse(String in, String out) {
return (in.isEmpty()) ? out
: (in.charAt(0) == ' ')
? out + ' ' + reverse(in.substring(1), "")
: reverse(in.substring(1), in.charAt(0) + out);
}
```

```// triangle(5, "*\n")) ->      // triangle(6, "*\n")) ->
// *                           // *
// ***                         // ***
// *****                       // *****
// ***                         // *****
// *                           // ***
// *
String triangle(int n, String s) {
return
n == 0 ? "" :
n == 1 ? s  :
s
+
triangle(n - 2, "**" + s)
+
s
;
}
```

#### 1 comment:

1. The java coding conventions (http://java.sun.com/docs/codeconv/html/CodeConventions.doc3.html#262) actually lists the "acceptable" ways of formatting ternary expressions. Some of your examples are not "supported", but (as with many other situations), the conventions does not cover all situations and easily readable alternative formattings.