Unraveling SOLID: An introduction to the principles with Dart - Part 3: The Liskov Substitution Principle

Unraveling SOLID: An introduction to the principles with Dart - Part 3: The Liskov Substitution Principle

Welcome back! If you've arrived here for the third part of our series on the SOLID principles, I presume you've already mastered the S and O letters. Today, we're diving deeper into the L letter in SOLID. In my opinion, understanding the Liskov Substitution Principle (LSP) might not be straightforward, but I can guarantee that by the end of this discussion, you'll grasp its essence.

L: Liskov Substitution Principle (LSP)

When discussing the Liskov Substitution Principle, we need to cover some fundamentals. The LSP was initially introduced by Barbara Liskov in a 1987 conference keynote address titled "Data Abstraction and Hierarchy." It's based on the concept of "substitutability," which means that a parent class may be replaced by a subclass without breaking the code. The significance of the LSP lies in its ability to ensure that the behavior of a program remains consistent and predictable when substituting objects of different classes. Violating the LSP can lead to unexpected behavior, bugs, and maintainability issues.

Let's explore some examples:

In the example above, we have the BankAccount class with three methods. We also have two other classes that extend from BankAccount: CheckingAccount and SavingsAccount. As you can see, inside SavingsAccount, in the makeLoan method, we're throwing an Exception because loans are not supported by this type of account, which violates the LSP. Take a look at the main function; when we initialize the account variable with CheckingAccount, we're able to run all three methods. However, if we change it to SavingsAccount and try to run makeLoan, we receive an error. This relationship of inheritance does not follow the Liskov Substitution Principle.

Now, consider this example:

In this scenario, we maintain the same class structure, but now we only have one method in the Person class. Both NaturalPerson and LegalPerson extend the Person class and override the validateDocument method. In the main function, when we initialize the person1 variable with NaturalPerson, we can use validateDocument without any issues. Similarly, if we assign person1 with LegalPerson, we can also use validateDocument without any problems. This exemplifies the LSP in action. You should strive to ensure that your classes respect the LSP. Always review your class hierarchies to ensure they uphold this principle.

I hope you found today's discussion enlightening. See you in part 4!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了