views:

144

answers:

4

Looking for opinions on this:

I have broken out various responsibilities into separate objects. However, many of these objects have dependencies on each other. All of these objects are adhering to interfaces so I'm not tied to an implementation. I'm concerned about the dependencies between objects and the potential for circular dependencies. Is this a symptom of bad design? What have other people done to separate responsibilities and manage dependencies? Thanks.

A: 

Well you can inject those dependencies.... If foo depends on an implementation of bar then make its constructor require an instance of bar as an argument or have it be set via a setter method.

prodigitalson
+2  A: 

What is important is that object models have Low Coupling and High Cohesion. That means that things should depend on other things only when they have to ( Coupling ) and that they should do one thing and only one thing ( very well ) ( Cohesion ). There is no simple answer about when to make these decisions other than experience ( which means learning from mistakes ) will be your main driver. There are lots of Design Patterns for addressing coupling ( Facade, Composite, Memento, Decorator, etc ). Cohesion is usually just a refactoring exercise to move things into or out of Classes when you start working with them.

fuzzy lollipop
+1  A: 

Generally, I try to avoid circular dependence like the plague because it makes things a pain to reason about and to instantiate. It also indicates that the circularly depending objects are very tightly coupled. While this may be necessary if it represents essential complexity in your problem, this coupling should be expressed more simply and cleanly in these cases. It may indicate that you would be better off using inheritance, if one object is clearly the "base" object and the other is clearly a "customization" object. Specifically, circular dependence is a strong hint that you should use the template method pattern instead of the strategy pattern. Circular dependencies may also indicate that you would be better off using a third class to model your problem.

dsimcha
A: 

As another reader has pointed out what you want your classes to have have Low Coupling and High Cohesion. If your classes have a risk of circular dependencies its sounds like you have a bad code smell.

Consider looking at the relationships in a layered, top-down approach. i.e. Which class makes more sense to contain the other? If its neither, and you need the functionality of both classes then consider a composite-adapter class that contains both.

mythz