4 ms·
Ditch That Else
- danjc 3y agoGreat advice. This is probably one of the top 5 or 10 things an inexperienced programmer could adopt to level up.
- Someone 3y agoIf possible, also ditch that if. Swift replaces it by guard. I’m not a 100% fan of its syntax (1), which is guard <#condition#> else { <#statements#> } but do like that <#statements#> must return. So, guard… else semantically can be replaced by if !, but is a bit more limited, thus making it easier to recognize the pattern. https://docs.swift.org/swift-book/documentation/the-swift-programming-language/statements/ https://docs.swift.org/swift-book/documentation/the-swift-pr...: “The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements: - return - break - continue - throw” (1) I can’t think of a much better one, but think I would have picked requires <#condition#> else { <#statements#> } or (getting rid of that weird else): ifnot <#condition#> { <#statements#> } Eiffel’s preconditions (https://www.eiffel.org/doc/eiffelstudio/Precondition https://www.eiffel.org/doc/eiffelstudio/Precondition) look even nicer: require <#condition#> but do not allow specifications of what to do when the condition isn’t met, and aren’t supposed to be checked in procession code. https://www.eiffel.org/doc/eiffel/ET-_Design_by_Contract_%28tm%29%2C_Assertions_and_Exceptions https://www.eiffel.org/doc/eiffel/ET-_Design_by_Contract_%28...: “It is in fact part of the Eiffel method that a routine body should never test for the precondition, since it is the client's responsibility to ensure it. (An apparent paradox of Design by Contract™, which is reflected in the bottom-right entries of the preceding and following contract tables, and should not be a paradox any more at the end of this discussion, is that one can get more reliable software by having fewer explicit checks in the software text.)”