Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  • Pro: seems its quite not bad pattern style for chaining many actions on the same object and making your code shorter.

  • Con: code looks a bit weird when you see that object returns itself in the method, which does something else (e.g. setter for some property)

Is it really good pattern practice or maybe an anti-patternpractice?

EDIT: well it was a little too much from my side to call it "pattern", thanks everyone for pointing me to right direction!

like image 455
Laimoncijus Avatar asked May 26 '11 12:05

Laimoncijus


People also ask

What is an example of an anti-pattern?

Poltergeist. A poltergeist is an anti-pattern involving a pointless class that is used to call methods of another class or simply adds an unnecessary layer of abstraction.

What is the difference between a pattern and an anti-pattern?

An anti-pattern is the evil twin of a good design pattern. A good design pattern is a reusable requirement, design, or implementation that solves hard problems in a standard way, which is well designed, well documented, easy to maintain, and easy to extend.

Is the singleton pattern actually an anti-pattern?

If singleton were used here, it would break that behavior. This inflexibility is one of the biggest reasons why singleton is an antipattern. Engineers often use singletons to provide a global access point. They are often used in place of a global variable that has a single instance.

How do you identify anti-patterns?

In an organization, there are three main opportunities to identify anti-patterns: During design reviews, during code reviews and during refactoring of legacy code. Design reviews are a great opportunity to find anti-patterns.


1 Answers

I've found method chaining to be useful in circumstances where it makes sense; a domain specific language, for example:

$query->select('*')->from('users')->where(array('user_id' => 1, 'verified' => 1));

The thing is, these methods would only be returning void anyway and so the return $this merely functions as a short hand version of writing:

$query->select('*'); $query->from('users'); $query->where(...);

We're still going to be calling the toSQL() or execute() method to make use of the data we've populated our object with.

In my opinion it is not an anti-pattern and can function as a legitimate, sensible, method of object population in the right circumstances.

like image 165
Nick Avatar answered Sep 22 '22 03:09

Nick