リスコフの置換原則に気を遣おう

タイトル装飾

リスコフの置換原則に気を遣おう

 


 

リスコフの置換原則に気を遣おう

リスコフの置換原則とは

リスコフの置換原則(りすこふのちかんげんそく、: Liskov substitution principle)は、オブジェクト指向プログラミングにおいて、サブタイプのオブジェクトはスーパータイプのオブジェクトの仕様に従わなければならない、という原則である。リスコフの置換原則を満たすサブタイプを behavioral subtype英語版 と呼ぶ。 

wikipediaより引用

どういうこと?

継承(is-a)の関係にあるクラスは親クラス以上の機能を持ってはいけないということ

逆説的にはis-aの関係にないものを継承しないこと

‘’’

class Rectangle

{

public:

    virtual void SetWidth(int Width)

    {

        this->Width = Width;

    }.my-custom-style

    virtual void SetHeight(int Height)

    {

        this->Height = Height;

    }.my-custom-style

    int GetArea() const

    {

        return Width * Height;

    }.my-custom-style

protected:

    int Width = 0;

    int Height = 0;

}.my-custom-style ;

class Square : public Rectangle

{

public:

    void SetWidth(int Width) override

    {

        this->Width = Width;

        this->Height = Width;

    }.my-custom-style

    void SetHeight(int Height) override

    {

        this->Width = Height;

        this->Height = Height;

    }.my-custom-style

}.my-custom-style ;

‘’’

この場合

 

つまり…?

継承するときは厳密にis-a関係か注意しよう!

余談

この原則を提唱したBarbara Liskovさんは女性で御年 86歳とのこと

作者
  Y.M
  PG

目次

目次を生成中...