Chapter 13. Fail Fast

There is an art to knowing where things should be checked and making sure that the program fails fast if you make a mistake. That kind of choosing is part of the art of simplification.

Ward Cunningham

13.0 Introduction

The ability to fail fast is critical for clean code. You need to take action as soon as a business rule fails. Every silent failure is a missed improvement opportunity. To accurately debug a problem you need to find the root cause. And the root cause will give you a certain hint to trace and solve the failure. Fail fast systems are more robust than weaker systems where failures are swept under the rug and processing keeps going forward, even after the failure affected the correct result.

13.1 Refactoring Reassignment of Variables

Problem

You reuse variables with different scopes.

Solution

Don’t reuse variable names. You break readability and refactor chances and gain nothing; this is a premature optimization that does not save memory. Narrow the scopes as much as possible.

Discussion

If you reuse a variable and extend its scope, automatic refactoring tools may break and your virtual machine might miss the chance to make optimizations. It is recommended that you define, utilize, and dispose of variables while keeping their lifecycle short. In this example, there are two unrelated purchases:

class Item:
  def taxesCharged(self):
    return 1;

lastPurchase = Item('Soda');
# Do something with the purchase

taxAmount = lastPurchase.taxesCharged ...

Get Clean Code Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.