Users/Roles design question
This may be quite trivial for many of you, but it's not my case...
I am trying to implement roles on a user class I've created. What I thought of was creating 3 classes:
- Role
- Roles (a container for all the existing roles)
- User
Each User should be able to contain none, one or many Role objects. My idea was to create a member in the User class, which consists of a collection where I can store each Role.
I also thought of having only one Role object per specific role, so that when, for example, the name of a Role in the Roles container is changed, the change is reflected in each User belonging to that Role (just because those are two references to the same object).
If someone wants to delete a Role, he should call a remove method from the Roles container (that removes the Role from the container and from every User). However, and this is what I don't like about this design, someone (just making a mistake) may try to do that by getting the Role from the container and setting it to null. I don't want to rely on the fact that the programmer will do things as they are suposed to be done, so... is there any way in which I can be sure that a Role object won't be set to null?
It's obvious that that doesn't make sense inside theses 3 classes (User, Role, Roles), but I'd really like to be able to achive that from outsider classes that I may not implement.
Though they don't convince me, my thoughts for solving this were:
- Never return the unique Role objects, but just clones of them. The drawback for this is that to keep the User roles synchronized I must update changes when modifying a Role property, or adding the Role object from the Roles container that is equal to the clone created.
- Creating an id for each Role and returning that instead of the Role object. In that case, whenever I need to calculate the roles of a User I would have to look up each id in the Roles container.
I hope my question is clear enough... any answer is really welcome.

