Search code examples
c#oopdesign-patternsinheritancerole

inheritance and roles


Let's use a quite plain example with employees and company(-ies).

public abstract class Employee
{
    // bunch of its features
}

public sealed class SalesManager : Employee
{
}

public sealed class SEO : Employee
{
}

Employee can take different posts or play different roles. So using inheritance (maybe with factory patterns in addition) doesn't give such a flexibility for concrete employee instance to change its role.

What would you advice, unfortunately I haven't seen the kind of approaches yet. And I haven't met a book which lights up the problem.

Edit

Thank you guys! In my edit I wanted to ask one more thing. Using generic role is it possible to transfer such a BLL to DAL. I have heard that generics are not supported in Entity Framework??

Thanks!


Solution

  • Use a has-a relationship

    public class Employee 
    {
        public Role EmployeeRole { get; set; }
    }
    
    public enum Role 
    {
        SalesManager,
        SalesPerson
    }
    

    Or you can make Role a class to store additional information in addition to the name of their role.

    public class Role
    {
        public string Name { get; set; }
        public decimal BaseSalary { get; set; }
    }
    

    To illustrate @Aasmund Eldhuset's comment:

    public abstract class Role
    {
        public string Name { get; set; }
        public decimal BaseSalary { get; set; }
    
        public abstract void PerformRole();
    }
    
    public class SalesPerson : Role
    {
        public void PerformRole()
        {
            // Do something
        }
    }