Re: Throw Exceptions from setters: second opinion
- From: amygdala <example@xxxxxxxxxxx>
- Date: Tue, 30 Dec 2008 14:19:39 +0100
Op Tue, 30 Dec 2008 13:16:16 +0100 schreef Jerry Stuckle <jstucklex@xxxxxxxxxxxxx>:
amygdala wrote:Hi all,
Recently somebody on a forum told me, and nearly convinced me, that throwing Exceptions from setters is bad practice. He stated that setters should only return boolean false if the provided input is not valid, since that is what they are expected to do: validate input and simply tell wheter it's valid or not. Furthermore he stated that throwing Exceptions is only meaningful when an internal routine of the class encounters invalid data. Does this sound reasonable to you? I'm not sure yet myself. Love to hear your opinions on the matter.
Thanks in advace.
Not at all. It's actually quite a good idea to throw exceptions from setters.
Returning true/false from a setter is old school - from before the time exceptions existed. Nowadays, a better way is to return the value you are setting it to. That way you can chain operations.
A 'fluid interface' you mean? Yes it makes sense now.
Because this way you now could do something like the following:
try
{
$myObject->setSomething( $something )
->setAnotherThing( $anotherThing )
->tellMyObjectToTakeAction()
}
catch( MyObjectException $exception )
{
// act on the caught Exception
}
.... in stead of the very verbose:
if( myObject->setSomething( $something ) )
{
if( $myObject->setAnotherThing( $anotherThing ) )
{
if( !$myObject->tellMyObjectToTakeAction() )
{
// act on return value false of tellMyObjectToTakeAction()
}
}
else
{
// act on return value false of setAnotherThing()
}
}
else
{
// act on return value false of setSomething()
}
....right?
.
- Follow-Ups:
- Re: Throw Exceptions from setters: second opinion
- From: Jerry Stuckle
- Re: Throw Exceptions from setters: second opinion
- From: Hugh Oxford
- Re: Throw Exceptions from setters: second opinion
- References:
- Throw Exceptions from setters: second opinion
- From: amygdala
- Re: Throw Exceptions from setters: second opinion
- From: Jerry Stuckle
- Throw Exceptions from setters: second opinion
- Prev by Date: Monogram Multicolore Griet MM M40203 Collection
- Next by Date: Re: Query String
- Previous by thread: Re: Throw Exceptions from setters: second opinion
- Next by thread: Re: Throw Exceptions from setters: second opinion
- Index(es):
Relevant Pages
|