views:

57

answers:

3

I am working on an application where I can have Teacher, Student etc role. Some of the functionality is similar so I also have a base class User. User contains AddRole method and other stuff.

Now, I want that when the Teacher object is created the "Teacher" role is automatically assigned to the object. I am doing this inside the constructor but I think it is ugly. Here is the code:

public class Teacher : User
    {
        public Teacher()
        {
            AddRole(new Role() { RoleName = "Teacher"});
        }
    }

There is no Teacher table in the database. Everything is User based. Teacher is just a Role and have different functionality then a Student.

How would I go about this?

A: 

How does it work in your domain model? Whatever works for your domain model should be in your code.

Samuel Carrijo
+2  A: 

How about

//C++ look alike pseudocode 
   public class User{
      String role;

      User (role_){role = role_;}

      String getRole(){return role;}

   }


    public class Teacher : User
        {
            public Teacher():User("Teacher")
            {

            }
        }
Tom
I like this approach. Just wondering if I should send a string or RoleType enum to the User constructor. Thanks!
azamsharp
I would go with some kind of enum, so that magic strings are avoided, and the functionality of comparison operators is clear and defined.
Tom
Instead of using a string or an enum, what about using the Type itself? E.g. public Teacher() : User(typeof(TeacherRole)). This would eliminate the need to keep types/enums synchronised.An alternative is to use Decorator + Factory/Builder pattern, although things could get convoluted very quickly.
Vijay Patel
A: 

It's actually quite common to have a Role table that has a 1-to-m or m-to-m relationship with the User table.

The implementation depends highly on how your roles are going to be used. Do they have functions associated with them? Or are they just labels? Are your roles fixed or dynamic? Depending on how they're used and defined, interfaces or inheritance might work for your roles, or actual Role objects might be better.

aberrant80
That's what I was wondering, why only one role?
Eric
Actually I have an IList<Role> which will save a list of Roles!
azamsharp
Yep, that AddRole() implies more than one role. What I think Eric means is that, quiet commonly, a Role contains a List<User> as well.
aberrant80