Thursday, May 13, 2010

Do your work, or throw an exception

Imagine this: My car breaks down, and I cannot make it to work. Should I inform my boss that I will not do my work as usual, or wait until she asks me if I will come to work? Should she ask me every day if I will do my work as usual?

If there's something wrong with my car, should a light on the dashboard tell me, or should the engineers that designed it require me to check everything to make sure it is in working order every day before I start driving?

I think you would agree that, when something or someone does not behave as expected, a notification that he, she, or it did not do its job would be nice. In many cases, we have a right to expect this sort of behavior.

Likewise, every method you ever write should either do what it says it will do or throw an exception. E.g., myObj.Save() should either save myObj or should throw an exception. It should not return a value indicating if it was successful or not, as that would require client code to check for success.

If there are multiple occasions where you would catch an exception thrown by a method immediately in order to do something with it, then (and only then) you can create a tryDoSomething method, such as myObj.TrySave(), and use it where applicable. (Of course, catch only exceptions that you know are caused by specific things; let the exception go if it is due to a bug.) TryDoSomething() methods should be the exception, not the rule.

No comments:

Post a Comment