Design Patterns: Refactor a Hierarchy to Adhere to LSP

Level : Intermediate
Mentor: Shailendra Chauhan
Type : GuidedLab
Points : 10
Duration : 00:30:00

Lab Details

Problem Statement:

A lab to follow the LSP principle while doing your code in C#.

  • Do refer to the below class hierarchy including a Voter class with a method vote().
  • Identify subclasses (e.g., UnderageVoter) that do not support voting.
  • Refactor the hierarchy by introducing an interface IVotable and implementing it in appropriate subclasses.
  • Implement a VotingBooth class to manage voting behavior.
  • Update client code in the Main class to reflect the new design.

Hierarchy Class (Voter Class):

// Voter Class

public class Voter

{

    public void vote()

    {

        Console.WriteLine("Voter is casting a vote");

    }

}

// AdultVoter Class

public class AdultVoter : Voter

{

    // Inherits vote() method from Voter

}

// UnderageVoter Class

public class UnderageVoter : Voter

{

    // Underage voters cannot vote, but still inherit vote() method

}

Lab Objective:

Upon completion of this lab, you will be able to:

  • Understand and apply the Liskov Substitution Principle (LSP) in the design of class hierarchies.
  • Identify LSP violations in the existing class hierarchy.
  • Refactor class hierarchies to segregate behaviors with interfaces.
  • Implement interfaces to ensure that appropriate subclasses only include relevant methods.

Prerequisites

You should install the following software on your machine:

  • VS Code or Visual Studio
  • .NET SDK

Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this