Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The third SOLID principle, which you’ll cover now, is Liskov Substitution. Its definition states:

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

In other words, if swapping out an object with its subclass could potentially break the affected component, you’re not adhering to this principle.

This principle isn’t a hard rule that you must follow in the system design; rather, it’s a guideline that engineers should aim to follow and respect.

In the previous principles, Single Responsibility made you break the system into smaller focused parts. This principle sets boundaries for the subclasses you implement in your system.

Base classes define the common functionality and the main APIs for your objects. Child classes, also known as subclasses, can implement that functionality in their own unique ways.

However, if subclasses start offering unexpected functionality that affects the system, then you’re breaking the Liskov Substitution principle. The system itself won’t detect this issue, as it depends on the various types to function properly. The responsibility to adhere to this principle falls on you.

It’s important to remember that if you have to create a subclass with extra functionality or one that alters the system’s expected output, the best practice is to update the base class to accommodate that potential output, even if not all subclasses will use it.

Does that sound confusing? It will make sense once you try it out with some code.

Currently, your contacts app doesn’t perform any validation when you update a contact card’s information. You simply expect the app to save whatever information it receives. There’s nothing to notify the system that an update should be rejected.

So for your next step, you’ll implement a new EmergencyContactCard in your contacts app. This card will have a restriction: The phone number must be three digits long. Any call to set(:) methods that change the phone number must verify that the new number contains exactly three digits.

In the next demo, you’ll explore how to adhere to the governance that the Liskov Substitution Principle requires. You’ll also learn how to update the system as needed to meet requirements without violating the principle.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo 1