Description
In OOP you will often encounter the abundance of using IF/Else which on the negative side may provide a deep layer of nesting, increasing the complexity of your solution. Imagine having more than 2 variables that must be tested simultaneously.
There are some good design patterns that would replace the classical procedural approach with a nice smooth OOP approach. One approach is named Strategy Pattern. Consider the following objects:
csharp
public enum EmployeeType
{
Manager,
Administrative,
General
}
public class Employee
{
public string Name { get; set; }
public EmployeeType Type { get; set; }
}
public class Payments
{
public double Pay(Employee employee)
{
switch (employee.Type)
{
case EmployeeType.Administrative:
return 100;
case EmployeeType.Manager:
return -1000;
case EmployeeType.General:
return 200;
default:
return 0;
}
}
}
static void Main(string[] args)
{
Employee me = new Employee { Name = "Me", Type = EmployeeType.Manager };
Payments payments = new Payments();
Console.WriteLine(payments.Pay(me));
}Solution
We continue by introducing polymorphism into the Employee class. Then instead of determining what type of employee it is, we define separate handlers for each:
csharp
public abstract class Employee
{
public string Name { get; set; }
public EmployeeType Type { get; protected set; }
}
public class EmployeeAdministrative : Employee
{
public EmployeeAdministrative()
{
this.Type = EmployeeType.Administrative;
}
}
public class EmployeeManager : Employee
{
public EmployeeManager()
{
this.Type = EmployeeType.Manager;
}
}
public class EmployeeGeneral : Employee
{
public EmployeeGeneral()
{
this.Type = EmployeeType.General;
}
}
public class Payments
{
public double Pay(EmployeeAdministrative employee) => 100;
public double Pay(EmployeeManager employee) => -1000;
public double Pay(EmployeeGeneral employee) => 200;
}
static void Main(string[] args)
{
EmployeeManager me = new EmployeeManager { Name = "Me" };
Payments payments = new Payments();
Console.WriteLine(payments.Pay(me));
}The following introduces a new pattern — Strategy Pattern — into the overloaded methods, which makes the code even cleaner:
csharp
public class Payments
{
private Dictionary<EmployeeType, Func<double>> paymentType
= new Dictionary<EmployeeType, Func<double>>
{
{ EmployeeType.Manager, () => -1000 },
{ EmployeeType.Administrative, () => 100},
{ EmployeeType.General, () => 200 }
};
public double Pay(Employee employee) => paymentType[employee.Type]();
}
static void Main(string[] args)
{
EmployeeManager me = new EmployeeManager { Name = "Me" };
Payments payments = new Payments();
Console.WriteLine(payments.Pay(me));
}