What is the dependency inversion principle and why is it important?

前端 未结 15 953
别那么骄傲
别那么骄傲 2020-11-28 00:06

What is the dependency inversion principle and why is it important?

15条回答
  •  有刺的猬
    2020-11-28 00:57

    I can see good explanation has been given in above answers. However i wants to provide some easy explanation with simple example.

    Dependency Inversion Principle allows the programmer to remove the hardcoded dependencies so that the application becomes loosely coupled and extendable.

    How to achieve this : through abstraction

    Without dependency inversion:

     class Student {
        private Address address;
    
        public Student() {
            this.address = new Address();
        }
    }
    class Address{
        private String perminentAddress;
        private String currentAdrress;
    
        public Address() {
        }
    } 
    

    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.

    With dependency inversion:

    class Student{
        private Address address;
    
        public Student(Address address) {
            this.address = address;
        }
        //or
        public void setAddress(Address address) {
            this.address = address;
        }
    }
    

提交回复
热议问题