100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

Liskov Substitution and Interface Segregation

Understand why subtypes must honor their base type's contract and why fat interfaces should be split into focused ones.

SOLID PrinciplesIntermediate11 min readJul 8, 2026
Analogies

Introduction

The Liskov Substitution Principle (LSP) and Interface Segregation Principle (ISP) both address how abstractions should be designed and used. LSP ensures that a subclass can stand in for its base class without surprising callers, while ISP ensures that interfaces stay small enough that clients only depend on what they actually use.

🏏

Cricket analogy: LSP is like ensuring any specialist opener can be swapped into the top order without surprising the team's run-rate plan, while ISP ensures a bowling coach's checklist only asks about bowling skills, not batting stats an all-rounder doesn't need.

Explanation

LSP, formulated by Barbara Liskov, states that if S is a subtype of T, objects of type T in a program should be replaceable with objects of type S without altering the correctness of that program. In practice this means subclasses must not strengthen preconditions, weaken postconditions, or throw away behavior that callers rely on. The classic counterexample is modeling a Square as a subclass of Rectangle: a Rectangle's contract allows width and height to be set independently, but a Square must keep both equal, so setting one silently changes the other and breaks code written against Rectangle's contract.

🏏

Cricket analogy: Just as a genuine all-rounder must bowl and bat without one skill secretly breaking the other, LSP says a substitute must fully honor the original player's role; the classic trap is assuming a specialist 'floater' batsman fits any batting-order slot when the role's contract (fixed position) actually forbids it.

ISP states that no client should be forced to depend on methods it does not use. A single 'fat' interface that bundles many unrelated operations forces every implementer to provide (or stub out) methods irrelevant to it. The fix is to split the fat interface into several smaller, role-specific interfaces so classes implement only the interfaces that describe what they actually do.

🏏

Cricket analogy: ISP is like not forcing a specialist wicketkeeper to also be evaluated on fast-bowling metrics; instead, the keeper's fitness assessment interface should be split so only relevant skills (glovework, reflexes) are required, not pace-bowling speed radar readings.

Example

python
# --- LSP: classic Rectangle/Square counterexample ---

class Rectangle:
    def __init__(self, width: float, height: float):
        self.width = width
        self.height = height

    def set_width(self, width: float) -> None:
        self.width = width

    def set_height(self, height: float) -> None:
        self.height = height

    def area(self) -> float:
        return self.width * self.height


class Square(Rectangle):
    """Violates LSP: forces width == height, breaking Rectangle's contract."""
    def set_width(self, width: float) -> None:
        self.width = width
        self.height = width  # silently changes height too!

    def set_height(self, height: float) -> None:
        self.width = height
        self.height = height  # silently changes width too!


def resize_and_check(rect: Rectangle) -> None:
    rect.set_width(5)
    rect.set_height(10)
    # A caller relying on Rectangle's contract expects area == 50 here.
    assert rect.area() == 50, f"LSP broken: got {rect.area()}"


# resize_and_check(Rectangle(1, 1))  # passes
# resize_and_check(Square(1, 1))     # fails: area is 100, not 50

# LSP-compliant fix: don't force Square to inherit Rectangle's mutable contract.
# Instead, use a shared read-only Shape abstraction.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        ...

class FixedRectangle(Shape):
    def __init__(self, width: float, height: float):
        self._width = width
        self._height = height

    def area(self) -> float:
        return self._width * self._height

class FixedSquare(Shape):
    def __init__(self, side: float):
        self._side = side

    def area(self) -> float:
        return self._side * self._side


# --- ISP: splitting a fat interface into focused ones ---

# Before: one bloated interface forces every worker to implement everything.
class FatWorker(ABC):
    @abstractmethod
    def work(self): ...
    @abstractmethod
    def eat(self): ...
    @abstractmethod
    def sleep(self): ...

class RobotWorker(FatWorker):
    def work(self):
        print("welding")
    def eat(self):
        raise NotImplementedError("robots don't eat")  # forced, unused method
    def sleep(self):
        raise NotImplementedError("robots don't sleep")


# After: smaller, role-specific interfaces.
class Workable(ABC):
    @abstractmethod
    def work(self): ...

class Eatable(ABC):
    @abstractmethod
    def eat(self): ...

class Sleepable(ABC):
    @abstractmethod
    def sleep(self): ...

class HumanWorker(Workable, Eatable, Sleepable):
    def work(self):
        print("coding")
    def eat(self):
        print("eating lunch")
    def sleep(self):
        print("sleeping")

class Robot(Workable):
    def work(self):
        print("welding")

Analysis

The Rectangle/Square example shows how inheritance can be misused to model an 'is-a' relationship from geometry class that does not hold for mutable behavior: a Square is a Rectangle mathematically, but Square cannot honor Rectangle's independent-setter contract. The fix was not to patch Square, but to stop assuming Rectangle's mutable API is the right shared abstraction at all -- an immutable Shape interface with only area() sidesteps the broken contract entirely. Similarly, RobotWorker was forced to implement eat() and sleep() only to throw exceptions, which is a strong signal that FatWorker should be segregated. After the split, Robot implements only Workable, and no client that only needs 'can this work?' is coupled to eating or sleeping behavior it will never use.

🏏

Cricket analogy: The Rectangle/Square trap mirrors assuming a specialist finisher can bat anywhere in the order like a versatile top-order batsman; the fix isn't patching the finisher's role but recognizing 'batsman' needs a narrower shared interface, just as forcing an umpire to also do groundskeeping (like FatWorker's eat/sleep) shows the role needs splitting so umpires only implement officiating duties.

Key Takeaways

  • LSP: a subclass must be usable anywhere its base class is expected, without breaking caller assumptions.
  • Overriding a method to throw an exception or silently change unrelated state is a common LSP red flag.
  • The Rectangle/Square example shows that 'is-a' in the real world does not always translate to safe inheritance in code.
  • ISP: split large, multi-purpose interfaces into small, role-specific ones.
  • A class implementing methods it must stub out with NotImplementedError signals an ISP violation.

Practice what you learned

Was this page helpful?

Topics covered

#Python#SoftwareEngineeringStudyNotes#SoftwareEngineering#LiskovSubstitutionAndInterfaceSegregation#Liskov#Substitution#Interface#Segregation#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse