views:

323

answers:

6

When I'm doing TDD, it forces me to employ Dependency Injection principle and I end up with loosely coupled code.

I was told that it's harder to understand application that has loosely coupled code.

Can you tell me what pros and cons of loosely coupled code?

+3  A: 

The other benefit is being able to replace components more easily when you have more than one implementation.

Imagine you have a shopping cart system, it normally stores and reads from a database, that's the default. But you can inject so that it uses a backend, which is not as good but it works when you don't have a database.

J. Pablo Fernández
+1  A: 

Since it's loosely coupled, it's highly changeable. That's the whole point. If you don't need that, the loose coupling may introduce many indirections that result in a system with more 'depth': you need to look down a level in order to see all that happens.

xtofl
+6  A: 

The biggest advantage is that introducing changes to one module does not break other modules in unpredictable ways.

Manu
+1  A: 

Like you said, the cons of loosely coupled code are increased complexity, and it's difficulty to understand. It's usually not immediately apparent what the code does when it's loosely coupled.

Like others have said: The benefit is that it's much easier to swap other pieces of code/modules/objects/components when the pieces aren't dependent on one another.

As with all OO design, there are trade offs you have to make - is it more important for you to have highly modular code that is easy to swap in and out? Or is it more important to have easily understandable code that is simpler? You'll have to decide that.

Hooray Im Helping
A: 

Reuse, extensibility and a reduction in side-effects.

altCognito
+3  A: 

Dependency Injection does not automatically lead to low coupling. I agree with the answers above about the pros of low coupling. The main benefits of Dependency Injection is that it improves testability and that it helps you follow the GoF principle of Program to Interfaces, not Implementations. But you can have high coupling to injected dependencies too.