Which patterns for loose coupling do you use most? [closed] - dependency-injection

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Lately I have seen a lot of blog posts concerning how to build loosely coupled applications. Which patterns do you use most when creating loosely coupled applications? Dependency Injection? Inversion of Control?

Model-View-Controller.
Aside: things that stops me writing coupled applications aren't just patterns:
Naming. If I can't easily think of a name for my class, it either does nothing or too many things.
Testability. If I can't easily mock out my class' dependencies, it's a coupled design.

I find myself using the Command pattern quite often. It's a pattern that just keeps giving project after project.

Dependency injection with spring is my favourite. Additionally with maven it's common to do this really neat trick of hiding all the implementations behind an API module. So if your code has three modules, "application-core", "externalsystems-api" and "externalsystems", you can make "application-core" depend ONLY on externalsystems-api. The actual-implementations and all their dependencies can be totally invisible to the application-core module. This really enforces a much harder separation of concerns and makes loose coupling easier.
The neat thing is that IDEs that load these maven setups enforce these visibility constraints. So you're not going to be able to reference SQL, AXIS, JAXB or whatever in your application-core

Some of the SOA related patterns (enterprise service bus for example) offer abstraction at a higher level and support separation of concerns across business services and technical services. Loose coupling between the services is then (arguably) supported by introducing a broker or bus that de-couples the services in the solution.

Visitor pattern works quite well

I think one of the fundamental techniques is "Tell Don't Ask Principle, Law Of Demeter". Maybe it is not like DI,UI or other Desing Patterns but I think objects that fallow this principle are loosely coupled and do the one thing well.
"Keep It Shy Keep It Dry Tell The Other Guy"

Yes, the important ones are Dependency Injection and Inversion of Control, but lets not forget the Abstract Factory and Registries.

Bridge pattern (http://en.wikipedia.org/wiki/Bridge_pattern)

Dependency Injection is a form of Inversion-of-control.
The Spring Framework has a large base of Java programmers, and it has a .NET implementation, too.

The Strategy Pattern.
I'm surprised this hasn't been mentioned yet - strategies allow you to avoid creating classes that know too much about different types in your domain model. Each strategy is responsible for codifying a particular interaction involving specific types. This avoids creating a master type that is aware of many others and the nuances of the implementation of each.
From Wikipedia:
The strategy pattern uses composition
instead of inheritance. In the
strategy pattern behaviors are defined
as separate interfaces and specific
classes that implement these
interfaces. Specific classes
encapsulate these interfaces. This
allows better decoupling between the
behavior and the class that uses the
behavior. The behavior can be changed
without breaking the classes that use
it, and the classes can switch between
behaviors by changing the specific
implementation used without requiring
any significant code changes.
Behaviors can also be changed at
run-time as well as at design-time.

Dependency injection and IOC are both excellent for decoupling code.
Dotnetrocks show 362 provides very good definitions. Also watch the related DNR TV episode to get a clearer understanding.

Dependency injection is the pattern that I use in nearly all classes that I write - if the class has a dependency, I always inject it (using constructor injection). Only classes which have no dependencies (i.e. value objects) don't use the DI pattern. Being able to test classes which use DI is a major benefit.
For information on the benefits of DI, these two presentations are very good:
http://googletesting.blogspot.com/2008/11/clean-code-talks-dependency-injection.html
http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
No DI container is needed to use the DI pattern, but when the program becomes big (tens of classes or many scopes), then a DI container can reduce much boilerplate. On the JVM my default choice is Guice.

Inversion of Control as overall code/architecture style.
DI as a mechanism to configure IoC.
Local abstractions (I call this "Ideal Environment Development" - write as if you had the exact environment you wanted).
Objects typically communicate using void methods, and by passing data, rather than having getters/setters.
I never use a dependency directly in a core business class - it is always abstracted to a local abstraction, and an explicit Bridge deals with the dependency.
I've found that this combination allows for extremely flexible code with a very compositional feel to it.

Related

Why AOP and DI aren't used together very often

I am confused about this line
Aspect-Oriented Programming and Dependency Injection are very different concepts, but there are limited cases where they fit well together.
from this website
http://www.postsharp.net/blog/post/Aspect-Oriented-Programming-vs-Dependency-Injection
I understand the advantages of DI over AOP, but why aren't they used together more often? why are there only limited cases where they fit together? Is it because of the way AOP is compiled, that makes using both difficult?
How do you define "limited cases"? I myself always use AOP and DI together.
There are basically three ways to apply AOP, which are:
Using code weaving tools such as PostSharp.
Using dynamic interception tools such as Castle Dynamic Proxy.
Using decorators.
The use of DI with code weaving tools doesn't mix and match very well, and I think that's the reason that the Postsharp site states that "there are limited cases where they fit well together". One reason it doesn't mix and match is because Dependency Injection is about loose coupling, while code weaving hard couples your code and the aspects together at compile time. From a perspective of DI, code weaving becomes an anti-pattern. In section 11.2 of our book, Mark and I make this argument very clear. In summary we state:
The aim of DI is to manage Volatile Dependencies by introducing Seams into your application. Theis enables you to centralize the composition of your object graphs inside the Composition Root.
This is the complete opposite of hat you achieve when applying compile-time weaving: is causes Volatile Dependencies to be coupled to your code at compile-time. This makes it impossible to use proper DI techniques and to safely compose complete object graphs in the application's Composition Root. It's for this reason that we say that compile-time weaving is the opposite of DI–using compile-time weaving on Volatile Dependencies is an anti-pattern. [page 355]
If you use dynamic interception, however, which means applying cross-cutting concerns at runtime by generating decorators on the fly it works great with DI and it is integrated easily with most DI libraries out there, and can be done as well when using Pure DI, which is something we demonstrate in section 11.1.
My personal preference is to use decorators. My systems are designed around a few well defined generic abstractions, and this allows me to apply cross-cutting concerns at almost all places that are important to my system. That leaves me in very rare cases with a few spots where decorators don't work very well, but this is almost always caused by design flaws. Either by my own limitations as a developer or by design flaws in the .NET framework or some other tool. One famous design flaw is the INotifyPropertyChanged interface. You might have guessed it, but in our book we describe this method in a lot of detail. We spend a complete chapter (10) on this topic.

Implementing cross-cutting concepts into LOB/DI application

I am currently creating a small personal windows (desktop) .NET LOB application and I want to use the opportunity to increase my knowledge and experience with DI. I've separated my application into model, DAO and GUI parts but I am wondering how to implement some cross-cutting concepts such as:
currently logged on user - used for:
asserting rights - in some parts of the application I check if the user has necessary rights
auditing - recording user actions into a separate database table
etc
current application parameters (loaded from configuration file or table) - used for:
defining business strategy
defining UI (theme for example)
etc
logging to file/database log - used for:
logging UI actions (clicking on buttons etc.)
logging business processes (results of calculations, strategy decisions etc.)
logging infrastructure stuff (SQL used to for CRUD operations)
etc
At the moment I can think of several ways to provide this information:
Using static properties - UserEntity.Current, Configuration.Current, Logger.Current, etc.
Pros:
Simple to implement
Simple to use
Cons:
Gets messy
It is unclear which part of the application uses what
Can not be used if you need finer granularity (for example if for some processes in the application you need to override current values)
Using DI - giving each class which needs this information a property/ctor parameter
Pros:
It is clear for each class what it needs
It is easy to unit test
Cons:
It just seems to explode constructors
Makes problems if class needs to have a default constructors
Difficult to setup when classes get instantiated by 3rd party (XAML)
Using ServiceLocator
Pros:
Easy to setup
Easy to use
Cons:
It is unclear which part of the application uses what
Difficult to setup finer granularity (but not impossible)
I am currently leaning towards ServiceLocator as I've worked with it before and it worked quite nice. However I am concerned about loss of control. It gets very easy to just reach for the service locator instead of trying to fix a design problem.
Can somebody provide their experiences/knowledge?
Sounds like perfect case to start with aspect-oriented approach. Your application's LOB will be designed according to business functional requirements that has been cross-cutted with different non-functional requirements: authentication, audit, logging, etc.
In same time, some of current application requirements could be solved by dependency-injection. To start, I recommend first to identify composition root. For example, in wpf applications it’s the Application.OnStartup method. In case if you are able to identify composition root it is better to avoid service-locator. Service locator will add unneeded complexity while maintaining and testing, because it could resolve literally anything, thus dependency management will be complicated.
Next step, to decide: should dependency injection and aspect-oriented approaches be separated or combined. Both approaches has benefits and drawbacks.
While choosing separated approach you could use postsharp with a lot of benefits: great samples and documentation, community and ready to use aspects. But nothing come for free, postsharp has only limited number of features in free version and complicated integration with continues-integration.
Another solution: combine dependency-injection with dynamic-proxy. As long as you follow conception: program to an interface, not an implementation — you will achieve all requirements. Benefits: one place to wire all components. There are two major drawbacks: first dynamic proxy is quite limited itself, second — integration between dependency injection container and dynamic proxy — for some container it already exists, for others not. Example: Ninject extension Interception, or StructureMap and Interception.
I recommend you to take a look at following resources to find more answers yourself:
* Book AOP in .NET: Practical Aspect-Oriented Programming by Matthew D. Groves: first chapter available for free
* Book Dependency Injection in .NET by Mark Seemann: well-written book about dependency injection, and chapter #9 dedicated to interception, approach that I found quite useful in cases that you had described in question. Author of book also has an excellent blog dedicated to dependency injection and video about aspect-oriented programming with dependency Injection.

Where exactly is the difference between IoC and DI [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Inversion of Control < Dependency Injection
I always read IoC(Inversion of Control) and DI(Dependency Injection) in the same context. What is exactly the difference between IoC and DI? How does IoC differ from DI?
In common usage, the terms have become somewhat synonymous. The original idea of IoC -- Inversion of Control -- was very much related to the "Hollywood Principle:" Don't Call Us, We'll Call You.
In traditional applications, developers would write business code and framework code. The business code would then call the framework code to accomplish tasks. Under an IoC model, you "invert" that model and create a framework that accepts business modules and calls them to accomplish tasks. This principle is exhibited in several development frameworks including the old Smart Client Software Factory and the newer Prism (or Composite Applications for WPF/Silverlight). In these models, the UI Modules are registered with an IoC Container and loaded as needed based on configuration and user actions. While powerful, these models also tend to have a very steep learning curve.
Dependency Injection is a technique (hard to call it a pattern, really) of removing internal dependencies from implementations by allowing dependent objects to be injected into the class/method by an external caller. IoC frameworks use dependency injection to supply user modules and other dependent code to framework routines that "glue it all together." Dependency injection is used heavily by IoC frameworks because that is the mechanism that allows them to "Call You."
IoC Containers, such as Castle Windsor and Structure Map help with dependency injection by providing automatic instantiation and lifecycle management of classes you register -- including automatic instantiation and injection of parameters required by registered classes. All of this makes it easier to use dependency injection, but is not required.
Dependency Injection is a mechanism for flexibility that maximizes dependency on Interfaces while minimizing dependency on specific implementation. Consequently, systems that use dependency injection can support "pluggable" implementation classes that can be used depending on circumstances. A very big benefit of this "pluggability" is that it makes creating Unit Tests much easier. You can mock an object to the needed interface, then inject it into your test object.
So, IoC is really the broader principle and DI is a fundamental technique within. IoC (Hollywood Principle) systems tend to be pretty complex, can be hard to understand, and thus have steep learning curves. DI, on the other hand is a good practice for everyday developers. I tend to prefer understandable and clear over cool, but complex.
IoC is the ability to vary the implementation of a contract.
DI is the ability to supply the implementation.

IoC, AOP and more

What is an IoC container?
What is an IoC/DI framework?
Why do we need a framework for IoC/DI?
Is there any relationship between IoC/DI and AOP?
What is Spring.net/ninject with respect to IoC and AOP?
JMSA,
James Kovacs wrote a fantastic article which covers many of your questions I would recommend reading it Here
Spring.Net, Ninject, Unity, Castle Windsor, Autofac are all IOC containers which are configurable in different ways, many of them do also support AOP.
Frameworks for IOC/DI are useful because they provide standard mechanisms, for example if you are hiring a new developer it is much easier to say, we use this framework and pass them the links to the tutorials / help guide. At the same time these frameworks are tried and tested by a large community / companies.
Let me know if any of your questions remain unanswered after reading the article and the above answes and I'll do my best to provide further assistance.
From a semantics point of view...
Dependency Injection itself implies a dependency, i.e. something that is required for construction/use (the application's "core concerns"). For example, a car is not a car without an engine.
Aspects are described as being cross-cutting to the application's core concerns. That means both separate from and non-crucial to the core concerns (you could think of them as "nice-to-haves"). Since the application can run without aspects, are they really dependencies? For example, a car is still a car even without an immobiliser.
(Of course, this is from a theoretical standpoint. In the real world matters like security are often as crucial to the existence of a marketable product as the core concerns themselves.)
So in while in practice DI can be used to implement aspects, I would not call that process true DI. This is coming from someone who uses constructor injection exclusively.
Martin Fowler has a good article here on the meaning of Inversion of Control and Dependency Injection.
Spring.NET usage AOP is described in detail here. I'm more familiar with the Java-based version of Spring, so I cannot say with absolutely certainty that Spring.NET currently only supports proxy-based AOP.
That is, a class to be advised must implement an interface. Spring will create a dynamic proxy that implements this interface and delegates to the original target instance.
Although it does state:
In a future release we will implement proxies using inheritance, which will allow you to proxy classes without interfaces as well and will remove some of the remaining raw reference issues that cannot be solved using composition-based proxies.

IoC Containers and Domain Driven Design

I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
IOC containers are invaluable when designing unit-testable code and are orthogonal to DDD. You could create your own implementation of factory and builder patterns if you want...by why go through the trouble?
Absolutely. Use an IOC container that's just powerful enough to meet you specific requirements; no more, no less.
We use DDD, and dependency injection (the pattern), but do not use a dependency injection framework.
One problem with popular dependency injection frameworks is how they separate configuration into XML files. XML is a great markup language. How it became a configuration language, I will never understand. The issue, of course, is that you have to run the application before you know if everything is wired up correctly. It is also hard to see what code is used where. If you are using interfaces, then the only reference to an implementation will be in an XML file, which is harder to spot. And finally you lose type safety and generics. (I once saw a horrible bug in production which would have been caught by the compiler had we not been using XML.)
I should point out that I am not saying that dependency injection is bad. It is a fundamental pattern of good object design. But there is absolutely nothing wrong with doing wiring in a factory.
At my last two projects we have removed large amounts of "code" out of XML files, and into factories. The factories are wired up with container managed services (such as JDBC connections, JMS connections and so forth). The application has become much simpler to understand, because the factory is less verbose than XML. And as a Java programmer, it is much easier to wire together a program using control-space, instead of XML twiddling - and your IDE will highlight when you have broken something.
In an integration test, just create the objects as you would in a factory.
ie,
dbConnection = DatabaseConnectionFactory.connection();
serviceUnderTest = new PaymentProcessor(new CustomerRepository(connection));

Resources