(on Friday, 29 May 2009, 01:30 PM -0700):
> Ha, I was in the middle of writing some getter/setter methods when I saw your
> message :)
>
> I'm reading the article now, but from what I am gathering it seems that the
> author is afraid that programmers use the getter/setter methods to override or
> hijack the implementation details of a class.
>
> Like take Zend_Db_Table, for instance. I could write something like this:
>
> $table->getAdapter()->query($myCustomSql);
>
> Generally, I think using getters in this fashion can lead to problems down the
> road.
Actually, in PHP, *not* adding getters/setters for items like this lead
to problems. Due to PHP not having strong typing, there's no way to
ensure that the adapter is a valid adapter without using a setter.
Additionally, due to how Zend_Db_Table works, getAdapter() allows the
table class to access the default db adapter instance when one is not
yet set. I'd argue that that particular example is a *perfect* example
of when to use getters and setters.
> But there are also valid uses for getter methods, like if you need to
> quote a string:
>
> $table->getAdapter()->quote('foo');
This isn't a getter at all -- it's a method providing a discrete
behavior. It's not setting object state whatsoever.
> Also, getters/setters are great for unit testing, as you can inject mock
> objects into your classes.
Exactly. I think this part was very much overlooked in the article.
> On Fri, May 29, 2009 at 1:12 PM, Ed Lazor <edlazor@internetarchitects.biz>
> wrote:
>
> Probably more of a general coding debate, but...
>
> What's your opinion on the pros and cons of using get and set
> accessors? What's the Zend Framework strategy on this? Do you have a
> preference one way or the other?
>
> Any examples you can give that support your opinion would be great.
>
> Here's one article suggesting that "getter and setter methods are
> evil". It's written toward Java, but it seems like the debate easily
> applies to PHP / ZF.
> http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html.
> Do you agree with what the author says?
>
> -Ed
>
>
>
--
Matthew Weier O'Phinney
Project Lead | matthew@zend.com
Zend Framework | http://framework.zend.com/
没有评论:
发表评论