Sobes.tech
Middle

Name two principles of SOLID, give examples of their violations.

sobes.tech AI

Answer from AI

Single Responsibility Principle (SRP)

This principle states that a class should have only one reason to change, meaning it should perform only one task.

Example of violation: a UserManager class that is responsible both for managing users and for logging actions. Changes in logging requirements would lead to modifications in this class, violating SRP.

class UserManager {
    public void AddUser(User user) { /* add user */ }
    public void Log(string message) { /* logging */ }
}

Liskov Substitution Principle (LSP)

Subclasses should be interchangeable with their base classes without affecting the correctness of the program.

Example of violation: a Square subclass inherits from Rectangle but overrides methods such that setting width and height leads to incorrect behavior.

class Rectangle {
    public virtual int Width { get; set; }
    public virtual int Height { get; set; }
}

class Square : Rectangle {
    public override int Width {
        set { base.Width = base.Height = value; }
    }
    public override int Height {
        set { base.Width = base.Height = value; }
    }
}

Using Square instead of Rectangle can lead to unexpected results, violating LSP.

Name two principles of SOLID, give examples of their… - sobes.tech