Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two objects with dependencies for each other. Is that bad?

I am learning a lot about design patterns when I am building my own system for my projects. And I want to ask you about a design question that I can't find an answer to.

Currently I am building a little Chat-server using sockets, with multiple Clients. Right now I have three classes:

  1. Person-class which holds information like nick, age and a Room-object.
  2. Room-class which holds information like room-name, topic and a list of Persons currently in that room.
  3. Hotel-class which have a list of Persons and a list of Rooms on the server.

I have made a diagram to illustrate it:

I have a list of persons on the server in the Hotel-class because it would be nice to keep track of how many there are online right now (Without having to iterate through all of the rooms). The persons live in the Hotel-class because I would like to be able to search for a specific Person without searching the rooms.

Is this bad design? Is there another way of achieve it?

Thanks.

like image 571
Kasper Grubbe Avatar asked Apr 11 '10 02:04

Kasper Grubbe


2 Answers

I don't like it. A hotel contains rooms, and rooms contain people. People don't contain rooms, they belong to them.

You don't necessarily have to iterate to get your guest count. You could just keep a running count ($Hotel->total_guests) and modify it as it changes.

like image 126
Syntax Error Avatar answered Nov 12 '22 22:11

Syntax Error


The mutual dependency problem among the classes, strictly speaking, can be solved by using interfaces (abstract classes, if your language is e.g. C++ or Python) IRoom and IPerson; in pseudocode

interface IPerson
    IRoom getRoom()
    // etc

interface IRoom
    iter<IPerson> iterPerson()
    // etc

this makes only the interfaces mutually dependent on each other -- the actual implementations of the interfaces need only depend on the interfaces.

This also gives you plenty of leeway in terms of implementation, if you want avoid circular reference loops (which can be a bother e.g. in CPython by slowing down garbage collections) -- you could use weak references, an underlying relational database with a typical "one to many relationship" table, etc, etc. And for the first simple prototype you can use what's simplest in your chosen language (probably simple, and alas necessarily circular, references [[pointers, in C++]] with a Person referring to a Room and a Room to a list<Person>).

like image 42
Alex Martelli Avatar answered Nov 12 '22 21:11

Alex Martelli