Question

I have scenario where a virtual function is overridden in derived class with additional pre-conditions. Here is the snapshot -

class Process
{
    protected virtual void ValidateDates()
    {
        if (Entity.StartDate.Date > Entity.EndDate.Date)
        {
            AddFailure("Start date cannot be later than the End date");
        }
    }
}

class InitialProcess : Process
{
    protected override void ValidateDates()
    {
        base.ValidateDates();
        if (IsImmediateProcess)
        {
            if (Entity.StartDate.Date > CurrentDateTime.Date)
            {
                AddFailure("Start date cannot be later than the current date");
            }
        }
    }
}

If I understand correctly, the code here breaks Liskov substitution by imposing an additional pre-condition - IsImmediateProcess and other of date check. Is it correct? Or is it alright for a overridden function to call a base function and then add its own behavior to it?

I cannot move the condition introduced by InitialProcess type in the overridden method to the base type as it is specific for InitialProcess.

What could have been the best way to achieve the overridden behavior in such scenarios, where derived class overrides the behavior and wants to substitute its own behavior, without breaking Liskov principle, if it does so like in this case?

Was it helpful?

Solution

Assuming you meant class InitialProcess : Process

This is exactly following the Liskov principle.

Both classes have the same interface but different (extended) behaviour. The derived class does not have a different pre-condition, it has a different validation-rule. Which is quite OK and does not break anything.

OTHER TIPS

As Henk Holterman says, it not violate LSP. Is strengthened the postconditions, and do not weakened the preconditions, which ok.

So, it do what base class do by calling:

base.ValidateDates();

and add some post conditions (strengthened the postconditions):

if (IsImmediateProcess)

IMHO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top