dealing with complex results in objects -- exceptions?
What is the general way of handling complex results from functions with an object? A simple method might return true or false, and that would be all I need to know. A more complex method might return true or false, but there might be more information I would want to get out of the class, such as why it failed ( there might be several reasons ).
I could do it with an exception, but I've read in some places that using an exception for a "normal" functions isn't good practice. Also since throwing an exception destroys the object, I can't do any开发者_StackOverflow社区thing else with it, so an exception wouldn't work if I want to continue to use the object. It seems to me that an exception should be thrown when things are really wrong, not an expected, recoverable error.
So, another way to this is to have a result property after having run a method, and if that method returns false, I can ask what the result state for it is. Is this the way to do it?
Obvious solution: Return an array, like ("success" => false, "explanation" => "saw a mouse and ran screaming like a little girl", "solution" => "call an exterminator")
.
I'd suggest you to always keep the methods signatures' predictable, i.e. always return the same type (be it an array, boolean, anything else.)
I think the example of validating with Zend_Validate
uses a sensible solution to your problem by differentiating the result from the eventual errors.
Exceptions do not destroy the object, but if you catch an exception in a place where you have no reference to the object, then you can loose the object - it is still there until garbage collection.
If you create your own exception class you could even add the object in question as a member to the exception, so the object is available where you handle the exception.
The exception to this rule is when you throw an exception in an object constructor. Then the object in question is never created in the first place.
The use of Exceptions vs other error mechanisms is as old as Exceptions are. Exceptions are a method for handling errors and in many circumstances they work very well and result in cleaner code than when not using them.
Whether they are a good solution for a specific problem is partly a matter of experience, so you will have to try them out to learn to use them.
精彩评论