<p>What is the dependency inversion principle and why is it important?</p>

[{'answer_id': 62577, 'author': 'Carl Seleborg', 'author_id': 2095, 'author_profile': 'https://Stackoverflow.com/users/2095', 'pm_score': 8, 'selected': True, 'text': '<p>Check this document out: <a href="https://drive.google.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZjRhMDRlNTQ3ZGMz/view" rel="noreferrer">The Dependency Inversion Principle</a>.</p>\n\n<p>It basically says:</p>\n\n<ul>\n<li>High level modules should not depend upon low-level modules. Both should depend upon abstractions.</li>\n<li>Abstractions should never depend upon details. Details should depend upon abstractions.</li>\n</ul>\n\n<p>As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.</p>\n\n<p>Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.</p>\n\n<p>By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.</p>\n'}, {'answer_id': 62594, 'author': 'Marc Hughes', 'author_id': 6791, 'author_profile': 'https://Stackoverflow.com/users/6791', 'pm_score': 1, 'selected': False, 'text': "<p>The point of dependency inversion is to make reusable software.</p>\n\n<p>The idea is that instead of two pieces of code relying on each other, they rely on some abstracted interface. Then you can reuse either piece without the other.</p>\n\n<p>The way this is most commonly achieved is through an inversion of control (IoC) container like Spring in Java. In this model, properties of objects are set up through an XML configuration instead of the objects going out and finding their dependency.</p>\n\n<p>Imagine this pseudocode...</p>\n\n<pre><code>public class MyClass\n{\n  public Service myService = ServiceLocator.service;\n}\n</code></pre>\n\n<p>MyClass directly depends on both the Service class and the ServiceLocator class. It needs both of those if you want to use it in another application.  Now imagine this...</p>\n\n<pre><code>public class MyClass\n{\n  public IService myService;\n}\n</code></pre>\n\n<p>Now, MyClass relies on a single interface, the IService interface. We'd let the IoC container actually set the value of that variable.</p>\n\n<p>So now, MyClass can easily be reused in other projects, without bringing the dependency of those other two classes along with it.</p>\n\n<p>Even better, you don't have to drag the dependencies of MyService, and the dependencies of those dependencies, and the... well, you get the idea.</p>\n"}, {'answer_id': 62613, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Inversion_of_Control" rel="nofollow noreferrer">Inversion of control</a> (IoC) is a design pattern where an object gets handed its dependency by an outside framework, rather than asking a framework for its dependency.</p>\n\n<p>Pseudocode example using traditional lookup:</p>\n\n<pre><code>class Service {\n    Database database;\n    init() {\n        database = FrameworkSingleton.getService("database");\n    }\n}\n</code></pre>\n\n<p>Similar code using IoC:</p>\n\n<pre><code>class Service {\n    Database database;\n    init(database) {\n        this.database = database;\n    }\n}\n</code></pre>\n\n<p>The benefits of IoC are:</p>\n\n<ul>\n<li>You have no dependency on a central\nframework, so this can be changed if\ndesired.</li>\n<li>Since objects are created\nby injection, preferably using\ninterfaces, it\'s easy to create unit\ntests that replace dependencies with\nmock versions.</li>\n<li>Decoupling off code.</li>\n</ul>\n'}, {'answer_id': 462884, 'author': 'Hace', 'author_id': 18703, 'author_profile': 'https://Stackoverflow.com/users/18703', 'pm_score': 3, 'selected': False, 'text': '<p>Good answers and good examples are already given by others here.</p>\n\n<p>The reason <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle" rel="nofollow noreferrer">DIP</a> is important is because it ensures the OO-principle "loosely coupled design".</p>\n\n<p>The objects in your software should NOT get into a hierarchy where some objects are the top-level ones, dependent on low-level objects. Changes in low-level objects will then ripple-through to your top-level objects which makes the software very fragile for change.</p>\n\n<p>You want your \'top-level\' objects to be very stable and not fragile for change, therefore you need to invert the dependencies.</p>\n'}, {'answer_id': 1113937, 'author': 'Derek Greer', 'author_id': 1219618, 'author_profile': 'https://Stackoverflow.com/users/1219618', 'pm_score': 7, 'selected': False, 'text': '<h2>What Is It?</h2>\n<p>The books Agile Software Development, Principles, Patterns, and Practices and Agile Principles, Patterns, and Practices in C# are the best resources for fully understanding the original goals and motivations behind the Dependency Inversion Principle.  The article &quot;The Dependency Inversion Principle&quot; is also a good resource, but due to the fact that it is a condensed version of a draft which eventually made its way into the previously mentioned books, it leaves out some important discussion on the concept of a package and interface ownership which are key to distinguishing this principle from the more general advise to &quot;program to an interface, not an implementation&quot; found within the book Design Patterns (Gamma, et. al).</p>\n<p>To provide a summary, the Dependency Inversion Principle is primarily about <strong>reversing</strong> the conventional direction of dependencies from &quot;higher level&quot; components to &quot;lower level&quot; components such that &quot;lower level&quot; components are dependent upon the interfaces <strong>owned</strong> by the &quot;higher level&quot; components.  (Note: &quot;higher level&quot; component here refers to the component requiring external dependencies/services, not necessarily its conceptual position within a layered architecture.)  In doing so, coupling isn\'t <strong>reduced</strong> so much as it is <strong>shifted</strong> from components that are theoretically less valuable to components which are theoretically more valuable.</p>\n<p>This is achieved by designing components whose external dependencies are expressed in terms of an interface for which an implementation must be provided by the consumer of the component.  In other words, the defined interfaces express what is needed by the component, not how you use the component (e.g. &quot;INeedSomething&quot;, not &quot;IDoSomething&quot;).</p>\n<p>What the Dependency Inversion Principle does not refer to is the simple practice of abstracting dependencies through the use of interfaces (e.g. MyService → [ILogger ⇐ Logger]).  While this decouples a component from the specific implementation detail of the dependency, it does not invert the relationship between the consumer and dependency (e.g. [MyService → IMyServiceLogger] ⇐ Logger.</p>\n<h2>Why Is It Important?</h2>\n<p>The importance of the Dependency Inversion Principle can be distilled down to a singular goal of being able to reuse software components which rely upon external dependencies for a portion of their functionality (logging, validation, etc.)</p>\n<p>Within this general goal of reuse, we can delineate two sub-types of reuse:</p>\n<ol>\n<li><p>Using a software component within multiple applications with sub-dependency implementations (e.g. You\'ve developed a DI container and want to provide logging, but don\'t want to couple your container to a specific logger such that everyone that uses your container has to also use your chosen logging library).</p>\n</li>\n<li><p>Using software components within an evolving context (e.g. You\'ve developed business-logic components which remain the same across multiple versions of an application where the implementation details are evolving).</p>\n</li>\n</ol>\n<p>With the first case of reusing components across multiple applications, such as with an infrastructure library, the goal is to provide a core infrastructure need to your consumers without coupling your consumers to sub-dependencies of your own library since coupling to such dependencies requires your consumers to require the same dependencies as well.  This can be problematic when consumers of your library choose to use a different library for the same infrastructure needs (e.g. NLog vs. log4net), or if they choose to use a later version of the required library which isn\'t backward compatible with the version required by your library.</p>\n<p>With the second case of reusing business-logic components (i.e. &quot;higher-level components&quot;), the goal is to isolate the core domain implementation of your application from the changing needs of your implementation details (i.e. changing/upgrading persistence libraries, messaging libraries, encryption strategies, etc.).  Ideally, changing the implementation details of an application shouldn\'t break the components encapsulating the application\'s business logic.</p>\n<p>Note: Some may object to describing this second case as actual reuse, reasoning that components such as business-logic components used within a single evolving application represents only a single use.  The idea here, however, is that each change to the application\'s implementation details renders a new context and therefore a different use case, though the ultimate goals could be distinguished as isolation vs. portability.</p>\n<p>While following the Dependency Inversion Principle in this second case can offer some benefit, it should be noted that its value as applied to modern languages such as Java and C# is much reduced, perhaps to the point of being irrelevant.  As discussed earlier, the DIP involves separating implementation details into separate packages completely.  In the case of an evolving application, however, simply utilizing interfaces defined in terms of the business domain will guard against needing to modify higher-level components due to changing needs of implementation detail components, even if the implementation details ultimately reside within the same package.  This portion of the principle reflects aspects that were pertinent to the language in view when the principle was codified (i.e. C++) which aren\'t relevant to newer languages.  That said, the importance of the Dependency Inversion Principle primarily lies with the development of reusable software components/libraries.</p>\n<p>A longer discussion of this principle as it relates to the simple use of interfaces, Dependency Injection, and the Separated Interface pattern can be found <a href="http://aspiringcraftsman.com/2008/12/28/examining-dependency-inversion/" rel="nofollow noreferrer">here</a>.  Additionally, a discussion of how the principle relates to dynamically-typed languages such as JavaScript can be found <a href="http://aspiringcraftsman.com/2012/01/22/solid-javascript-the-dependency-inversion-principle/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 1355089, 'author': 'Rogério', 'author_id': 2326914, 'author_profile': 'https://Stackoverflow.com/users/2326914', 'pm_score': 3, 'selected': False, 'text': '<p>To me, the Dependency Inversion Principle, as described in the <a href="http://www.objectmentor.com/resources/articles/dip.pdf" rel="noreferrer">official article</a>, is really a misguided attempt to increase the reusability of modules that are inherently less reusable, as well as a way to workaround an issue in the C++ language.</p>\n\n<p>The issue in C++ is that header files typically contain declarations of private fields and methods. Therefore, if a high-level C++ module includes the header file for a low-level module, it will depend on actual <b>implementation</b> details of that module. And that, obviously, is not a good thing. But this is not an issue in the more modern languages commonly used today.</p>\n\n<p>High-level modules are inherently less reusable than low-level modules because the former are normally more application/context specific than the latter. For example, a component that implements an UI screen is of the highest-level and also very (completely?) specific to the application. Trying to reuse such a component in a different application is counter-productive, and can only lead to over-engineering.</p>\n\n<p>So, the creation of a separate abstraction at the same level of a component A that depends on a component B (which does not depend on A) can be done only if component A will really be useful for reuse in different applications or contexts. If that\'s not the case, then applying DIP would be bad design.</p>\n'}, {'answer_id': 31323674, 'author': 'martin.ra', 'author_id': 5083711, 'author_profile': 'https://Stackoverflow.com/users/5083711', 'pm_score': 4, 'selected': False, 'text': '<p>Basically it says:</p>\n\n<p>Class should depend on abstractions (e.g interface, abstract classes), not specific details (implementations).</p>\n'}, {'answer_id': 35355975, 'author': 'xurxodev', 'author_id': 3537539, 'author_profile': 'https://Stackoverflow.com/users/3537539', 'pm_score': 4, 'selected': False, 'text': '<p>Dependency inversion well applied gives flexibility and stability at the level of the entire architecture of your application. It will allow your application to evolve more securely and stable.</p>\n<h2>Traditional layered architecture</h2>\n<p>Traditionally a layered architecture UI depended on the business layer and this in turn depended on the data access layer.</p>\n<p><a href="https://i.stack.imgur.com/6e2K9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6e2K9.png" alt="" /></a></p>\n<p>You have to understand layer, package, or library. Let\'s see how the code would be.</p>\n<p>We would have a library or package for the data access layer.</p>\n<pre><code>// DataAccessLayer.dll\npublic class ProductDAO {\n\n}\n</code></pre>\n<p>And another library or package layer business logic that depends on the data access layer.</p>\n<pre><code>// BusinessLogicLayer.dll\nusing DataAccessLayer;\npublic class ProductBO { \n    private ProductDAO productDAO;\n}\n</code></pre>\n<h2>Layered architecture with dependency inversion</h2>\n<p>The dependency inversion indicates the following:</p>\n<blockquote>\n<p>High-level modules should not depend on low-level modules. Both should depend on abstractions.</p>\n</blockquote>\n\n<blockquote>\n<p>Abstractions should not depend on details. Details should depend on abstractions.</p>\n</blockquote>\n<p>What are the high-level modules and low level? Thinking modules such as libraries or packages, high-level module would be those that traditionally have dependencies and low level on which they depend.</p>\n<p>In other words, module high level would be where the action is invoked and low level where the action is performed.</p>\n<p>A reasonable conclusion to draw from this principle is that there should be no dependence between concretions, but there must be a dependence on an abstraction. But according to the approach we take we can be misapplying investment depend dependency, but an abstraction.</p>\n<p>Imagine that we adapt our code as follows:</p>\n<p>We would have a library or package for the data access layer which define the abstraction.</p>\n<pre><code>// DataAccessLayer.dll\npublic interface IProductDAO\npublic class ProductDAO : IProductDAO{\n\n}\n</code></pre>\n<p>And another library or package layer business logic that depends on the data access layer.</p>\n<pre><code>// BusinessLogicLayer.dll\nusing DataAccessLayer;\npublic class ProductBO { \n    private IProductDAO productDAO;\n}\n</code></pre>\n<p>Although we are depending on an abstraction dependency between business and data access remains the same.</p>\n<p><a href="https://i.stack.imgur.com/6e2K9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6e2K9.png" alt="" /></a></p>\n<p>To get dependency inversion, the persistence interface must be defined in the module or package where this high level logic or domain is and not in the low-level module.</p>\n<p>First define what the domain layer is and the abstraction of its communication is defined persistence.</p>\n<pre><code>// Domain.dll\npublic interface IProductRepository;\n\nusing DataAccessLayer;\npublic class ProductBO { \n    private IProductRepository productRepository;\n}\n</code></pre>\n<p>After the persistence layer depends on the domain, getting to invert now if a dependency is defined.</p>\n<pre><code>// Persistence.dll\npublic class ProductDAO : IProductRepository{\n\n}\n</code></pre>\n<p><a href="https://i.stack.imgur.com/c7Xln.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c7Xln.png" alt="" /></a><br />\n<sub>(source: <a href="https://xurxodev.com/content/images/2016/02/Dependency-Inversion-Layers.png" rel="nofollow noreferrer">xurxodev.com</a>)</sub></p>\n<h2>Deepening the principle</h2>\n<p>It is important to assimilate the concept well, deepening the purpose and benefits. If we stay in mechanically and learn the typical case repository, we will not be able to identify where we can apply the principle of dependence.</p>\n<p>But why do we invert a dependency? What is the main objective beyond specific examples?</p>\n<p>Such commonly <strong>allows the most stable things, that are not dependent on less stable things, to change more frequently.</strong></p>\n<p>It is easier for the persistence type to be changed, either the database or technology to access the same database than the domain logic or actions designed to communicate with persistence. Because of this, the dependence is reversed because as it is easier to change the persistence if this change occurs. In this way we will not have to change the domain. The domain layer is the most stable of all, which is why it should not depend on anything.</p>\n<p>But there is not just this repository example. There are many scenarios where this principle applies and there are architectures based on this principle.</p>\n<h2>Architectures</h2>\n<p>There are architectures where dependency inversion is key to its definition. In all the domains it is the most important and it is abstractions that will indicate the communication protocol between the domain and the rest of the packages or libraries are defined.</p>\n<h3>Clean Architecture</h3>\n<p>In <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html" rel="nofollow noreferrer">Clean architecture</a> the domain is located in the center and if you look in the direction of the arrows indicating dependency, it is clear what are the most important and stable layers. The outer layers are considered unstable tools so avoid depending on them.</p>\n<p><a href="https://i.stack.imgur.com/uNQZQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNQZQ.jpg" alt="" /></a><br />\n<sub>(source: <a href="https://8thlight.com/blog/" rel="nofollow noreferrer">8thlight.com</a>)</sub></p>\n<h3>Hexagonal Architecture</h3>\n<p>It happens the same way with the hexagonal architecture, where the domain is also located in the central part and ports are abstractions of communication from the domino outward. Here again it is evident that the domain is the most stable and traditional dependence is inverted.</p>\n<p><a href="https://i.stack.imgur.com/cDymr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cDymr.jpg" alt="" /></a><br />\n<sub>(source: <a href="https://a.pragprog.com/magazines/2009-12/images/HexagonalArchitecture__bbe7fy__.jpg" rel="nofollow noreferrer">pragprog.com</a>)</sub></p>\n'}, {'answer_id': 37283098, 'author': 'mattvonb', 'author_id': 1170736, 'author_profile': 'https://Stackoverflow.com/users/1170736', 'pm_score': 3, 'selected': False, 'text': "<p>A much clearer way to state the Dependency Inversion Principle is:</p>\n\n<p>Your modules which encapsulate complex business logic should not depend directly on other modules which encapsulate business logic. Instead, they should depend only on interfaces to simple data.</p>\n\n<p>I.e., instead of implementing your class <code>Logic</code> as people usually do:</p>\n\n<pre><code>class Dependency { ... }\nclass Logic {\n    private Dependency dep;\n    int doSomething() {\n        // Business logic using dep here\n    }\n}\n</code></pre>\n\n<p>you should do something like:</p>\n\n<pre><code>class Dependency { ... }\ninterface Data { ... }\nclass DataFromDependency implements Data {\n    private Dependency dep;\n    ...\n}\nclass Logic {\n    int doSomething(Data data) {\n        // compute something with data\n    }\n}\n</code></pre>\n\n<p><code>Data</code> and <code>DataFromDependency</code> should live in the same module as <code>Logic</code>, not with <code>Dependency</code>.</p>\n\n<p>Why do this?</p>\n\n<ol>\n<li>The two business logic modules are now decoupled. When <code>Dependency</code> changes, you don't need to change <code>Logic</code>. </li>\n<li>Understanding what <code>Logic</code> does is a much simpler task: it operates only on what looks like an ADT.</li>\n<li><code>Logic</code> can now be more easily tested. You can now directly instantiate <code>Data</code> with fake data and pass it in. No need for mocks or complex test scaffolding.</li>\n</ol>\n"}, {'answer_id': 39429473, 'author': 'nikhil.singhal', 'author_id': 6631986, 'author_profile': 'https://Stackoverflow.com/users/6631986', 'pm_score': 4, 'selected': False, 'text': '<p>When we design software applications we can consider the low level classes the classes which implement basic and primary operations (disk access, network protocols,...) and high level classes the classes which encapsulate complex logic (business flows, ...).</p>\n\n<p>The last ones rely on the low level classes. A natural way of implementing such structures would be to write low level classes and once we have them to write the complex high level classes. Since high level classes are defined in terms of others this seems the logical way to do it. But this is not a flexible design. What happens if we need to replace a low level class?</p>\n\n<p>The Dependency Inversion Principle states that:</p>\n\n<ul>\n<li>High level modules should not depend upon low level modules. Both should depend upon abstractions.</li>\n<li>Abstractions should not depend upon details. Details should depend upon abstractions.</li>\n</ul>\n\n<p>This principle seeks to "invert" the conventional notion that high level modules in software should depend upon the lower level modules. Here high level modules own the abstraction (for example, deciding the methods of the interface) which are implemented by lower level modules. Thus making lower level modules dependent on higher level modules.</p>\n'}, {'answer_id': 54944762, 'author': 'Rejwanul Reja', 'author_id': 4259851, 'author_profile': 'https://Stackoverflow.com/users/4259851', 'pm_score': -1, 'selected': False, 'text': '<p>Dependency Inversion Principle (DIP) says that </p>\n\n<p>i) High level modules should not depend upon low-level modules. Both should depend upon abstractions.</p>\n\n<p>ii) Abstractions should never depend upon details. Details should depend upon abstractions.</p>\n\n<p>Example: </p>\n\n<pre><code>    public interface ICustomer\n    {\n        string GetCustomerNameById(int id);\n    }\n\n    public class Customer : ICustomer\n    {\n        //ctor\n        public Customer(){}\n\n        public string GetCustomerNameById(int id)\n        {\n            return "Dummy Customer Name";\n        }\n    }\n\n    public class CustomerFactory\n    {\n        public static ICustomer GetCustomerData()\n        {\n            return new Customer();\n        }\n    }\n\n    public class CustomerBLL\n    {\n        ICustomer _customer;\n        public CustomerBLL()\n        {\n            _customer = CustomerFactory.GetCustomerData();\n        }\n\n        public string GetCustomerNameById(int id)\n        {\n            return _customer.GetCustomerNameById(id);\n        }\n    }\n\n    public class Program\n    {\n        static void Main()\n        {\n            CustomerBLL customerBLL = new CustomerBLL();\n            int customerId = 25;\n            string customerName = customerBLL.GetCustomerNameById(customerId);\n\n\n            Console.WriteLine(customerName);\n            Console.ReadKey();\n        }\n    }\n</code></pre>\n\n<p>Note: Class should depend on abstractions like interface or abstract classes, not specific details (implementation of interface).</p>\n'}, {'answer_id': 55666719, 'author': 'Daniel Andres Pelaez Lopez', 'author_id': 6371836, 'author_profile': 'https://Stackoverflow.com/users/6371836', 'pm_score': -1, 'selected': False, 'text': '<p>Dependency inversion: Depend on abstractions, not on concretions.</p>\n\n<p>Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.</p>\n\n<p><img src="https://i.stack.imgur.com/qU57n.png" alt="DIP and IoC"></p>\n\n<p>These are some good posts talking about this:</p>\n\n<p><a href="https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/" rel="nofollow noreferrer">https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/</a></p>\n\n<p><a href="https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/" rel="nofollow noreferrer">https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/</a></p>\n\n<p><a href="https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/" rel="nofollow noreferrer">https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/</a></p>\n'}, {'answer_id': 56630214, 'author': 'John Silence', 'author_id': 1812300, 'author_profile': 'https://Stackoverflow.com/users/1812300', 'pm_score': -1, 'selected': False, 'text': '<p>Adding to the flurry of generally good answers, I\'d like to add a tiny sample of my own to demonstrate good vs. bad practice. And yes, I\'m not one to throw stones!</p>\n\n<p>Say, you want a little program to <strong>convert a string into base64 format</strong> via console I/O. Here\'s the naive approach:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        /*\n         * BadEncoder: High-level class *contains* low-level I/O functionality.\n         * Hence, you\'ll have to fiddle with BadEncoder whenever you want to change\n         * the I/O mode or details. Not good. A good encoder should be I/O-agnostic --\n         * problems with I/O shouldn\'t break the encoder!\n         */\n        BadEncoder.Run();            \n    }\n}\n\npublic static class BadEncoder\n{\n    public static void Run()\n    {\n        Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(Console.ReadLine())));\n    }\n}    \n</code></pre>\n\n<p>The DIP basically says that high-level components shouldn\'t be dependent on low-level implementation, where "level" is the distance from I/O according to Robert C. Martin ("Clean Architecture"). But how do you get out of this predicament? Simply by making the central Encoder dependent only on interfaces without bothering how those are implemented:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {           \n        /* Demo of the Dependency Inversion Principle (= "High-level functionality\n         * should not depend upon low-level implementations"): \n         * You can easily implement new I/O methods like\n         * ConsoleReader, ConsoleWriter without ever touching the high-level\n         * Encoder class!!!\n         */            \n        GoodEncoder.Run(new ConsoleReader(), new ConsoleWriter());        }\n}\n\npublic static class GoodEncoder\n{\n    public static void Run(IReadable input, IWriteable output)\n    {\n        output.WriteOutput(Convert.ToBase64String(Encoding.ASCII.GetBytes(input.ReadInput())));\n    }\n}\n\npublic interface IReadable\n{\n    string ReadInput();\n}\n\npublic interface IWriteable\n{\n    void WriteOutput(string txt);\n}\n\npublic class ConsoleReader : IReadable\n{\n    public string ReadInput()\n    {\n        return Console.ReadLine();\n    }\n}\n\npublic class ConsoleWriter : IWriteable\n{\n    public void WriteOutput(string txt)\n    {\n        Console.WriteLine(txt);\n    }\n}\n</code></pre>\n\n<p>Note that you don\'t need to touch <code>GoodEncoder</code> in order to change the I/O mode &mdash; that class is happy with the I/O interfaces it knows; any low-level implementation of <code>IReadable</code> and <code>IWriteable</code> won\'t ever bother it.</p>\n'}, {'answer_id': 59756845, 'author': 'mike', 'author_id': 697551, 'author_profile': 'https://Stackoverflow.com/users/697551', 'pm_score': 1, 'selected': False, 'text': '<p>If we can take it as a given that a "high level" employee at a corporation is paid for the execution of their plans, and that these plans are delivered by the aggregate execution of many "low level" employee\'s plans, then we could say it is generally a terrible plan if the high level employee\'s plan description in any way is coupled to the specific plan of any lower level employee.</p>\n\n<p>If a high level executive has a plan to "improve delivery time", and indicates that an employee in the shipping line must have coffee and do stretches each morning, then that plan is highly coupled and has low cohesion. But if the plan makes no mention of any specific employee, and in fact simply requires "an entity that can perform work is prepared to work", then the plan is loosely coupled and more cohesive: the plans do not overlap and can easily be substituted. Contractors, or robots, can easily replace the employees and the high level\'s plan remains unchanged.</p>\n\n<p>"High level" in the dependency inversion principle means "more important".</p>\n'}, {'answer_id': 61267123, 'author': 'Sumanth Varada', 'author_id': 4044987, 'author_profile': 'https://Stackoverflow.com/users/4044987', 'pm_score': -1, 'selected': False, 'text': "<p>I can see good explanation has been given in above answers. However i wants to provide some easy explanation with simple example.</p>\n\n<p><strong><em>Dependency Inversion Principle allows the programmer to remove the hardcoded dependencies so that the application becomes loosely coupled and extendable.</em></strong></p>\n\n<p><strong>How to achieve this :</strong> through abstraction</p>\n\n<p><strong>Without dependency inversion:</strong></p>\n\n<pre><code> class Student {\n    private Address address;\n\n    public Student() {\n        this.address = new Address();\n    }\n}\nclass Address{\n    private String perminentAddress;\n    private String currentAdrress;\n\n    public Address() {\n    }\n} \n</code></pre>\n\n<p><strong><em>In above code snippet, address object is hard-coded. Instead if we can use dependency inversion and inject the address object by passing through constructor or setter method. Let's see.</em></strong></p>\n\n<p><strong>With dependency inversion:</strong></p>\n\n<pre><code>class Student{\n    private Address address;\n\n    public Student(Address address) {\n        this.address = address;\n    }\n    //or\n    public void setAddress(Address address) {\n        this.address = address;\n    }\n}\n</code></pre>\n"}, {'answer_id': 66808672, 'author': 'yoAlex5', 'author_id': 4770877, 'author_profile': 'https://Stackoverflow.com/users/4770877', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Dependency Inversion Principle(DIP)</strong></p>\n<p>It is a part of SOLID<a href="https://stackoverflow.com/a/66087638/4770877"><sup>[About]</sup></a> which is a part of OOD and was introduced by Uncle Bob. It is about <strong>loose coupling</strong> between classes(layers...). Class should not be depended on <strong>concrete</strong> realization, class should be depended on <strong>abstraction/interface</strong></p>\n<p>Problem:</p>\n<pre><code>//A -&gt; B\nclass A {\n  B b\n\n  func foo() {\n     b = B();\n  }\n}\n</code></pre>\n<p>Solution:</p>\n<pre><code>//A -&gt; IB &lt;|- B\n//client[A -&gt; IB] &lt;|- B is the Inversion \nclass A {\n  IB ib // An abstraction between High level module A and low level module B\n\n  func foo() {\n     ib = B()\n  }\n}\n</code></pre>\n<p>Now <code>A</code> is not depended on <code>B</code>(one to one), now <code>A</code> is depended on interface <code>IB</code> which is implemented by <code>B</code>, it means that A depends on multiple realization of <code>IB</code>(one to many)</p>\n<p><a href="https://stackoverflow.com/a/67401178/4770877">[DIP vs DI vs IoC]</a></p>\n'}]
['https://Stackoverflow.com/questions/62539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3012/']