Understanding open closed principle and dependency inversion

Source: Internet
Author: User
Introduction

In the following three articles I'm going to discuss solid. This is the part one of the series. I'll try to explain open colsed priciple and dependency inversion.

Now what does solid mean? Solid is the OOD (Object-orient design) principle, where each letter has its own mean

  • S->Single responsibility
  • O->OPEN CLOSED
  • L->Liskov substitution
  • I->Interface segregation
  • D->Dependency inversion

According to the Wikipedia the definition of solid is

"SOLID Are guidelines that can be applied while working on software to remove code smells by causing the programmer to refactor the software's source code until it is both legible and extensible ."

Using the code

Before Start TEC discuss I want to answer the below questions:

What is open closed principle?

Answer :"Software entities (classes, modules, functions, etc.) shocould be open for extension, but closed for Modification"

What is dependency inversion?

Answer:

  • High-level modules shocould not depend on low-level modules. Both shoshould depend on each action.
  • Specified actions shoshould not depend upon details. Details shoshould depend upon specified actions.

Let's consider an example to make it better understand. Suppose I need a computer, not decided yet whether I need desktop, laptop or other.

Suppose I go to a computer shop and ask for desktop computer. Let's convert my requirements into code.

using System;namespace SOLID{    public class Desktop    {        public string GetComputerDescription()        {            return "You get a desktop";        }    }    public class Laptop    {        public string GetComputerDescription()        {            return "You get a laptop";        }    }    public class ComputerShop    {        public enum ComputerType//Violation of OCP        {             Desktop,Laptop        }        public string GetComputerDescripution(ComputerType type)        {            var myComp = string.Empty;            if (type == ComputerType.Desktop)//Violation of OCP            {                myComp = new Desktop().GetComputerDescription();//Volation of DI            }            if (type == ComputerType.Laptop)            {                myComp = new Laptop().GetComputerDescription();            }            return myComp;        }    }    class Program    {        static void Main(string[] args)        {            var computerShop = new ComputerShop();            string desc=computerShop.GetComputerDescripution(ComputerShop.ComputerType.Desktop);                    }    }}

If you run the code it will execute fine and give you a output "you get a desktop". So what's wrong? Here we are violating OCP (open closed principle) and DIP (dependency inversion principle ).

  • Closed for Modification. (We did violation of OCP)
  • High-level modules shocould not depend on low-level modules. Both shold depend on each action. (We did violation of DIP)

Still confuse? No problem I am explaining.

How we violate OCP?

Yes we did it by creating instances of desktop class and laptop class on getmycomputerdescripution method. Because if a new type computer come, then we needModify the function as well as the class Enum.

How we violate dip?

Yes we did it by creating low-level object (desktop, laptop) on high-level object (computer ). so high-level module depends on low-level module (desktop, laptop) and no such action here.

Now I am adding a new type (tablet) and modify my class by violation of OCP and dip.

public class ComputerShop{    public enum ComputerType    {        Laptop, Desktop, Tablet  // Violation of OCP    }     public ComputerShop()    {    }    public string GetMyComputerDescription(ComputerType type)    {        var myComp = string.Empty;        if (ComputerType.Desktop == type)        {            myComp = new Desktop().GetComputer();        }        else if (ComputerType.Laptop == type)        {            myComp = new Laptop().GetComputer();        }                                         // Violation of OCP        else if (ComputerType.Tablet == type)        {            myComp = new Tablet().GetComputer();        }        return myComp;    }}

Did you notice the violation? Yes we modify the class as New Type introduce.

Now let's follow the OCP and dip rules and implement the new structure.If we can get the required computer without creating object of low-level class on shop class, then we can achieve our goal. Now we are going to introduce the specified action.

using System;namespace OCPDI{    public interface IComputer    {        string GetComputerDescripution();    }    public class Desktop:IComputer     {        public string GetComputerDescripution()        {            return "You get a desktop";        }    }    public class Laptop:IComputer     {        public string GetComputerDescripution()        {            return "You get a laptop";        }    }    //    public class Tablet : IComputer    {        public string GetComputerDescripution()        {            return "You get a tablet";        }    }    //--    public class AnotherNewItem : IComputer    {        public string GetComputerDescripution()        {            return "Another new item";        }    }    public class ComputerShop    {        public string GetMyComputerDescripution(IComputer computer)        {            var myComp = computer.GetComputerDescripution();            return myComp;        }    }    class Program    {        static void Main(string[] args)        {            var computerShop = new ComputerShop();            var desc=computerShop.GetMyComputerDescripution(new Laptop());            Console.WriteLine(desc);        }    }}

We introduce a interface (icomputer) to remove the dependency from computershop, desktop, laptop, etc.

Also now both high-level and low-level modules depend on each action and the specified acion does not depend on details. So if the details changed, they shocould not affect the specified acion (satisfy DIP ).

Now we extend our new item (tablet, anothernewitem) without modify the computershop class (satisfy OCP ).

Points of interest

So the interface gives an extendability and remove dependency. Now whatever computer type comes, computershop class does not depend on any Lowe-level module.

    public class AnotherNewItem : IComputer    {        public string GetComputerDescripution()        {            return "Another new item";        }    }

It simply give the product we need from your acion.

    public class ComputerShop    {        public string GetMyComputerDescripution(IComputer computer)        {            var myComp = computer.GetComputerDescripution();            return myComp;        }    }

So now our Code satisfy both OCP and dip.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.