From encapsulation to protocol extensions
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!):