0

Should the function that operates on the object return it?

Shortened example:

class Example1
{
    public function method($a, $b)
    {
        $result = new Result($a, $b);

        $this->multiplication($result, 2);

        return $result;
    }

    private function multiplication(Result $object, $value)
    {
        $object->multi($value);
    }
}

class Example2
{
    public function method($a, $b)
    {
        $result = new Result($a, $b);

        $result = $this->multiplication($result, 2);

        return $result;
    }

    private function multiplication(Result $object, $value)
    {
        return $object->multi($value);
    }
}

Both classes give the same results, but which style should I use?

The second example is clearer, but on the other hand everyone should know that the objects are passed through the reference.

  • 1
    I would say no. Returning the object could indicate immutability and another developer could count on that. So either clone the object, modify the new instance and return it or do not return anything. – Andy Oct 22 '18 at 10:06
  • 1
    What's the result of $object->multi($value)? You seem to be assuming that it will be $object. By your rule, every function should return $this – Caleth Oct 22 '18 at 10:34
  • In theory, a method should return only necessary data not all data. – NoChance Dec 31 '18 at 15:24
3

The multiplication method is in the wrong class. If a method doesn't need $this then it should be moved into a class that it does need. Your method methods (both of them) use $this but only because multiplication is in the wrong class.

Now on to your actual question rather than the sample code.

If a method returns something other than $this it should not modify the state of this. If a method returns $this or doesn't return any value, then it should modify $this.

Since none of the methods you wrote modify the state of $this, they should all return something other than $this.

The above is known as command-query separation.

So now, should a method that modifies the state of this return this or return nothing? Returning this consistently allows for easy chaining of methods $obj->fn1()->fn2() but limits the ability of methods to perform asynchronous operations which means they can't act as proxies for some external source. It's a tradeoff. Personally, I prefer the latter. I see no point in ever returning $this because the caller already has a reference to this and therefore doesn't need you to pass one back to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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