title: **"**LSP : The Liskov Substitution Principle**"**
description: "LSP : The Liskov Substitution Principle"
cleanUrl: /sw-engineer/lsp
floatFirstTOC: right

Definition

LSP violated sample

**public class Line** {   
	public Line(Point p1, Point p2){ /*code*/} }    

	public Point P1 { get { /*code*/} } }   
	public Point P2 { get { /*code*/} } }   

	public virtual bool IsOn(Point p) {/*code*/} 
}
 
**public class LineSegment : Line** {   
	public LineSegment(Point p1, Point p2)
         : base(p1, p2) {}    

	public double Length() { get {/*code*/} }
  //Line.IsOn()의 참이 아래에서는 거짓이 될 수 있음.
  public override bool IsOn(Point p) {/*code*/} 
}
 
**class LineClient** {
    void DoSomething(Line) { /*code*/ }
}

LSP 준수 방법

  1. DBC(Design by Contract; 계약에 의한 설계)
  2. deriving 대신 factoring(공통 인자 추출)
**public abstract class LinearObject** {   
	public LinearObject(Point p1, Point p2) { /*code*/} }    

	public Point P1 { get { /*code*/} } }   
	public Point P2 { get { /*code*/} } }    

	public abstract virtual bool IsOn(Point p);
}
 
**public class Line : LinearObject** {   
	public Line(Point p1, Point p2) : base(p1, p2) {}
 
  public override bool IsOn(Point p) {/*code*/} 
}
  
**public class LineSegment : LinearObject** {
	public LineSegment(Point p1, Point p2) : base(p1, p2) {}
 
  public double GetLength() {/*code*/}   

	public override bool IsOn(Point p) {/*code*/} 
}
 
**class LineClient** {
    void DoSomething(Line) { /*code*/ }
}

Conclusion