Patterns to deal with with functions that can have different kinds of results.
Posted
by KaptajnKold
on Stack Overflow
See other posts from Stack Overflow
or by KaptajnKold
Published on 2010-05-31T21:58:58Z
Indexed on
2010/05/31
22:03 UTC
Read the original article
Hit count: 137
Suppose you have an method on an object that given the some input alters the objects state if the input validates according to some complex logic.
Now suppose that when the input doesn't validate, it can be due to several different things, each of which we would like to be able to deal with in different ways.
I'm sure many of you are thinking: That's what exceptions are for! I've thought of this also.
But my reservation against using exceptions is that in some cases there is nothing exceptional about the input not validating and I really would like to avoid using exceptions to control what is really just in the expected flow of the program.
If there were only one interpretation possible, I could simply choose to return a boolean value indicating whether or not the operation resulted in a state change or not and the respond appropriately when it did not.
There is of course also the option to return a status code which the client can then choose to interpret or not. I don't like this much either because there is nothing semantic about status codes.
The solution I have so far is to always check for each possible situation which I am able to handle before I call the method which then returns a boolean to inform the client if the object changed state. This leaves me the flexibility to handle as few or as many as the possible situations as I wish depending on the context I am in. It also has the benefit of making the method I am calling simpler to write. The drawback is that there is quite a lot of duplication in the client code wherever I call the method.
Which of these solutions do you prefer and why?
What other patterns do people use for providing meaningful feedback from functions? I know that some languages support multiple return values, and I if I had that option I would surely prefer it.
© Stack Overflow or respective owner