Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent multiplicity in java with less coupling

Tags:

java

oop

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.

like image 539
Hariharan Avatar asked Sep 13 '13 07:09

Hariharan


2 Answers

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.

like image 198
IProblemFactory Avatar answered Nov 11 '22 18:11

IProblemFactory


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.

like image 1
Surveon Avatar answered Nov 11 '22 18:11

Surveon