Skip to content

Don't use ternary as an alternative for if else #2358

Closed

Description

@Igor-Palaguta

Rule Request

  1. Why should this rule be added? Share links to existing discussion about what
    the community thinks about this.

Ternary operator should be used just on right side of assignment or in return statement. And should not be used as an alternative for if/else. As it is very unusual and harder to read than usual if/else
https://softwareengineering.stackexchange.com/a/294560

  1. Provide several examples of what would and wouldn't trigger violations.
// NOT TRIGGERED
let result = success ? "Success" : "Fail"

if success {
    askQuestion()
} else {
    exit()
}

var price: Double {
    return hasDiscount ? initialPrice - discount : initialPrice
}

// TRIGGERED
success ? askQuestion() : exit()

  1. Should the rule be configurable, if so what parameters should be configurable?

No parameters expected

  1. Should the rule be opt-in or enabled by default? Why?

It can be enabled by default

Activity

  1. added
    rule-request
    on Aug 21, 2018
  2. drrost commented on Dec 4, 2018

    @drrost
    // TRIGGERED
    success ? askQuestion() : exit()
    

    I'd suggest not allow to call functions in the 2nd and 3rd part that return void.

  3. drrost commented on Dec 4, 2018

    @drrost
    1. Should the rule be opt-in or enabled by default? Why?

    It can be enabled by default

    And I'd make this rule disabled by default 'cause it's quite exotic behavior for C/Objective-C/Swift and many people may want to use it as they used to.

  4. added 2 commits that reference this issue on Feb 8, 2020
    f8ac10e
    b22a0b8
  5. added 3 commits that reference this issue on Feb 8, 2020
    1d39071
    6ffbe11
    763e107
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    rule-request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions