3

During a discussion, I wasn't sure if I was correct when saying:

"It's better to pass around objects as parameters instead of object ID's."

So I thought I'd ask here for clarification.

What are the advantages of doing this:

public function doSomething(\Item $item) 
{   
     return $item->getSomething() * 2;
}

Over this:

public function doSomething($itemID) 
{
    $item = \Item::getByID($itemID); // Return an item based on ID
    if ($item) // Check the object has been returned
    {
       return $item->getSomething() * 2;
    }
}

Is it true to say that one benefit is you can presume the object will exist, so there is no need to check if it does?

2 Answers 2

4

It's called dependency injection, and the main benefit is that you can test the doSomething() method in complete isolation by injecting a "mock" Item object into the method, so testing doSomething() isn't dependent on the logic of Item itself

Sign up to request clarification or add additional context in comments.

2 Comments

Ah of course. Are there any other benefits unrelated to testability?
Other benefits, like you can pass object of class Item or of classes that extend class Item; whereas your second version forces you to instantiate an object of type Item unless you jump through some hoops in the getByID() method - that gives you additional flexibility.... that's the L of SOLID
0

The first solution may be a little bit faster at runtime. You should prefer that to the second inside of a loop. The second does a look up for the item by its ID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.