4

I am using Swift and am wondering about the concepts of Extension and Delegation. Recently I found a case where either one of these two concepts could be applied. This reminded of the "composition over inheritance" principle, which teaches that a "has-a" relationship may be preferred to a "is-a" relationship.

I encountered a case where it is always an object of some specific type that depends on an object conforming a certain protocol, therefore allowing both Extension and Delegation to be used.

For instance, I have a UIViewController that depends on a subclass of UIView. Say we take the following protocol:

protocol ViewInteraction {
  func interact()
}

This protocol will be conformed by the UIView subclass, say InteractedView. And any UIViewController may need to interact with this InteractedView.

In these types of situations, what's a good default - the Delegation pattern, or the Extension pattern? That is, should I use the Delegation pattern - letting the InteractedView conform it, and letting the UIViewController subclass manipulate a ViewInteraction property - or should I follow the Extension pattern and extend UIViewController to conform the ViewInteraction protocol (and call the InteractedView)?

Vince
  • 141

1 Answers1

2

If each view controller needs to interact with a different ViewInteraction, then delegation is the obvious choice. If all view controllers need to interact with the same (global) ViewInteraction, or if the ViewInteraction is passed in as a parameter of a particular method and only used there, then extension might be better.

Some things to keep in mind. Extension methods are essentially the same as writing free functions. For example see the following:

class A {
}

extension A {
    func b() { print(self) }
}

func c(a: A) { print(a) }

The only difference between calling myA.b() and c(myA) is the syntax. Don't get me wrong, I'm not trying to belittle extensions. This syntax change can be a huge deal, especially if you are chaining methods. ( a.b().c(d) is far easier to read than c(b(a), d))

Keeping this in mind will hopefully help you in making your decision.

Daniel T.
  • 3,053