Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What if I want to also decouple my application, from classes like Product or User? (which usually have more than one instance)

Take a look at this example:

class Controller {
    public function someAction() {
        $product_1 = new Product();
        $product_2 = new Product();
        // do something with the products
    }
}

Is it right to say that Controller now depends on Product?

I was thinking that we could decouple them too (as we would with single-instance objects like Database)

In this example, however ugly, they are decoupled:

class Controller {
    public function someAction(ProductInterface $new_product) {
        $product_1 = clone $new_product;
        $product_2 = clone $new_product;
        // do something with the products
    }
}

Has anyone done something like this before? Is it excessive?

share|improve this question
1  
Looks excessive. If what the controller does directly ties in with the 2 product instances, why decouple? What's the benefit? –  Oded Nov 13 '11 at 20:05
1  
Most people would understand single-instance object to mean singleton, but I don't see how your question has anything to do with the singleton pattern. –  Caleb Nov 13 '11 at 20:10
2  
@Caleb Well, that's not correct. Single-instance objects means just that. Singleton is an anti-pattern, that constraints classes to have only one instance. To manage single-instance objects without constraining it within the class itself, we use a DI Container, which lets us create more instances if we really need to (eg: when doing unit-testing) –  HappyDeveloper Nov 13 '11 at 20:13
add comment

1 Answer

When I first learned about unit testing and the real power of abstraction layers, I wanted to put an interface on everything. And I did. And I learned very quickly that there is a "too far."

Assuming that you're not dealing with sub-types of products, there is absolutely no benefit to your decoupling. All you achieve is creating another place where you have to replicate any changes you make to the Product's interface.

That said, I don't think the line that I'd draw here is between single-instance and multiple-instance classes. But that may be because I don't like making things single-instance unless they need to be -- controllers and databases are not good examples, to my mind.

Choose not to have an abstraction until you need one (although, if you're unit testing properly then you will probably need one on all but the domain objects). And choose to make a class multiple-instance until it needs to be single-instance.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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