开发者

VB.Net Refactor to Remove Code Duplication

开发者 https://www.devze.com 2023-02-08 03:00 出处:网络
This is a simplified version of a class that I have in my project. Since the Bonus is figured the exact same way in each function I want to remove the obvious code duplication that appears here and ma

This is a simplified version of a class that I have in my project. Since the Bonus is figured the exact same way in each function I want to remove the obvious code duplication that appears here and make the three different functions into one. However I am not sure how to provide the argument that this new function would require.

For instance I am currently just passing the argument like this from code

lblVolumeBonus.Content = TestClass.VolumeBonusAmountStore(bonus).

I think I have to basically turn this logic around and call it with something like

lblVolumeBonus.Content = TestClass.VolumeBonusAmountStore(BonusTrackerBO.StoreBonus)

but I am not sure of the correct syntax or whether I am on the right track at all.

Can someone help get me in the right direction?

Public Class TestClass
Public Shared Function StoreBonus(ByVal bonus As BonusTrackerBO.StoreBonus) As Double

    Dim myBonus As Double = bonus.TicketAmount
    Return myBonus * 5

End Function

Public S开发者_开发问答hared Function DistrictBonus(ByVal bonus As BonusTrackerBO.DistrictBonus) As Double

    Dim myBonus As Double = bonus.TicketAmount
    Return myBonus * 5

End Function

Public Shared Function CompanyBonus(ByVal bonus As BonusTrackerBO.CompanyBonus) As Double

    Dim myBonus As Double = bonus.TicketAmount
    Return myBonus * 5

End Function
End Class

Edit: It may not make a difference but I should have made clear that there are other factors in the equation (I was just trying to keep it simple). So is the answer the same when there are other callbacks to the bonus like bonus.MaximumAmount, bonus.MinimumAmount? There are 5 callbacks to the bonus object and the amounts are different depending on whether it is a Store, District or Company asking.


why not a simple

Public Shared Function GiveBonus(ByVal TicketAmount As Double) As Double
    Return TicketAmount  * 5
End Function



lblVolumeBonus.Content = TestClass.VolumeBonusAmountStore(bonus.TicketAmount)


How about:

Public Shared Function GetBonus(ByVal bonus as Double) As Double
    Return bonus * 5
End Function

Where bonus is bonus.TicketAmount. Or if They all inherit from a base class like BaseBonusClass.

Public Shared Function GetBonus(ByVal bonus as BaseBonusClass) As Double
    Return bonus.TicketAmount * 5
End Function

Edit: or try generics

Public Shared Function GetBonus(Of T As BaseBonusClass)(ByVal bonus as T) As Double
    Return bonus.TicketAmount * 5
End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消