sander
sander

Reputation: 1654

Do I create a separate class for collection or store them in the same class?

I have 3 classes, Team, Game and Round.

Game contains a list of Teams.

Round contains a list of Game.

I'm going to create multiple objects from each class.

Should I create another classes for this like which contain a list of each object:

GameRepository
TeamRepository
RoundRepository

Or should I just keep the collections in their own classes?

Upvotes: 1

Views: 453

Answers (2)

Andrew
Andrew

Reputation: 49606

Remember the single responsibility principle.

I am sure your classes already have a plenty of methods to manage/control the inner state. Do they need another responsibility to take? No, they don't.

Storing items, being a collection is a completely new responsibility and it shouldn't be messed up with the already-given ones.


On the other hand, there is nothing wrong if a Round will contain a List<Game> and a Game will have references to Teams. But you need to be sure that, for example, removing a Game wouldn't affect Team instances. The issue is still to decide which class keeps instances, and which one just refers them.

Upvotes: 2

kfir88
kfir88

Reputation: 380

If I have to do that, I would do it this way(These classes can be in different files):

public class Game{
List<Team>teamList;
}

public class Round{
 List<Game>gameList;
}

public class Team{

}

That way if you have an instance of a Round, you have everything you need

Upvotes: 1

Related Questions