I have this basic design with a circular dependency. Is there any solution for this? The problem is that a Machine cannot be created if a Model for that Team has been submitted.
- 131
1 Answers
Design
From a design point of view, circular dependencies are usual business:
- A
teamworks withmodelsto build or testmachines. There is an ambiguity sincemanyis not defined in the UML notation. It suggests a multiplicity of either0..*or1..*. - Conversely, every
machineis build/tested based on a singlemodeland every machine is build/tested by oneteam. Here, 1 unambiguously means exactly one. - In absence of any constraints, a
machinecan be build by ateambased on amodelof anotherteam.
Implementation
You'll have to cope with circular dependencies, since each class has to know about the others. The solution depends on the language: there are already plenty of them on StackOverflow. Search for the tag circular-dependency combined with your favorite language. In general, with reference semantic (i.e. java object, C++ pointer or reference, C# class object) it is no particular difficulty.
Instantiation
You cannot enforce all the associations, if they are all mandatory at the same time. It's the circularity issue of the chicken and the egg, since there would always be a mandatory associated object missing for whatever you want to instantiate.
Possible solutions:
Relax the constraints: If
manyis understood as0..*, you could create ateamwithout having neither amodelnor amachine. You could then create amodelassociated with theteam, but with nomachineyet. Finally, you could create the machine for the both other elements. This appears to me the most natural solution.Create the egg first: Allow the creation of the objects without having all the associations from the start. Make a chicken out of the egg: use a variant of the builder pattern to make sure the that after the build process, all the mandatory constraints/associations are consistent.
Decouple time and constraints: Design explicitly the life-cycle of your objects, and enforce contraints in their behavior with the state pattern. You can then keep the object in an unusable state "Not ready" until all the mandatory associations are provided. But in your situation, this seems like a bulldozer rolling over a fly, and I'd still strongly suggest to consider optinon 1.
- 81,699
