I have been trying to grasp protocol-oriented-programming but i don't understand the difference between the 2 following scenarios...
Scenario 1
I have two classes that are UIViewControllers
. Both of these classes need to use some common functionality so I create a protocol and an extension with a default implementation of the protocol and then the view controllers only need have the protocol in the class line and they will automatically inherit the needed functionality. ie...
protocol SomeProtocol {
func foo()
}
extension SomeProtocol {
func foo(){
//execute
}
}
class FirstViewController: UIViewController, SomeProtocol {
...
func doSomething(){
foo()
}
}
class SecondViewController: UIViewController, SomeProtocol {
...
func doSomethingElse(){
foo()
}
}
Scenario 2
I have two classes that are UIViewControllers
. Both of these classes need to use some common functionality so I create a controller class and both UIViewController
classes use an instance of the controller class. ie...
class FirstViewController: UIViewController {
...
let controller = Controller()
func doSomething(){
controller.foo()
}
}
class SecondViewController: UIViewController {
...
let controller = Controller()
func doSomethingElse(){
controller.foo()
}
}
class Controller {
func foo(){
//execute...
}
}`
So what is the difference? Anywhere that I need to use the foo()
function I could just grab an instance of Controller()
. What advantage do I get by putting the foo()
function in a protocol and then having the classes that need foo()
inherit from the protocol?