Liskov's Substitution Principle(LSP)

Discussion in 'C' started by sharanbr, Aug 20, 2010.

  1. sharanbr

    sharanbr New Member

    Joined:
    Aug 20, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Folks,

    I am not a seasoned C++ programmer but trying to understand some of the OOPS concepts that can be applied to other languages. I am a bit confused with the above principle.

    One of the explanation is as below:
    "We must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules"

    But most of the time, in our derived classes, we actually replace the functionality of the base class. In other words, we specialize. But according to the above rule, we should not be doing that but adding new functionality without replacing existing one.

    Have I understood it correctly?
    Am I missing something here?

    Regards,
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    We never replace the existing functionality in derived classes but we enhance it.

    Lets take a simple example

    Class Operation

    Where we have addition as method.

    Now our addition method can only add integers.

    Now we derive a class AdvOperations to perform addition which can add floating numbers.

    Now the above definition says we extend it but not replace it and this means we do not start doing subtraction in addition class but get it more advance.
     
  3. sharanbr

    sharanbr New Member

    Joined:
    Aug 20, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    I think you are giving an example where the derived class is adding fresh piece of code (new function in your example). There are occasions where the functions in the base classes need to be overridden to specialize the class. In that case, following this rule becomes easy. Can you give an example?

    I am not questioning the LSP but I am only trying to understand how easy or difficult it is in practical situation.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    This isn't a hard and fast rule that must be followed no matter what. It's purely a guideline. The point is that the function should do what is expected; if it doesn't then this means your object model is wrong.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice