Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Object Oriented Programming which object should maintain the many to many relationship? (if there is one)

I'll use an example to illustrate this:

class Company {

}

class Person {

}

Company and Person hold a many to many relationship. A Person can belong to multiple Companies and a Company can hold multiple People.

Would I then need to create a third class:

class CompanyPerson {

}

or should the company handle it:

class Company {
    function add_person() {

    }
}

or maybe the Person should?

class Person {
    function add_to_company() {

    }
}
like image 658
Matt Avatar asked Mar 31 '12 06:03

Matt


2 Answers

It totally depends on you usage scenario.

If you only ever need to find the people who work for a company, store the list of People on the Company; if you only ever need to find the companies that people work for then store it there.

Sooner or later you'll probably find you need to model the actual relationship Person<-->Company and you'll create a separate class to represent that. Now you can handle adding properties like the date the employment began, the date it ended etc.

like image 191
Ian Mercer Avatar answered Sep 20 '22 22:09

Ian Mercer


The properties common to some random combination of a Person and Company instance can be modeled using an "association class".

There is a notation for this in UML, and it's not hard to create such a concept in an extensible programming language.

The idea is that any random pair of objects consisting of a Person and Company has a relationship, and that relationship is itself an object. It is neither Person nor Company, but the stuff associated with the connection between a particular Person and Company instance.

That stuff (properties, methods) constitutes a class: the Person-Company association class.

I made this work in Lisp before, with some macros for defining an association class for a given pair of classes, and a global weak hash table for mapping object pairs to their association class object (so that for a given person and company it was possible to retrieve the association, and that association would go away when these objects become garbage).

The actual link between particular companies and people is easy, using e.g. lists or other associative data structures. A person object can have a list of companies, and vice versa. The association class idea addresses the problem of where to put the person-company stuff. For example each Person has a role within a Company (let's say). We cannot have a role variable in a Person because it can have many roles w.r.t many companies. We certainly cannot have a role in the company because it's not even a person; it has people associated with it who have roles. The role can go into the association: problem solved.

like image 41
Kaz Avatar answered Sep 21 '22 22:09

Kaz