You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Liskov substitution principle named after Barbara Liskov states that one should always be able to substitute a base type for a subtype. LSP is a way of ensuring that inheritance is used correctly. If a module is using a base class, then the reference to the base class can be replaced with a derived class without affecting the functionality of the module.
501
+
502
+
Usage:
503
+
504
+
Let us understand LSP’s usage with a simple example.
505
+
506
+
```
507
+
import UIKit
508
+
import Foundation
509
+
510
+
protocol Cricketer {
511
+
func canBat()
512
+
func canBowl()
513
+
func canField()
514
+
}
515
+
```
516
+
517
+
We define a protocol called Cricketer which implements three methods of canBat, canBowl, canField.
518
+
519
+
```
520
+
class AllRounder : Cricketer{
521
+
func canBat() {
522
+
print("I can bat")
523
+
}
524
+
525
+
func canBowl() {
526
+
print("I can bowl")
527
+
}
528
+
529
+
func canField() {
530
+
print("I can field")
531
+
}
532
+
}
533
+
```
534
+
We then define a class called AllRounder conforming to Cricketer protocol. An all-rounder in cricket is someone who can bat, bowl and field.
535
+
536
+
```
537
+
class Batsman : Cricketer{
538
+
func canBat() {
539
+
print("I can bat")
540
+
}
541
+
542
+
func canBowl() {
543
+
print("I cannot bowl")
544
+
}
545
+
546
+
func canField() {
547
+
print("I can field")
548
+
}
549
+
}
550
+
551
+
```
552
+
553
+
We then define a class called Batsman conforming to Cricketer protocol. This is violation of LSP as a batsman is a cricketer but cannot use Cricketer protocol because he cannot bowl. Let us now see how we can use LSP in this scenario:
554
+
555
+
```
556
+
protocol Cricketer {
557
+
func canBat()
558
+
func canField()
559
+
}
560
+
561
+
class Batsman : Cricketer{
562
+
func canBat() {
563
+
print("I can bat")
564
+
}
565
+
566
+
func canField() {
567
+
print("I can field")
568
+
}
569
+
}
570
+
```
571
+
We change the Cricketer protocol and now make the Batsman class conform to Cricketer protocol.
572
+
573
+
```
574
+
class BatsmanWhoCanBowl : Cricketer{
575
+
576
+
func canBat() {
577
+
print("I can bat")
578
+
}
579
+
580
+
func canField() {
581
+
print("I can field")
582
+
}
583
+
584
+
func canBowl() {
585
+
print("I can bowl")
586
+
}
587
+
588
+
}
589
+
590
+
class AllRounder : BatsmanWhoCanBowl{
591
+
592
+
}
593
+
594
+
```
595
+
596
+
We then define a new class named BatsmanWhoCanBowl with super class as Cricketer and define the extra method of canBowl in this class.
0 commit comments