wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Golden (or Happy) Path #14

Closed wnagrodzki closed 6 years ago

wnagrodzki commented 6 years ago

Nesting if statements should be avoided.

func buy(soda id: SodaID, with money: [Coin]) throws -> (Soda, [Coin]) {
    if let soda = soda(for: id) {
        if value(of: money) >= soda.price {
            if let change = change(from: money, minus: soda.price) {
                return (soda, change)
            }
            else {
                throw PurchaseError.noChange
            }
        }
        else {
            throw PurchaseError.insufficientFunds
        }
    }
    else {
        throw PurchaseError.outOfStock
    }
}

All error conditions should be handled at the beginning of the function leaving "the working code" on the first indentation level.

func buy(soda id: SodaID, with money: [Coin]) throws -> (Soda, [Coin]) {
    guard let soda = soda(for: id) else {
        throw PurchaseError.outOfStock
    }

    if value(of: money) < soda.price {
        throw PurchaseError.insufficientFunds
    }

    guard let change = change(from: money, minus: soda.price) else {
        throw PurchaseError.noChange
    }

    return (soda, change)
}

It is easier to understand error conditions written in linear manner than as a nested structure.

wnagrodzki commented 6 years ago

@moskacz @pwgr Do you think it is good enough to be incorporated as a guideline?

wnagrodzki commented 6 years ago

Michał approved

pwetrifork commented 6 years ago

ok