Closed wnagrodzki closed 6 years ago
Nesting if statements should be avoided.
if
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.
@moskacz @pwgr Do you think it is good enough to be incorporated as a guideline?
Michał approved
ok
Nesting
if
statements should be avoided.All error conditions should be handled at the beginning of the function leaving "the working code" on the first indentation level.