Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setters and objects

Tags:

php

I've just added this method to my class:

/**
 * @param string|StreamableInterface $body
 * @return Message
 */
public function setBody($body) {
    $this->body = $body instanceof StreamableInterface ? $body : new StringStream($body, true);
    return $this;
}

And now it occurs to me that the semantics are a little bit different depending on if you pass the method a string or an object.

If you give it a string, it will construct a new object, otherwise it will just create a reference to the object you provide, which means that you can further modify that object from outside this class in one case, but not the other.

Is this bad practice? Should I create a full clone of the object if you pass one in? I'm not sure what the expected behaviour is.

like image 635
mpen Avatar asked Apr 22 '15 19:04

mpen


Video Answer


1 Answers

In my opinion, the stream shouldn't be cloned and you should keep your code the way it is. I would even consider what you have done best practice. If someone wants the object to have its own isolated stream, then they should give the object its own stream—I would leave that decision up to the caller.

Your method is what is commonly done in almost every similar scenario I have seen.

like image 189
2 revs Avatar answered Oct 02 '22 15:10

2 revs