re: What do you think about the ternary operator? VIEW POST


I feel the same as other "syntax sugar cool" things, when used correctly it improves your code, but most of the time it's going to be over used. I've seen some horrors using the ternary operator you would not believe.

what = (f() ? (g() && x ? a + d : b ) : c)

I used it when dealing with simple, 1 word condition and values.

As a Go newbie I don't miss it, having so few language constructs and operators it is very relieving, you need a condition you use if, simple and efficient. All your peers will do the same, everyone understands it, and it is harder to screw it up.


I agree. I've seen it used in some perfectly legitimate ways such as in JSVerbalExpressions.

    startOfLine(enable = true) {
        this._prefixes = enable ? '^' : '';
        return this.add();

    endOfLine(enable = true) {
        this._suffixes = enable ? '$' : '';
        return this.add();

This pattern is repeated throughout the library. Using if-else here would be painful, but it'd be manageable. At least one wouldn't have to deal with the code like you described. Why people would write code of that sort (except for codegolf) is beyond me.


Why people would write code of that sort (except for codegolf) is beyond me.

The most common reason I saw (is not specific to this problem) was when a dev had to add some new logic, instead of refactoring the ternary expression into an if, switch or separate to functions, or objects or whatever added the new complexity in place.

The reasons why that happened were various, excuses like "I was in a hurry", "I didn't had the time to understand the code" and so on were common.

Fear of refactoring is a common problem in projects without tests and/or devs without the desire to write good code, or just insane release schedule, you know, common problems.

startOfLine(enable = true) {
    this._prefixes = (enable && '^') || ''
    return this.add()

endOfLine(enable = true) {
    return(this._suffixes = (enable && '$') || '', this.add.bind(this))()
    //    ^ look mom, no space after `return`                          ^
    //                                                                 |
    //             note the artisanal external position of call parens |
code of conduct - report abuse