Question

A small payroll program which pays employees a salary or an amount based on how many hours they've worked in a month (Hourly paid employees only) Here is one of two class diagrams I have produced:

Class Diagram 1

This version uses two child classes to define two types of employees and inherits the base attributes from the Employee parent class and the two child classes have their own methods to pay the two kinds of employees.

My other version however looks like this:

Class Diagram 2

This version uses method overriding based on what type of employee is being paid.

Which is more suitable in terms of implementation based on the other classes and their relationships? Will implementing one over the other have any kind of drastic effect?

Was it helpful?

Solution

I wouldn't subclass Employee at all. I'd maybe model it as Employee HAS a PaymentStrategy, which is subclassed with HourlyPaymentStrategy, SalaryPaymentStrategy, etc.

To expand as to why: In statically-typed languages like Java and C#, an object can't change its type once instantiated. So, using inheritance, an hourly employee could never become a salaried employee, whereas, with composition, you could replace his PaymentStrategy property from an instance of HourlyPaymentStrategy with SalaryPaymentStrategy.

OTHER TIPS

Yet another possibility is to have only one employee type but a hierarchy of pay types.

abstract class PayType
{
    public abstract decimal CalculateSalary();
}

class HourlyRate : PayType
{
}

class Salary : PayType
{
}

The employees would have a PayType property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top