Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to avoid unused method parameter in some of the subclasses while applying strategy pattern?

I have the following scenario where I have different kinds of sales algorithms to calculate the sales price. FixedSaleStrategy does not need basePrice parameter while all the other strategy implementations need it. Is there a good way to avoid this redundant parameter?

public abstract class SalesStrategy
{
    public abstract double GetPrice(double basePrice, double saleAmount);
}
public class AmountOffSale : SalesStrategy
{
    public override double GetPrice(double basePrice, double salesAmount)
    {
        return basePrice - salesAmount;
    }
}
public class FixedPriceSale : SalesStrategy
{
    public override double GetPrice(double basePrice, double salesAmount)
    {
        return salesAmount;
    }
}
like image 481
derdo Avatar asked Jul 30 '10 23:07

derdo


2 Answers

At the core of the strategy pattern is the idea that the calling code does not know the implementation being called.

If you were to change the parameters used per implementation you would find that you are not getting the full benefit of this pattern: a caller would need to know which implementation was going to be used and how to call it.

What I tend to do is pass a class that contains a super-set of information (something like PricingInfo), which is always populated the same way (Ideally centralized in the code) and the only difference is the implementations of the strategy.

One of the benefits is that I can add a property to my PricingInfo class that was not relevant in the past (like say, systemDiscount), and the impact to the system as a whole is not too large.

like image 185
brian chandley Avatar answered Nov 05 '22 03:11

brian chandley


No. It's not a redundant parameter; the code that utilizes a SalesStrategy should not know which concrete class it is using, so the method signature must be identical in all derived classes.

like image 5
Jamie Ide Avatar answered Nov 05 '22 03:11

Jamie Ide