This workshop will be retired on May 31, 2020.
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
What is Dependency Injection?2:52 with Amit Bijlani
Learn about the concept of dependency injection by way of an analogy.
[MUSIC] 0:00 Hi, my name is Amit an iOS developer and teacher. 0:04 Today we're going to talk about a design pattern known as Dependency Injection. 0:08 Now according to Wikipedia Dependency Injection is a design principle in 0:13 which code creating a new object 0:17 supplies the other objects that the new object depends on for operation. 0:20 A dependency is an object that can be used. 0:25 Namely a service and injection is the passing of a dependency 0:29 to a dependent object, a client that would use it. 0:34 In actuality, Dependency Injection is a fancy term for a very simple concept. 0:40 You've probably been using Dependency Injection all the while and 0:46 you didn't even know it. 0:50 If you've ever used a storyboard or 0:52 a zip in your iOS app, then you've probably created IB outlets. 0:54 And IB outlet is a property related to a view. 0:59 These are injected into the view controller when it is instantiated, 1:03 which is essentially a form of Dependency Injection. 1:07 You see, when programming an IRiS app, you are describing your software problem 1:12 in terms of objects and how they relate to each other. 1:16 There are times when one object is dependent on another object 1:19 to achieve its functionality. 1:23 For example, a table view controller is dependent on a data source for 1:26 its contents. 1:31 You can either create an instance of this dependency or inject it. 1:33 Injecting a dependency decouples it for testing and future proofing. 1:37 Let's see an analogy. 1:43 Let's take a Music Box. 1:45 The tune that a music box can play is in 1:47 coded in the pattern of the notches on the drum. 1:50 Now if you want to play a different tune, then unfortunately you have to 1:54 take the whole device apart, replace the drum and put it back together. 1:58 Conversely, a record player has all the mechanism to play music except the music 2:02 itself. 2:07 You have to supply the LP and provide a source for output, 2:08 probably a set of speakers. 2:12 These dependencies are injected and without it the record player is useless. 2:15 The music box is self-contained, it contains the music and 2:20 the output of the music. 2:24 However, this is also its biggest disadvantage because the music cannot be 2:26 easily replaced nor can the output of the music changed based on the venue. 2:30 Now the moral of the story is that decoupling dependencies 2:35 make them interchangeable. 2:39 And in the case of programming easily testable, In the next video, we'll take 2:40 a look at an example of a class that can be refactored for dependency injection. 2:46
You need to sign up for Treehouse in order to download course files.Sign up