Every time you're implementing some kind of logic and you don't know what to do when things go bad ...
Every time you think: this can never happen, I don't have to check for it ...
Every time you don't know what to do or what would happen ...
Please ...
Fail fast.
This is the Fail Fast Rule, as I call it, a term borrowed from the Java Collections iterators behavior:
Every time your code might fail, and you don't know what to do, just make it fail abruptly.
That is: do not ignore it, do not (just) log it, but let your code throw an exception.
An example was how we computed a shopping cart total in one of my previous posts:
public class ShoppingCart {
private static final int MAX_TOTAL = 10000;
private List orders = new ArrayList();
public void addOrder(Order o) {
this.orders.add(o);
}
public double computeTotal() {
double total = 0;
Iterator it = this.orders.iterator();
while (it.hasNext()) {
Order current = (Order) it.next();
total += current.computeSubTotal();
if (total > MAX_TOTAL) {
throw new SomeException();
}
}
return total;
}
}
As soon as the total gets too high, an exception is thrown. Probably this will change later, because we may want to handle it more gracefully, but in the meantime: make it fail.
Why?
Because if an exception will pop up in front of you, you'll have found a bug, a corner case, something that you have not still properly implemented or that you have not thought of.
So remember: make it good, or fail fast.
No comments:
Post a Comment