I'm aware of circular references (Class A holds Class B and Class B holds Class A). But since I haven't programmed enough, it's hard for me to find reasons to use them. I was wondering if people could give me some examples and explain good reasons for using them.
In my case, right now I'm looking at 2D source code tutorials and the user created a Creature and a CreatureAi class that reference each other. For what reason? I don't know yet, that's why I'm looking for examples and still reading around.
You have a class Company containing a list of Individuals that work for it. Every Individual class instance in the collection contains a reference to the Company they work for.
This way you can easily find out which individuals work for which companies. Note, that it may not necessarily be the best design especially if the classes are persisted into the database using an ORM or a document database.
The most obvious case of circular reference is self-reference: you need it for linked lists, trees, and lots of other recursive structures.
Circular references are often implicit within a hierarchy of relared classes, such as UI elements with arbitrary nesting, or expression trees.
Finally, a common case of circular referencing is bidirectional parent-child relationship: a parent (e.g. a UI panel) holds a reference to an array of its children, and each child (e.g. buttons, tables, etc.) holds a references to the parent. The parent needs to send motifications to its children to tell them that it became enabled, disabled, visible, or invisible; a child may notify the parent of the need to resize, change visual state, etc.
This last example is probably similar to your Creature-CreatureAI pair: they are separate because their concerns are dissimilar, but they have references to each other because they need to cooperate on different tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With