Hi,
I’m resuming this book with intentions of learning communication with web services. I liked the way you’ve implemented the architecture and explained roles of classes. One thing that I find awkward is why do we have to inject property dependency in AppDelegate.swift
. We’re doing multiple force unwrapping to just set store
property to new instance of PhotoStore
. Why we didn’t just do it in PhotosViewController
like:
let store = PhotoStore()
Please explain. Thanks.
Basically what’s going on here is the application of the “Dependency Injection” principle.
Google it and you’ll find all levels of explanations.
Short answer:
You want decouple PhotosViewController from that specific implementation of PhotoStore.
If you init the store property directly inside of PhotosViewController, your app is gonna work just fine and everyone is very happy with that.
So far so good.
BUT… what if you or your boss or whatever (even the team that develops the actual PhotoStore) decide to change something?
Isn’t it much easier if PhotosViewController didn’t know anything about PhotoStore and the other way around ?
Thanks for sharing your explanation of dependency injection and giving a short and sweet reason as to the importance.
It is a rule of a thumb to use singleton pattern implementing sockets stores DB etc in order to fetch the data from one and the same spot otherwise app’s behavior is unpredictable or buggy.
When you create a PhotoStore instance in the AppDelegate you’ve got one and only one store during app running. Doing the same job in the PhotosViewController may end up in several stores during the app’s life as its transitions to and from background may destroy and create the view controller.
In a multiple view application, keeping a data store in a view controller is a serious bug as other parts of such app are not able to reach that store if that controller is not active. In this case extension of “Photorama” to have multiple views will be painful.
PhotosViewController, as well as other classes, are already decoupled from the implementation of PhotoStore. The main question is where to create an instance of the PhotoStore and keep the reference to it.
hey gio, I want to ask. what if we have a tab bar that’s more than one screen since the book only explain one screen using dependency inversion, how can I solve if there more? thank you