3. Liskov Substitution Principle (LSP): SOLID Principle

The Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented programming and is about ensuring that derived classes (subclasses) can be substituted for their base classes (superclasses) without affecting the correctness of the program.
we have a base class CreditCard and two subclasses, VisaCard and MasterCard, representing specific types of credit cards. Both subclasses need to adhere to the Liskov Substitution Principle to ensure they can be used interchangeably.
Here’s a simple example:
class CreditCard {
var cardNumber: String
init(cardNumber: String) {
self.cardNumber = cardNumber
}
func makePayment(amount: Double) {
// Default implementation to make a payment
print("Payment of $\(amount) made with a generic credit card.")
}
}
class VisaCard: CreditCard {
override func makePayment(amount: Double) {
print("Payment of $\(amount) made with a Visa card (Card Number: \(cardNumber)).")
}
}
class MasterCard: CreditCard {
override func makePayment(amount: Double) {
print("Payment of $\(amount) made with a MasterCard (Card Number: \(cardNumber)).")
}
}In this updated example, we have a base class CreditCard with a method makePayment. We also have two subclasses, VisaCard and MasterCard, which override the makePayment method to provide their own implementation. Both subclasses can be used interchangeably with the base class, and when you call the makePayment method on them, the specific behavior of the card is executed.
Here’s how you can use these classes:
let visa = VisaCard(cardNumber: "1234-5678-9876-5432")
let masterCard = MasterCard(cardNumber: "5678-1234-4321-8765")
let cards: [CreditCard] = [visa, masterCard]
for card in cards {
card.makePayment(amount: 100.0)
}This code demonstrates that you can use instances of VisaCard and MasterCard interchangeably with CreditCard, adhering to the Liskov Substitution Principle. When you make payments using each card, the appropriate card-specific behavior is executed
Pros:
- Interchangeability: Subclasses can be used interchangeably with their base class, enhancing code reusability and flexibility.
- Consistency: LSP promotes consistent behavior across different class hierarchies, making code easier to understand and maintain.
- Enhanced Polymorphism: It enables the use of polymorphism to create more generic and extensible code.
Cons:
- Complexity: Enforcing LSP can lead to more complex code and design, which may not be necessary for all situations.
- Performance Overhead: Adhering to LSP might lead to performance overhead in some cases, as more generalized code can be less efficient.
👏🏻👏🏻 👏🏻👏🏻 Applaud to express your encouragement. Join me for additional insights and let’s progress together.
