Slide 1

Slide 1 text

DEPENDENCY INJECTION (DI) IN SWIFT ILYA PUCHKA (@ILYAPUCHKA) IOS DEVELOPER @HELLOFRESH

Slide 2

Slide 2 text

FUNCTIONAL OR OBJECT ORIENTED?

Slide 3

Slide 3 text

SOLID KISS DRY YAGNI RAP CQS DECORATOR FACADE ABSTRACT FACTORY STRATEGY ...

Slide 4

Slide 4 text

DI SOLID

Slide 5

Slide 5 text

WHAT IS DEPENDENCY INJECTION?

Slide 6

Slide 6 text

In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. — Wikipedia

Slide 7

Slide 7 text

“Dependency injection is really just passing in an instance variable. — James Shore

Slide 8

Slide 8 text

VOODO MAGIC SLOW FRAMEWORKS ONLY FOR TESTING OVERENGINEERING

Slide 9

Slide 9 text

> What is Dependency Injection? > How to do it? > How not to do it?

Slide 10

Slide 10 text

WHY DEPENDENCY INJECTION?

Slide 11

Slide 11 text

ABSTRACTIONS EVERYWHERE

Slide 12

Slide 12 text

LOOSE COUPLING

Slide 13

Slide 13 text

TEST EXTEND AND REUSE DEVELOP IN PARALLER MAINTAIN

Slide 14

Slide 14 text

NOT JUST UNIT TESTS BUT LOOSE COUPLING

Slide 15

Slide 15 text

FIRST STEP - PASSING INSTANCE VARIABLES

Slide 16

Slide 16 text

SECOND STEP - ? THIRD STEP - ?

Slide 17

Slide 17 text

PATTERNS CUSTRUCTOR INJECTION PROPERTY INJECTION METHOD INJECTION AMBIENT CONTEXT

Slide 18

Slide 18 text

CONSTRUCTOR INJECTION class NSPersistentStore : NSObject { init(persistentStoreCoordinator root: NSPersistentStoreCoordinator?, configurationName name: String?, URL url: NSURL, options: [NSObject: AnyObject]?) var persistentStoreCoordinator: NSPersistentStoreCoordinator? { get } }

Slide 19

Slide 19 text

EASY TO IMPLEMENT IMMUTABILITY

Slide 20

Slide 20 text

PROPERTY INJECTION extension UIViewController { weak public var transitioningDelegate: UIViewControllerTransitioningDelegate? }

Slide 21

Slide 21 text

LOCAL DEFAULT FOREIGN DEFAULT

Slide 22

Slide 22 text

OPTIONALS NOT IMMUTABLE THREAD SAFETY

Slide 23

Slide 23 text

METHOD INJECTION public protocol NSCoding { public func encodeWithCoder(aCoder: NSCoder) }

Slide 24

Slide 24 text

AMBIENT CONTEXT public class NSURLCache : NSObject { public class func setSharedURLCache(cache: NSURLCache) public class func sharedURLCache() -> NSURLCache }

Slide 25

Slide 25 text

CROSS-CUTTING CONCERNS > logging > analitycs > time/date > etc.

Slide 26

Slide 26 text

PROS: > does not pollute API > dependency always available CONS: > implicit dependency > global mutable state

Slide 27

Slide 27 text

SEPARATION OF CONCERNS > what concrete implementations to use > configure dependencies > manage dependencies' lifetime

Slide 28

Slide 28 text

WHERE DEPENDENCIES ARE CREATED?

Slide 29

Slide 29 text

COMPOSITION ROOT

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

VIPER EXAMPLE class AppDependencies { init() { configureDependencies() } func configureDependencies() { // Root Level Classes let coreDataStore = CoreDataStore() let clock = DeviceClock() let rootWireframe = RootWireframe() // List Module Classes let listPresenter = ListPresenter() let listDataManager = ListDataManager() let listInteractor = ListInteractor(dataManager: listDataManager, clock: clock) ... listInteractor.output = listPresenter listPresenter.listInteractor = listInteractor listPresenter.listWireframe = listWireframe listWireframe.addWireframe = addWireframe ... } }

Slide 32

Slide 32 text

VIPER EXAMPLE @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let appDependencies = AppDependencies() func application( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { appDependencies.installRootViewControllerIntoWindow(window!) return true } }

Slide 33

Slide 33 text

The biggest challange of properly implementing DI is getting all classes with dependencies moved to Composition Root — Mark Seeman

Slide 34

Slide 34 text

ANTI- PATTERNS

Slide 35

Slide 35 text

CONTROL FREAK class RecipesService { let repository: RecipesRepository init() { self.repository = CoreDataRecipesRepository() } }

Slide 36

Slide 36 text

init()

Slide 37

Slide 37 text

STABLE OR VOLATILE

Slide 38

Slide 38 text

VOLATILE DEPENDENCIES > dependency requires environment configuration (data base, networking, file system) > nondetermenistic behavior (dates, cryptography) > expected to be replaced > dependency is still in development

Slide 39

Slide 39 text

VOLATILE DEPENDENCIES DISABLE LOOSE COUPLING

Slide 40

Slide 40 text

BASTARD INJECTION class RecipesService { let repository: RecipesRepository init(repository: RecipesRepository = CoreDataRecipesRepository()) { self.repository = repository } }

Slide 41

Slide 41 text

FOREIGN DEFAULT

Slide 42

Slide 42 text

SERVICE LOCATOR let locator = ServiceLocator.sharedInstance locator.register( { CoreDataRecipesRepository() }, forType: RecipesRepository.self) class RecipesService { let repository: RecipesRepository init() { let locator = ServiceLocator.sharedInstance self.repository = locator.resolve(RecipesRepository.self) } }

Slide 43

Slide 43 text

Pros: > Extensibility > Testability > Parallel development > Separation of concerns

Slide 44

Slide 44 text

Cons: > Implicit dependencies > Hidden complexity > Tight coupling > Not reusable > Less maintainable

Slide 45

Slide 45 text

> DI enables loose coupling > 4 patterns, prefer constructor injection > Use local defaults, not foreign > Inject volatile dependencies, not stable > Avoid anti-patterns

Slide 46

Slide 46 text

EXPLICIT DEPENDENCIES COMPOSITION ROOT

Slide 47

Slide 47 text

SECOND STEP - ABSTRACTIONS

Slide 48

Slide 48 text

DEPENDENCY INVERSION PRINCIPLE (DIP)

Slide 49

Slide 49 text

!

Slide 50

Slide 50 text

!

Slide 51

Slide 51 text

DI = DI PATTERNS + DIP

Slide 52

Slide 52 text

Program to an interface, not an implementation — Design Patterns: Elements of Reusable Object-Oriented Software

Slide 53

Slide 53 text

PROGRAM TO AN INTERFACE ABSTRACTION

Slide 54

Slide 54 text

INTERFACES ARE NOT ABSTRACTIONS 1 1 http://blog.ploeh.dk/2010/12/02/Interfacesarenotabstractions/

Slide 55

Slide 55 text

DI = DI PATTERNS + DIP

Slide 56

Slide 56 text

THIRD STEP - INVERSION OF CONTROL

Slide 57

Slide 57 text

DI CONTAINERS

Slide 58

Slide 58 text

TYPHOON DIP

Slide 59

Slide 59 text

TYPHOON http://typhoonframework.org > a lot of features > good docs > well maintained > continuously improved

Slide 60

Slide 60 text

public class APIClientAssembly: TyphoonAssembly { public dynamic func apiClient() -> AnyObject { ... } public dynamic func session() -> AnyObject { ... } public dynamic func logger() -> AnyObject { ... } }

Slide 61

Slide 61 text

public dynamic func apiClient() -> AnyObject { return TyphoonDefinition.withClass(APIClientImp.self) { definition in definition.useInitializer(#selector(APIClientImp.init(session:))) { initializer in initializer.injectParameterWith(self.session()) } definition.injectProperty("logger", with: self.logger()) } }

Slide 62

Slide 62 text

public dynamic func session() -> AnyObject { return TyphoonDefinition.withClass(NSURLSession.self) { definition in definition.useInitializer(#selector(NSURLSession.sharedSession)) } } public dynamic func logger() -> AnyObject { return TyphoonDefinition.withClass(ConsoleLogger.self) { definition in definition.scope = .Singleton } }

Slide 63

Slide 63 text

let assembly = APIClientAssembly().activate() let apiClient = assembly.apiClient() as! APIClient

Slide 64

Slide 64 text

TYPHOON + SWIFT ! > Requires to subclass NSObject and define protocols with @objc > Methods called during injection should be dynamic > requires type casting > not all features work in Swift > too wordy API for Swift

Slide 65

Slide 65 text

DIP https://github.com/AliSoftware/Dip > pure Swift api > cross-platform > type-safe > small code base

Slide 66

Slide 66 text

REGISTER let container = DependencyContainer() container.register { try APIClientImp( session: container.resolve() ) as APIClient } .resolveDependencies { container, client in client.logger = try container.resolve() } container.register { NSURLSession.sharedSession() as NetworkSession } container.register(.Singleton) { ConsoleLogger() as Logger }

Slide 67

Slide 67 text

RESOLVE let apiClient = try! container.resolve() as APIClient

Slide 68

Slide 68 text

AUTO-WIRING class APIClientImp: APIClient { private let _logger = Injected() var logger: Logger? { return _logger.value } }

Slide 69

Slide 69 text

AUTO-WIRING class APIClientImp: APIClient { init(session: NetworkSession) { ... } } container.register { APIClientImp(session: $0) as APIClient }

Slide 70

Slide 70 text

Typhoon Dip Constructor, property, method injection ✔ ✔ Lifecycle management ✔ ✔ Circular dependencies ✔ ✔ Runtime arguments ✔ ✔ Named definitions ✔ ✔ Storyboards integration ✔ ✔ ----------------------------------------------------------- Auto-wiring ✔ ✔ Thread safety ✘ ✔ Interception ✔ ✘ Infrastructure ✔ ✘

Slide 71

Slide 71 text

WHY SHOULD I BOTHER? > easy integration with storyboards > manage components lifecycle > can simplify configurations > allow interception (in Typhoon using NSProxy) > provides additional features

Slide 72

Slide 72 text

DI ≠ DI CONTAINER

Slide 73

Slide 73 text

DEPENDENCY INJECTION IS A MEANS TO AN END

Slide 74

Slide 74 text

LINKS > "Dependency Injection in .Net" Mark Seeman > Mark Seeman's blog > objc.io Issue 15: Testing. Dependency Injection, by Jon Reid > "DIP in the wild" > Non-DI code == spaghetti code?

Slide 75

Slide 75 text

THANK YOU! @ILYAPUCHKA HTTP://ILYA.PUCHKA.ME