A very general question. I was thinking about method chaining, which seems useful, and began wondering if there is a reason to not return the object in a class member, as a matter of course.
For instance:
function doStuffAndReturnThis() {
/* Does Stuff */
$this->variable = $stuff;
return $this;
}
I suppose it is like one of those arguments against always returning true/false;
Is there a consensus? Also, my main language is PHP, but thisn’t a PHP specific question.
4
Method chaining implies that multiple method calls are related, with each call building on the previous one. An example is a “fluent” style of programmatically querying the database.
$posts = Post::where(array('name' => 'Test'))
.order_by(array('date' => 'desc'))
.limit(10);
(Forgive my lackluster PHP, it’s been quite a while since I wrote any)
The Post class’s where method returns a QueryBuilder object which has an order_by method and a limit method, both of which return the QueryBuilder object.
You’ll see this fluent, natural language like syntax when an object needs a bunch of configuration that is conceptually easier to manage in natural language, such as ad hoc SQL queries.
Why not always return the object to promote method chaining? Because people could be making assumptions about you class’s functionality that aren’t true. If a method call doesn’t require subsequent method calls to achieve the end goal then returning the object could make programmers think your class need additional calls when it doesn’t.
1