Re: Throw Exceptions from setters: second opinion
- From: Jerry Stuckle <jstucklex@xxxxxxxxxxxxx>
- Date: Tue, 30 Dec 2008 09:34:18 -0500
amygdala wrote:
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?
Yes, that is called "chaining operations", not a "fluid interface".
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.
- Follow-Ups:
- Re: Throw Exceptions from setters: second opinion
- From: amygdala
- 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
- Re: Throw Exceptions from setters: second opinion
- From: amygdala
- Throw Exceptions from setters: second opinion
- Prev by Date: Re: Query String
- Next by Date: Re: Throw Exceptions from setters: second opinion
- Previous by thread: Re: Throw Exceptions from setters: second opinion
- Next by thread: Re: Throw Exceptions from setters: second opinion
- Index(es):
Relevant Pages
|