Saturday, 22 April 2017

Replace Conditional with Polymorphism

Replace Conditional with Polymorphism

Problem Code

foreach(Employee in _emp)
{
    if(emp.IsManager)
    {
        emp.bonus = totalFreight/10m;
    }
    else
    {
        emp.bonus = totalFreight/10m;
    }
}

Solution Code

public class Employee
{
    public string Name;
    public bool IsManager;
    protected decimal bonus;
    public decimal Bonus { get{ return bonus;}}
    public virtual void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/1000;
    }
}
public class Manager : Employee
{
    public override void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/10;
    }
}

Benefits

  • Tell-Don't-Ask Principal instead of asking an object about its state and then performing actions based on this, it is much easier to simply tell the object what it needs to do and let it decide for itself how to do that.
  • Do Not Repeat (DRY) Principal we get rid of many almost identical conditionals.
  • Open/Closed Principle If we need to add a new variant, all you need to do is add a new subclass without touching the existing code

Tuesday, 11 April 2017

Some inheritance Cases in Objected Oriented Programming in CSharp

Inheritance by using Virtual and Override Keyword

Parameterized Constructor Inheritance

Common Errors while Inheritance