[Tutor] best practice: throw exception or set a flag?

Bill Felton subscriptions at cagttraining.com
Fri Feb 4 14:35:30 CET 2011


On Feb 4, 2011, at 8:03 AM, Alex Hall wrote:

> On 2/4/11, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> "Alex Hall" <mehgcap at gmail.com> wrote
>> 
>>> I am wondering what the best way to do the following would be: throw
>>> an exception, or always return an object but set an error flag if
>>> something goes wrong? Here is an example:
>> 
>> Throw an exception is the short general case answer...
>> 
>>> class c:
>>> def __init__(self):
>>> self.error=False
>>> def func(self, val):
>>> if val!=10: self.error=True
>> 
>> But note that neither of these methods returns "an object"
>> - unless you count None as an object of course.
> There should have been a function below that which returned the object
> with or without the error attribute.
>> 
>>> Which is the "standard" way when dealing with objects? Throw
>>> exceptions or always return an object, even if said object has an
>>> error and may therefore not have data beyond an error code and
>>> message?
>> 
>> I'm not sure what you have in mind here but remember that
>> init() is an initialiser and not really a constructor so the object
>> already exists when init() is called. init() does not return the
>> object.
> Right, that second function should have done it, but I likely wrote it
> wrong (what I get for making up an example on the spot).
>> 
>> And most methods do not return the object of which they
>> are a part (in Python at least, in SmallTalk they do).
> That seems like it would get rather confusing...

Um, not quite correct -- methods *without a specified return value* always return self, that is, the object which executed the method.
This is useful, but is hardly the most common situation.
It is used most often when a method modifies the receiver and the sender(s) is/are likely to be interested in the updated object itself rather than in one of the parameters to the method or some other object.
However, it can be a source of error, as many methods which modify return self, but many common collection protocols return the argument rather than the modified collection.  Just one of those things you need to learn, which all languages have ;-)

cheers,
Bill



More information about the Tutor mailing list