-1

Say we have to create a model for a company, where employees can be part of many different teams.

A team can have member members. Members can be part of many teams.

How to design database tables for this is well known, but what would be a good model for this in the world of classes? Both Team and Member have their own identity, and traversal could go both ways; i.e. equal likelihood of users getting members of a team or getting teams of a member.

Although this is an elementary example, it's hard to find good documented solutions.

1

Since you didn't specify a language, here's a naive approach that can be implemented in most OOP-languages.

Each Team and each Member are unique standalone objects. Each Team has a container with references/pointers to all Members it contains. Each Member has a container with references/pointers to all Teams they're part of.

This way you can easily look up which Team contains which Members and vice versa.

An added bonus would be that in case of deletion (a Team gets disbanded or a Member leaves the company) you'll just have to look at the object you want to delete and know which other objects you need to update (so you're not referencing deleted objects).

5
  • Yes, but I don't think the naive approach is good. For Swift structs, this won't work. Also, consider the situation where you're printing the objects to the console. If the team prints all users and all users prints teams, that will result in a stack overflow. – funct7 Mar 31 at 2:40
  • @funct7 I have no idea how swift works. I was mainly talking about C (++/#), Python, etc. – TheBeautifulOrc Mar 31 at 10:12
  • Yes, but the fact that it's reliant on a specific implementation makes me think it may not be a good design. – funct7 Apr 1 at 6:15
  • Well not exactly a "specific implementation" but rather one that can be done in any language where objects can be referenced. Are you absolutely sure that swift can't do that? – TheBeautifulOrc Apr 1 at 12:21
  • 1
    "If the team prints all users and all users prints teams, that will result in a stack overflow". That's only true if you do something silly like refuse to print yourself without printing everything you're connected to. Doing that will break things regardless of language or paradigm. Remember, it's source code dependency cycles that are bad. If dynamic cycles are banned then doubly linked lists are banned. Being acyclic can be good but please don't over apply it. – candied_orange Apr 1 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.