Refactoring Change Bidirectional Association to Unidirectional
ProblemYou have a bidirectional association between classes, but one of the classes does not use the other's features.
SolutionRemove the unused association.
A bidirectional association is generally harder to maintain than a unidirectional one, requiring additional code for properly creating and deleting the relevant objects. This makes the program more complicated.
In addition, an improperly implemented bidirectional association can cause problems for garbage collection (in turn leading to memory bloat by unused objects).
Example: the garbage collector removes objects from memory that are no longer referenced by other objects. Let's say that an object pair
Order was created, used, and then abandoned. But these objects will not be cleared from memory since they still refer to each other. That said, this problem is becoming less important thanks to advances in programming languages, which now automatically identify unused object references and remove them from memory.
There is also the problem of interdependency between classes. In a bidirectional association, the two classes must know about each other, meaning that they cannot be used separately. If many of these associations are present, different parts of the program become too dependent on each other and any changes in one component may affect the other components.
Simplifies the class that does not need the relationship. Less code equals less code maintenance.
Reduces dependency between classes. Independent classes are easier to maintain since any changes to a class affect only that class.
How to Refactor
- Make sure that one of the following is true for your classes:
- No association is used.
- There is another way to get the associated object, such through a database query.
- The associated object can be passed as an argument to the methods that use it.
Depending on your situation, use of a field that contains an association with another object should be replaced by a parameter or method call for getting the object in a different way.
Delete the code that assigns the associated object to the field.
Delete the now-unused field.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()