Consider two classes Team and Players.
Class Player
{
String name;
int age;
//Getters and Setters
}
What is the best way to represent a team of players.
1)
Class Team
{
String teamName;
String city;
List<Player> players;
//Getters and Setters
}
2)
Class Team
{
String teamName;
String city;
//Getters and Setters
}
Class TeamPlayers
{
Team team;
List<Player> players;
//Getters and Setters
}
The first form seems more logical for me, but the latter one gives more flexibility. So which one I can decide and what possible pros and cons of both of these approaches.
It depends (of course...)!
If u are going to implement a lot of methods which perform some actions directly on List<Player> players;
AND some methods which do something with Team
class, it will be more readable to use another class TeamPlayers
and do some wrappers (if needed) to TeamPlayers
methods inside Team
class.
When working with OOP code, I find that the best approach is always the one that models the problem most intuitively.
When you look at a Team
, it definitely has Players
. A Team
should almost certainly know about the players in it, as well as provide functionality for modifying its roster (i.e. addPlayer()
, removePlayer()
) - the first option would let this be done easily.
If you require the additional flexibility of the TeamPlayers
class, you could have the Team
contain an instance of it and then have the calls to any Player
related calls to Team
be delegated to TeamPlayers
. My two cents.
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