Jakob Bieling wrote:
[snip, re: exceptions]
I guess it also depends on how, when and where you use them.
You throw an exception when the promises the interface
makes cannot be kept.
So, that implies that the interface has to make promises,
has to have its required inputs and promised outputs made
explicit. One term for this is "programming to a contract."
Each function will have requirements for what it can accept
as inputs, and make promises about the side effects it
can produce and the values it can return.
This does not tell you enough to design good functions.
But it gives you an idea how to correctly implement
exceptions when you do have good functions.
Basically, stuff that is normal, predictable behaviour
for a function, probably should be handled through the
regular interface. Stuff that is not that may be better
as an exception. That way, you handle the routine stuff
in the interface, and deal with it in client code as
routine stuff. The rare stuff, or the weird stuff, you
handle through the exception mechanism.
In one of the "standard references" everybody recomends,
there's a story about sending somebody to cut the lawn.
And there's various things that could happend.
- He could find the lawnmower, and cut the lawn. Return
message is "yes, ok, done."
- The lawnmower could be out of fuel. So, he has to fill
it and then go on. Should be the same result. And it's
an ordinary occurence. Shouldn't be an exception.
The guy should handle it inside his task. So, he might
have a "cut the lawn" task that includes "check for fuel"
and "fill with fuel" as sub-tasks.
- It could be bucketing down rain, and so cutting the lawn
could be impossible. Result: Return the message "can't
cut the lawn right now, try later." Probably you want
to include this as part of the task, as it's a fairly
regular occurence. So it would go through the regular
interface.
- The lawnmower could be in the garage, the garage could
be locked. What now? Not the ordinary thing, so got to
go get the person with the keys and do something unusual.
That might be an exception, as the keys might be someplace
that is not easily available.
- The lawnmower could be missing. (Borrowed, stolen, not put
back in the right place, etc.) Again, this is outside the
ordinary nature of the task, so it's an exception.
So you get the notion of "ordinary part of the task" and
"not ordinary part of the task." And it depends on context.
Socks