1

So I have a class called Game and I need to retrieve several objects of Game from the database based on their session ID, so I have this method:

public ArrayList<Game> getGamesBySession

Okay, but I have to pass a parameter there so I would know which session's games I want to retrieve and I have two possibilities. I can either pass an int or I can pass an object of Session which has an attribute id and then use session.getID(). In the end, both would result in the same thing basically, but what I am wondering is something else.

My question is, which is a better approach and if I pass an object, would it mean that Game is high coupled with Session and violates GRASP?

Nikola
  • 2,093
  • 3
  • 22
  • 43

1 Answers1

1

That depends, is session.ID just an int? If it is, I would rather pass the entire session in, since getGamesBySession(session) is a lot clearer than getGamesBySession(int).

However, you could also consider wrapping the int into a SessionIdentifier object, which gives a bit more semantic meaning to the value. getGameBySession(SessionIdentifier) is equally as clear and would prevent you from passing in some random int from elsewhere...

MattDavey
  • 8,897
  • 3
  • 31
  • 54
  • Yes, `sessionID` is an `int`. Basically my project is a really simple one, just `Game` and `Session` where `Session` is basically a collection of `Game` objects, but I also use a database, therefore I need to search with an ID to obtain all `Game`s for a specific `Session` (through `id`). Isn't `SessionIdentifier` too much? A whole class for an integer? However, I accept criticism, that's why I asked for help :-) – Nikola Jun 20 '13 at 13:34
  • 1
    The problem with a "naked" int (or any other primitive value) is that it has no semantic meaning - it's just a scalar value. Take the Date constructor (`Date(int, int, int)`). It's very easy to mix up the years, months and days. (`Date(years, months, days)`) is a lot clearer... By making small primitive wrappers, you're attaching a little more semantic meaning to the parameter, giving both the developer and the compiler additional information (it's no longer possible to pass years to the months parameter). – MattDavey Jun 20 '13 at 13:40
  • The other benefit to these small primitive wrappers is that data validation has an obvious place to live. For example a `Days` class might limit the value to 1-31 - this is a constraint that does not exist on a "naked" int. This can save you from duplicating simple validation (`assert days > 0 && days <= 31`) all over your codebase... – MattDavey Jun 21 '13 at 08:18