[nycphp-talk] OOP noob - general best practices
Paul A Houle
paul at devonianfarm.com
Wed Jan 20 11:58:27 EST 2010
Yitzchak Schaffer wrote:
>
> That's actually one way I've used the static factory - to handle a
> situation where there is no Bar that can be created from Foo, but this
> is expected:
>
> $foo = new Foo();
> $bar = Bar::factory( $foo ); // false
> if ($bar) {
> // do stuff with $bar
> }
>
> Is this good practice? I think my question of
> client-calls-constructor vs. factory came out of the fact that so many
> of my classes fall into this category.
>
It's really up to you. Your code is simple and clear... In the
exact use case you've given, where the implications of Bar::factory()
failing can be handled correctly and locally at the place you call it.
If, on the other hand, you're going to pass the error condition
back up to the caller of the function that just called Bar::factory()
and then pass the error condition back to the caller of the function
that called that function, you're either:
(i) writing a lot of if-then-else ladders to handle errors (like you see
in old-style C code), or
(ii) not writing the code to handle errors, which means you're not
handling errors correctly.
Some of my thoughts about error handling are written about in these
two articles:
http://gen5.info/q/2008/07/31/stop-catching-exceptions/
and
http://gen5.info/q/2008/08/27/what-do-you-do-when-youve-caught-an-exception/
There's really no "right" answer in questions like this; you're
trading one bunch of problems for a different bunch of problems.
More information about the talk
mailing list