Object Oriented Programming
in Swift
Ch 2: Polymorphism
Sai Li @ Yowoo Tech.
2016/12/23
References
• Agile Software Development: Principles, Patterns,
and Practice ( : )

by Robert C. Martin
• Fundamental Object Oriented Programming 

by Hsuan-Tien Lin
• 

by Teddy Chen
• Essential Object-Oriented Programming

by Josh Ko
OOP
• Encapsulation
• Inheritance
• Polymorphism
Polymorphism
One Thing,
Many shapes….
Strawberry
Strawberry
Polymorphism in Swift
1. Class Inheritance
2. Protocol Interface
Fruit
Orange Strawberry
Playable
CD Piano
Polymorphism
Polymorphism means that the sender of a
stimulus does not need to know the receiving
instance’s class. The receiving instance can
belong to an arbitrary class.
S.O.L.I.D
S.O.L.I.D
• SRP: Single Responsibility Principle
• OCP: Open Closed Principle
• LSP: Liskov Substitution Principle
• ISP: Interface Segregation Principle
• DIP: Dependency Inversion Principle
Open Closed Principle
– Ivar Jacobson
“All systems change during their life cycles.
This must be born in mind when devloping
systems expected to last longer than the first
version.”
Open Closed Principle
Software entities (classes, modules, functions,
etc.) should be open for extension, but closed
for modification
- Bertrand Meyer (1988)
• Open for extension
• Closed for modification
Triangle?
• No ripple effect
• further changes of that kind are achieved by
adding new code, not by changing old code
that already works.
• Elastic
<Design Pattern > GoF
“Program to an interface,
not an implementation.”
What you can do rather than who you are.
Black Cat & White Cat
How ?
Barbara Liskov

(1939 - )
• UCB, Stanford
• 1st female CS PhD
• CLU
• von Neumann Award
• Turing Award
Liskov Substitution Principle
Let Φ(x) be a property provable about objects x
of type T.
Then Φ(y) should be true for objects y of type S
where S is a subtype of T
Liskov Substitution Principle
Subtypes must be substitutable for their base
types.
Liskov Substitution Principle
Subtypes must be substitutable for their base
types.
Let Φ(x) be a property provable about objects x of type T.
Then Φ(y) should be true for objects y of type S where S
is a subtype of T
( )
LSP Violation
p.s: Circle Ellipse Problem
LSP Violation
LSP Violation
Why?
Design By Contract
Class Invariant
Postcondition
Subtype func precondition can’t be stronger than base type

Subtype func postcondition can't be weaker than base type
Recap
• Polymorphism
• Open Closed Principle
• Liskov Substitution Principle
To be continued …
References
• https://zh.wikipedia.org/wiki/
File:Barbara_Liskov.PNG
• http://www.relatably.com/m/img/wtf-memes/
grandma-finds-the-internet-meme-generator-wtf-
b12499.jpg
• http://i.imgur.com/BTpuqPX.jpg
• wiki: https://en.wikipedia.org/wiki/Circle-
ellipse_problem

Object Oriented Programming in Swift Ch2 Polymorphism, OCP, LSP