Reputation: 91
I want to create a project with multiple classes but not sure how to properly connect them together.
Let's say our model consists of following classes. Sports leagues consists of multiple teams, teams consists of players and a manager. Let's say I want to connect players to a specific team and a team to a specific league.
I can add to a League class list of teams and to a Team class — list of Players and "Manager" property like that:
class League {
private List<Team> teams;
}
class Team {
private List<Player> players;
private Manager manager;
}
With this kind of "top-to-bottom" model we can easily construct league tables or get team rosters. But what we cannot do with this model is to take a player and find his manager or team-mates. And we can't find a position of a concrete team in a league because only league knows this information, but Team is unaware of what League it has been appointed to. One the other hand I can use "bot-to-top" approach and add property "Team" to a Player and "League" to a Team, but now we cannot easily create league tables since League doesn't consist of teams anymore.
I can make both kind of connections simultaneously and add "private League league" to a Team and "List teams" to a League. But it's kind of a making a job twice and that is not good either. Let's say I want to store both of them in a database and I certainly can't this properties to a table since they duplicate themselves.
So what is general principle of making classes dependent on each other? Maybe I should make another support classes to maintain connections between them? What kind of principles describe this kind of a problems? What should I read to better understand this dependencies?
Upvotes: 1
Views: 32
Reputation: 753
I consider the solution of implementing bidirectional dependencies to be the best for this particular scenario. There will be two main drawbacks though:
This will depend on the solution you are trying to implement. If you are expected to perform queries and so on, then it's fine, given that the utility it brings is way better than the issues it might cause. But if you are not planning to query the information that much, then I'd rather pay for the lower performance rather than maintenance and memory usage.
Upvotes: 1