$30 off During Our Annual Pro Sale. View Details »

Dependency Injection in iOS Apps

Dependency Injection in iOS Apps

yashigani

April 26, 2016
Tweet

More Decks by yashigani

Other Decks in Programming

Transcript

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

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

  3. 8IBUJT %FQFOEFODZ*OKFDUJPO

  4. • Depend interface, not depend implementations • Make less dependency

    between components • Improve testability • Make easy to mock dependency objects
  5. )PXUPJOKFDU EFQFOEFODZPCKFDUT

  6. // Constructor injection class ViewController: UIViewController { let client: APIClient

    init(client: APIClient) { self.client = APIClient } }
  7. • Pros • Easy to control • Cons • Don’t

    fit storyboard • Need dependency objects to create
  8. // Property injection override func prepareForSegue() { if let vc

    = segue.dVC as? NextViewController { vc.client = client } }
  9. • 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
  10. // 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() }
  11. None
  12. 6TJOH %FQFOEFODZJOKFDUJPO

  13. View Controller Context

  14. View Controller ViewController: WithContext WithContext Context ContextType

  15. // 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() }
  16. protocol WithContext { var context: ContextType { get } }

    extension WithContext { var context: ContextType { return Context.get() } } class ViewController: UIViewController, WithContext {}
  17. • 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
  18. 3FDBQ

  19. • 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 ✨
  20. 5IBOLZPV