`return $this;` design pattern or anti-pattern?

前端 未结 5 1567
醉酒成梦
醉酒成梦 2021-01-17 13:22

I\'ve seen many times Zend Framework using return $this; pattern style - and from my point of view:

  • Pro: seems its quite not

5条回答
  •  有刺的猬
    2021-01-17 14:00

    If you mean "good practice or bad practice", here's my take:

    On the plus side, you get some syntactic sugar.

    On the down side, you give up meaningful return values in favor of chainability. Which is not really feasible because eventually you will have to have methods which return something other than the base object, so you end up with some methods which are chainable and some which are not (users of your classes get to have fun guessing which ones are which.)

    Or you go full hog and make all of them chainable no matter what, but then you find yourself in ridiculous situations such as returning a fake "empty" object for the sake of preserving the chain, which object needs to be tested for some obscure property to determine if it's a "real" one or just a link in the chain.

    The classical example is jQuery, which exhibits all the symptoms: the base object attempts to be the sole basic unit of data throughout the code (everything returns a jQuery object); fake object testing (if (obj.length)); plus the self-contradiction where it still needs to break chainability for methods like getAttribute() that return string.

    IMHO, it's an awful mess to make of things just for the sake of that bit of syntactic sugar.

提交回复
热议问题