Use Factory | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1941302-intermediate-ios-design-patterns/lessons/5

Thanks for the tutorial.

I have a question.

Would it be better choice to create the factory method as a static method on the factory class?
That way it does not have to be created as a property at all the callsites.

Are there downsides to that approach? or is it just preference?

Inside viewDidLoad() method of ViewController class, you have used this code.
DispatchQueue.main.async { [weak self] in
self?.locationManager.requestWhenInUseAuthorization()
}

Inside viewDidLoad(), we are already in main thread, so why we have again used DispatchQueue.main?

You can choose to do this, yet there’s pros and cons:

Pros

  1. You don’t need to inject the factory anywhere. Instead, just call the static method.

Cons

  1. It’s not obvious the consumer is using the factory
  2. It’s hard to unit test a static method that’s called directly on the type. Conversely, you can easily test a factory instance method by swapping out the factory with either a protocol or a subclass.

In production apps, you usually need unit tests. Hence, the cons of the static-method approach (harder testability) greatly outweigh the pros (not having to inject a factory).

If you’re new to unit testing, check out other video courses or books on RW to find out more about it, and why it’s so important and helpful ! :]

Well, that’s honestly a small hack… :sweat_smile:

Basically, there was a bug in an older version of iOS wherein you needed to wait to call locationManager.requestWhenInUseAuthorization() until the view was shown. If you didn’t, then the request wouldn’t actually be made (…awkward)…

In this simple demo app, this was an easy way to work around this issue. This dispatch essentially pushed the call until later on in the view controller lifecycle (after viewDidLoad was completely done).

I think Apple may have solved this issue in later versions of iOS. You can try removing the dispatch and seeing if it still works.

If/when this video series gets an update, we’ll make sure this is re-visited and updated appropriately! :smiley:

Thanks @jrg.developer for the reply. Much appreciated