开发者

OO Design Question

开发者 https://www.devze.com 2022-12-19 18:52 出处:网络
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 inte

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 implem开发者_如何学JAVAentation. 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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号