Blogger news

Blogger templates

Tuesday, May 30, 2017

Explaining oops abstraction with real world example

Maybe one of the most asked questions in object oriented programming is "Abstraction and encapsulation". In this article, I will explain what abstraction means using a real world example and converting that example to code.

Say in your house you do have an electric plug and many devices can connect to the same plug but plug will never have an idea which device it is connected to, in other words, the details of the devices is abstracted (hidden) to the plug.
Think what if we connect a device directly to electric wire without a plug? Say connect a bulb directly to a wire, then wire knows which device it is connected to and whenever we need to replace the bulb then we have to remove the wire connection from the bulb, which means the bulb is tightly coupled with the wire. In other words, bulb and wire know the details where it is connected to, means not abstracted.
In object oriented world abstraction works exactly same. The class which consumes other classes function/property doesn't need to know which classes function/property it is consuming and everything should be abstracted with an interface / abstract class.
Let me code the same example. Here I have a class "ElectricPlug", which is running a device. But the class "ElectricPlug" doesn't have any idea which device it is running. It can be any class implementing the interface "IDevice", which means the implementation of "RunDevice" is abstracted from "ElectricPlug". Here is the sample code,

class Program
{
    static void Main(string[] args)
    {
        ElectricPlug electricPlug = new ElectricPlug(new Bulb());
    }
}

public class ElectricPlug
{
    private readonly IDevice _device;
    public ElectricPlug(IDevice device)
    {
        _device = device;
    }

    public void Run()
    {
        _device.Rundevice();
    }
}


public interface IDevice
{
    void Rundevice();
}


public class Bulb : IDevice
{
    public void Rundevice()
    {
       Console.WriteLine("Switched on bulb");
    }
}


public class ElectricPlug
{
    private readonly IDevice _device;
    public ElectricPlug(IDevice device)
    {
        _device = device;
    }

    public void Run()
    {
        _device.Rundevice();
    }
}

No comments:

Post a Comment