Slide 1

Slide 1 text

%FQFOEFODZ*OKFDUJPO
 JOJ04"QQT @yashigani ؔϞό #13

Slide 2

Slide 2 text

yashigani @yashigani http://yashigani.hatenablog.com

Slide 3

Slide 3 text

8IBUJT %FQFOEFODZ*OKFDUJPO

Slide 4

Slide 4 text

• Depend interface, not depend implementations • Make less dependency between components • Improve testability • Make easy to mock dependency objects

Slide 5

Slide 5 text

)PXUPJOKFDU EFQFOEFODZPCKFDUT

Slide 6

Slide 6 text

// Constructor injection class ViewController: UIViewController { let client: APIClient init(client: APIClient) { self.client = APIClient } }

Slide 7

Slide 7 text

• Pros • Easy to control • Cons • Don’t fit storyboard • Need dependency objects to create

Slide 8

Slide 8 text

// Property injection override func prepareForSegue() { if let vc = segue.dVC as? NextViewController { vc.client = client } }

Slide 9

Slide 9 text

• Pros • Don’t need to dependency objects to create • Fit view controller with storyboard • Cons • Too difficult to stay simple • Overtime pass to dependency objects

Slide 10

Slide 10 text

// Hold all dependency objects in app class Context { // Singleton!!! private static let context = Context() static func get() -> Context { return context } let client = APIClient() } class ViewController: UIViewController { // Depend to singleton pattern let context = Context.get() }

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

6TJOH %FQFOEFODZJOKFDUJPO

Slide 13

Slide 13 text

View Controller Context

Slide 14

Slide 14 text

View Controller ViewController: WithContext WithContext Context ContextType

Slide 15

Slide 15 text

// protocol for Context protocol ContextType { var client: APIClientType { get } } class Context: ContextType { private static let context = Context() static func get() -> Context { return context } let client: APIClientType = APIClient() }

Slide 16

Slide 16 text

protocol WithContext { var context: ContextType { get } } extension WithContext { var context: ContextType { return Context.get() } } class ViewController: UIViewController, WithContext {}

Slide 17

Slide 17 text

• Default behavior, WithContext return static Context object • In unit test, add extension ViewController.context • Change context object to mock • Easy to mock context because it depend to ContextType • Solve strong dependency to singleton pattern

Slide 18

Slide 18 text

3FDBQ

Slide 19

Slide 19 text

• Don’t depend to implementations, depend to protocols • DI makes easy and flexible to inject dependency objects • Depending protocols makes easy to change implementations • Fit View Controller with storyboard very much ✨

Slide 20

Slide 20 text

5IBOLZPV