2

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.

  • ...even though I don't agree with that answer. – Telastyn Dec 15 '14 at 22:09
  • @Telastyn I'm not concerned with method chaining, itself, but the returning of self, when otherwise you wouldn't return anything. Also, could you elaborate on your thoughts about method chaining? – nobrandheroes Dec 15 '14 at 22:23
  • 1
    "Wouldn't return anything" implies side effects. I dislike side effects. And I use C# primarily. If you want to mutate the object, use the assignment operator. Yes, it might be a little longer, but it will be piles more readable. – Telastyn Dec 15 '14 at 22:37
  • 1
    @Telastryn: The assignment operator is not always appropriate. Methods are ok as long as you use verbs to name it. – Greg Burghardt Dec 16 '14 at 3:04
2

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.

| improve this answer | |
  • The last paragraph is what I am looking for. Thank you. – nobrandheroes Dec 16 '14 at 14:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.