WAQS: Calculated properties and polymorphism

7 reasons to use WAQS

WAQS documentation

 

Sometimes we need to use polymorphism with calculated properties.

In our sample, we could want to apply a 10% discount to VIPCustomers.

How to express it? You could not use asbtract / virtual / override keywords in static methods.

Because WAQS will only use this code to generate another one, we can just use attributes on the specifications.

So our sample could be written like this:

[Virtual]
public static double GetDiscount(this Customer c)
{
    return 0;
}

[Override]
public static double GetDiscount(this VIPCustomer c)
{
    return 0.1;
}


WAQS code analysis will see these attributes and will generate adequate code.



So in Customer class, WAQS will generate this code:



public virtual double Discount
{
    get
    {
if (Specifications != null && Specifications.HasDiscount)
            return Specifications.Discount;
        return 0;
    }
    set
    {
        throw new System.InvalidOperationException();
    }
}


And this one in VIPCustomer class:



public override double Discount
{
    get
    {
        if (Specifications != null && Specifications.HasDiscount)
            return Specifications.Discount;
        return 0.1;
    }
    set
    {
        throw new System.InvalidOperationException();
    }
}


So with this way you have the expected polymorphism

This entry was posted in 16868. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>