From: Robert Klemme Date: 2005-11-08T00:32:12+09:00 Subject: Re: programming best practices gwtmp01@mac.com wrote: > On Nov 7, 2005, at 4:32 AM, Robert Klemme wrote: >> IMHO using int's as return values is as bad as using boolean return >> values >> in a language that has exceptions. Exceptions are a far more >> elegant way >> of handling errors and also often code will be shorter and cleaner. > > I tend to think there is a middle ground also. Well, yes. My statement was of course too strong. I wanted to make clear that the quality of the code doesn't necessarily improve with the number of distinct return values (int vs. boolean) and that it's not a good idea to augment every method with a boolean return value that indicates success or failure. > Bertrand Meyer has > written > a lot about the use of exceptions in programming. I tend towards his > model > where an exception is, well, exceptional. That is to say that an > exception > shouldn't be used to model an outcome that is *expected*. > > There is a nice side bar in Agile Web Development in Rails where > David talks > about Active Record and exceptions. He explains why: > > Person.find(5) > > raises an exception if the record is not found while > > Person.find(:first, :condition => "name = 'Dave'") > > returns an empty result if the record is not found. The difference is > that > in the first case, the assumption is that the record exists > (otherwise I wouldn't have known to use 5 versus some other key). If > the record doesn't > exist then something bad or exceptional has happened. > > In the second example, we are trying to determine if the record > exists and > so the fact that it may not exist is entirely expected. In this case > an exception is not warranted because the outcome "doesn't exist" is > anticipated by the caller. > > Bertrand Meyer ties this all back to his Design by Contract > philosophy. If the outcome is part of the contract then an exception > is probably not needed. If the outcome violates the contract then > the exception is probably desired. That sums it up pretty good. After all, there is no general one size fits all rule. Even for the orginial example it's debatable whether a failed login is an exceptional event or an expected event. I'd probably lean more towards expected as users occasionally mistype their id or password. Thanks for taking the discussion one step further! Kind regards robert