From encapsulation to protocol extensions

Sorin
Swift sections
Published in
3 min readDec 5, 2018

--

Let’s say we want to define a simple service class in Swift that just prints some output if some input is positive. (Wow: requirements span less than 2 rows!)

Object encapsulation

Easy said — easy done? Yes, if we don’t care about the client side extensibility:

With this approach, the client class can simply instantiate the service and delegate doSomething work to it. Very simple (that’s good), yet very annoying that the client cannot intervene with input data and output actions to be executed while the work is being performed by the service instance itself.

Inheritance — nice try!

No, inheritance is not always our enemy. It does have (two?) valid use cases. But imho it’s not our best friend here (even that the code is indeed shorter!):

--

--

Sorin
Swift sections

Software Developer • Rust, Swift, WPF, Web • MacBook enthusiast • fashion design • EDM • absurdism • writing from Cluj