On Tue, 20 Nov 2007 13:36:41 -0500, Abhijit Gadkari
<[EMAIL PROTECTED]> wrote:

>I was doing some code review. I saw something interesting – Liskov
>implementation. [for more info, check out
>http://en.wikipedia.org/wiki/Liskov_substitution_principle]
>
>Here is the sample implementation of the same.
>
>namespace ToTest
>{
>    class Liskov
>    {
>        public Liskov()
>        {
>            //do nothing
>        }
>
>        public virtual int Add(int one,int two)
>        {
>            return one + two;
>        }
>    }
>
>    class DerievedLiskov :Liskov
>    {
>        public DerievedLiskov()
>        {
>            //do nothing
>        }
>
>        /// <summary>
>        /// <para>to add the number to itself.For Example - Add(4,0) will
>result 8</para>
>        /// </summary>
>        /// <param name="one"></param>
>        /// <param name="two"></param>
>        /// <returns></returns>
>        public override int Add(int one, int two)
>        {
>            if (two == 0)
>            {
>                return one + one;
>            }
>            else
>            {
>                return base.Add(one, two);
>            }
>        }
>
>        public int Add(int one)
>        {
>            return one + one;
>        }
>    }
>}
>
>Now, I know there is no validation here. But the point is about
>substitution principle. Here we have Add method in the base class. An
>override in derived class will substitute it.

yes....but the problem is what does the client code expect to happen when
it calls "Add(int one, int two)"....on a liskov object....

now if the client just expects no more than the signature i.e. you pass 2
ints and get one back...then the substitution is technically 'correct'....

but I expect the client code would expect much more than this....

if it were me I would expect the result to be the sum of the two
parameters passed....clearly the override does not do this...so
substitution is actually broken, and the code is incorrect, the compiler
doesn't warn you, because it doesn't know...but basically it is at best
bad practice and at worse a bug.


>
>SO if we want to change the behavior of Add method such that it will
>accept only one integer and will return the result as int added to itself
>[i.e. 3+3=6],we have two options as coded in the DerievedLiskov. Which one
>is beter from oo design point?
>

so from an OO perspective the override is bad/wrong...it breaks (any
sensible interpretation of the) substitution.

the additional method 'Add' is a much better solution...but I would call
it 'double' or 'times2'.

>Thanks.
>
>Abhi
>
>===================================
>This list is hosted by DevelopMentor®  http://www.develop.com
>
>View archives and manage your subscription(s) at
http://discuss.develop.com

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to