php - Using an object as a parameter vs creating the object in the method -


during discussion, wasn't sure if correct when saying:

"it's better pass around objects parameters instead of object id's."

so thought i'd ask here clarification.

what advantages of doing this:

public function dosomething(\item $item)  {         return $item->getsomething() * 2; } 

over this:

public function dosomething($itemid)  {     $item = \item::getbyid($itemid); // return item based on id     if ($item) // check object has been returned     {        return $item->getsomething() * 2;     } } 

is true 1 benefit can presume object exist, there no need check if does?

it's called dependency injection, , main benefit can test dosomething() method in complete isolation injecting "mock" item object method, testing dosomething() isn't dependent on logic of item itself


Comments

Popular posts from this blog

Android Java.Lang.RuntimeException : Unable to start activity Component Info -

c# - Sort XmlNodeList with a specific Node value -

actionscript 3 - Equivalent to moveReceived in ElectroServer 5 -