views:

72

answers:

2

Suppose I have a class that represents a product to be priced using one of a number of different pricing strategies. This pricing occurs hundreds of times per second, so to eliminate repetitive if/else statements I am instead using a delegate to launch the appropriate strategy, like so:

Private Delegate Sub PricingModel(ByVal params As PricingParameters)
Private myPricingModel As PricingModel
Private myPricingParameters As PricingParameters

Public Sub RunPricingModel()
    myPricingModel(myPricingParameters)
End Sub

My question is this: if I want to be able to change the strategy, what do I do with myPricingModel? Currently I am simply setting it to a new PricingModel:

Public Sub SwitchStrategy(ByVal strategy As PricingStrategy)
    Select Case strategy
        Case PricingStrategy.STRATEGY_X
            myPricingModel = New PricingModel(AddressOf PricingModelStrategyX)
        Case PricingStrategy.STRATEGY_Y
            myPricingModel = New PricingModel(AddressOf PricingModelStrategyY)
        Case Else
            Exit Sub
    End Select
End Sub

But this doesn't look right to me (though it seems to work). Is there an accepted/better way of doing this? Or is this the standard way? Or is this just simply a doomed approach from the start?

+3  A: 

There is nothing inherently wrong with this overall approach. As long as PricingStrategy is otherwise acceptable as an enum then this is a perfectly acceptable way of changing private behavior for a different pricing strategy.

My only nitpick comment would be that in "Case Else" you should avoid failing silently.

JaredPar
Yup, you are using a local version of the command pattern. Really handy in some places. Also agree with the Case Else note. Fail hard, loud and early.
Wyatt Barnett
It was really helpful to receive some validation on this method from a respected developer. Thanks.
Dan Tao
A: 

You can have a static class with the pricing stretegies (C#):

public static class PricingStrategies {
    public static PricingStrategyX( PricingParameters parameters ) { /* here is body */ }
    public static PricingStrategyY( PricingParameters parameters ) { /* here is body */ }
}

// ... somewhere elsewhere ...
public PricingStrategyDelegate Pricing;
// ...
this.Pricing = PricingStrategies.PricingStrategyX;
TcKs