Java - 2 Way 'Has A' Relationship
java, object, object-oriented-analysis, oop
Solution
Is there anything objectionable to this, or is it fine?
There's no definitive answer to this. The best answer is: it depends to the design of your application.
When to use it
If your `Client` object should navigate to the `Site` object and your `Site` object should navigate to the `Client` object, then the current example in your code is fine. Still, probably you will need some way to associate these elements, probably by an additional id field on one of the classes or in both.
If it happens that you work with a framework that helps you to bind the classes automatically like Hibernate, then maintaining the circular reference won't be a problem for you.
When not to use it
Basically, for text serialization, since it will generate an infinite loop. As already mentioned in Raibaz's answer, a library like Jackson will fall into infinite loop while serializing `Client` or `Site` class into a JSON string1. Note that this is also valid when serializing to other `String` data like passing the objects through a JAX-WS web service in XML (more info: What happens to generic class in jax-ws webservice?).
1 This can be solved using annotations (`@Something`) that belong to a specific library e.g. `@JsonManagedReference` and `@JsonBackReference` from Jackson library, as noted by @SimonAndréForsberg, but the downside of this solution is that your classes will have tight coupling with the library.
Problem
I have just started a project to make my employer a management software. I have a niggling, but potentially simple, query that I can't seem to find any information on. Is it prudent/good practice to have a 2 way 'has a' relationship between objects. So can, for example, a `Client` object 'have a' `Site`, and then the `Site` 'has a' `Client`, where the `Client` object is the `Client` that 'has' the `Site`? ``` public class Client { Site site; } public class Site { Client client; } ``` Is there anything objectionable (no pun intended) to this, or is it fine? I am currently creating a mock-up UML for the project, and this has been bothering me.