Saturday, January 08, 2005

Do or die

I believe that the Do-or-die principle is the strongest protector of good software, and the greatest preventative against mystery bugs, convoluted logic and tortuous coding. What do I mean?

Do-or-die is simple: either an operation succeeds or it raises an exception. When you call a do-or-die method, any normal code path relying on the results of that method have a guarantee for sanity—there are no problems to check for or deal with in the normal code path. The abnormal code path coping with the raised exception handles all problems. (Contrast this with languages lacking exceptions.) This means:

  1. Any procedure always returns void; no boolean returns that require checking for success or failure. Just call the procedure and be done with it.
  2. Any function always returns a valid object; no null returns that require nullity checks. Just capture the return and use it as expected.

Because of do-or-die, tremendous amounts of work, thinking, testing, coding and bug hunting are eliminated. Code is vastly more readable without a thicket of checks, nexted if/else blocks and null handling. Clarity and sanity is a natural product of do-or-die. I can think of no other idiom with as high a payoff in simplicity of notion to size of benefit.

3 comments:

Anonymous said...

Beautiful.

Anonymous said...

What about stuff like;
void CreateData()
{
CreateDb();
CreateTables();
CreateData();
CreateIndexes();
}

How do you recover from an exception in CreateData?

Brian Oxley said...

I don't think I do recover from an exception in CreateData()! Java has no notion of monads so methods with side effects are impossible to properly do-or-die with full rollback semantics. This is an example of the classic PC loser-ing problem.