5 ms·
Guard clauses aren't only for errors. They do however usually involve certain kinds of asymmetry. Typically: The early return case does fewer things (or nothing
by psyc 9y ago
Guard clauses aren't only for errors. They do however usually involve certain kinds of asymmetry. Typically: The early return case does fewer things (or nothing) than the major case. Or the early return case is normal, but has a 'negative' sense (which again does less work) like not finding a key in a dictionary.
- chaboud 9y agoI agree with you. I think the statement (ish) “don’t use if/else, use return” deserves some qualification, and one natural place to use it is for errors. When people start dropping returns all over massive multi-screen branching and looping structures, readability may suffer, and debugability quite often takes a big hit. In general, I like to use guard clauses for any big at-entry branch asymmetries. If they’re farther down the logic tree and/or unwieldy, it may be time to call some more functions.