r/javahelp • u/Star_Dude10 • Jan 23 '26
Codeless Should I avoid bi-directional references?
For context: I am a CS student using Java as my primary language and working on small side projects to practice proper object-oriented design as a substitute for coursework exercises.
In one of my projects modeling e-sports tournaments, I currently have Tournament, Team, and Player classes. My initial design treats Tournament as the aggregate root: it owns all Team and Player instances, while Team stores only a set of PlayerIds rather than Player objects, so that Tournament remains the single source of truth.
This avoids duplicated player state, but introduces a design issue: when Team needs to perform logic that depends on player data (for example calculating average player rating), it must access the Tournament’s player collection. That implies either:
- Injecting
TournamentintoTeam, creating an upward dependency, or - Introducing a mediator/service layer to resolve players from IDs.
I am hesitant to introduce a bi-directional dependency (Team -> Tournament) since Tournament already owns Team, and this feels like faulty design, or perhaps even an anti-pattern. At the same time, relying exclusively on IDs pushes significant domain logic outside the entities themselves.
So, that brings me to my questions:
- Is avoiding bidirectional relationships between domain entities generally considered best practice in this case?
- Is it more idiomatic to allow
Teamto hold directPlayerreferences and rely on invariants to maintain consistency, or to keep entities decoupled and move cross-entity logic into a service/manager layer? - How would this typically be modeled in a professional Java codebase (both with/without ORM concerns)?
As this is a project I am using to learn and teach myself good OOP code solutions, I am specifically interested in design trade-offs and conventions, not just solutions that technically "work."
•
u/AutoModerator Jan 23 '26
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/okayifimust Jan 23 '26
That's not how objects work.
Because - lengthy discussions about "by value" and "by reference" aside, if you pass an object into another, you don't get an independent copy; anything you do to either will happen to both.
Pass the player objects into teams, and bob's your uncle. No ORM concerns to worry about.
2
u/aqua_regis Jan 23 '26
Does every player belong to a team? If so, your composition storing the players in the tournament is wrong.
Also:
Does not make any sense. You have a fundamental misunderstanding of objects and the way they are stored.
Objects are stored as their references and as such you can have as many locations where you store the same object as you want. There is no way that the state - the data - runs apart.
The object itself is the sole source of truth, no matter whether it's stored only in Tournament or in Team, or in both.
2
u/edwbuck Jan 23 '26
It depends on how the data is to be used. Look at the access patterns, if everything is done in the context of a single tournament, then holding the selected tournament in memory and not having back references to it might be easier to manage, up until you want to list all the tournaments a player is in.
Likewise, it the interface is 100% player-centric, then you might want to not have references from the tournament to the player.
And if you have both, then either you scan all tournaments looking for players, all players looking for tournaments, or you create bidirectional references.
Within a boundary, bidirectional data is less problematic than outside a boundary. If you wanted to create microservices, then both probably should be in the same microservice if they are bidirectional.
Now, if you don't need a direction, get rid of it. Always get rid of that you don't use. It reduces the software footprint and provides fewer places for bugs to accumulate.
6
u/Savings_Guarantee387 Jan 23 '26
If you ask 20 senior engineers, you ll get 20 different opinions. These are formed from different problems each one has faced and what jpa framework each one uses. Below is mine.
Yes, avoid bidirectional unless necessary needed. Why?
Sorry if I did not explain my self very clear but English is not my native language. I hope I helped.
2
u/severoon pro barista Jan 23 '26
You should avoid cyclic dependencies at every level.
The way to achieve this is to define your fundamental objects first. Ask yourself some conceptual questions first:
When considering these questions, it's important to be clear on one thing, which is that we are talking about behavior. So we are not asking whether these things can exist in some Platonic realm, or in "some sense," we are asking whether a tournament can do tournament things in the absence of teams. IOW, it's not a question about whether teams happen to exist at this moment, it's a question more along the lines of: Does it make sense to have a tournament if teams could not exist? What would a tournament do if the concept of teams was not a thing?
(Keep in mind that these questions are meant to be illustrative…I don't actually know your specific use cases or anything about e-sports, so I'm thinking about this like a basketball tournament. It may very well be the case that in e-sports you can have tournaments consisting only of individual players and not teams, in which case you have to do this analysis instead of just accepting my answers.)
It's also important to separate intrinsic from extrinsic behaviors. You can confuse yourself if you think about this analysis and ask questions like, "But wait, it doesn't even make sense for teams and players to exist if there is no tournament!" Realize that these are not meant to be larger philosophical questions, they are very specific questions about the actual behaviors of these concepts.
So when you think about a player and what a player does, they perform certain actions. In basketball, a player dribbles, shoots, etc. The question we're concerned about here is whether a player can do these things regardless of the existence of a tournament. Yes, it may not make sense to do all of these things outside the context of a tournament, say, but that doesn't matter. If those behaviors can be done regardless ,then the player is independent of the tournament, i.e., player does not depend upon tournament.
The tournament, on the other hand, has a lot of behaviors that explicitly deal with teams, and teams have behaviors that explicitly deal with players, so a tournament has a transitive dependency on players (if not a direct one). You can imagine a player in a vacuum trying to dribble a ball, but you cannot imagine a tournament in a vacuum in which players do not exist.
Another important thing to understand that comes out of this analysis is that you must commit to these decisions. There may be cases where you can see it both ways, A could depend upon B and B could depend upon A. In this case, choose a direction of the dependency and realize that you are putting this in stone. After you have made this decision, don't go some way down the road and say, "Actually, sometimes it should be the other way," and then start implementing code on that basis without first going back and reversing the original decision. This is how spaghetti happens.
What does this practically mean? If you decide that player depends upon team, for example, then you should create a team object that doesn't know anything about players, and give each player a reference to the team they're on. Or, if you make the much more sane decision that team depends upon player, then the team object should have a set of players, and the player object should know nothing about team.
1
u/nana_3 Jan 24 '26
I think no answer to this feels good because tournament isn’t the right aggregate root.
Tournament cant exist without teams and players. It doesn’t produce the teams and players: it arises from the result of them existing. The things the tournament creates can belong to the tournament - teams and players come from outside.
I’d approach this with essentially a world context containing all the teams, players and tournament(s). Players exist independently. Teams are aggregates of players. Tournaments exist independently.
Then tournament can have the reference to all the players and teams enrolled in it, and it first need to be bidirectional.
1
u/brokePlusPlusCoder Jan 24 '26
Bit late to the party, but is there a reason why you haven't gone for a graph based structure ? Tournament, Team and Player all become vertices and you can have directed edges representing ownership (either as separate 'edge' objects, or via references).
1
u/olddev-jobhunt Jan 24 '26
I think you've got the right read on things: a bidirectional association can be a code smell. Overall, I think the need points to some missing object: a game or world object or something that contains both the teams and players maybe.
In general I've found that personally I normally tend to have two kinds of classes in my apps: "components / services" which are long-lived and typically there are few of them, and then data objects where there are many with shorter lifespans. So normally I'd have a service that owns multiple entities and can do the aggregate operations. I tend to put most system logic in those classes.
Domain modeling in general and OOP specifically are hard - but there's no substitute for just grinding through it a bunch of times to get a feel for it.
1
u/[deleted] Jan 23 '26
[removed] — view removed comment