VB • Refactor the Purchase class.

Listing 1. The newly refactored Purchase class has a new method for calculating customer discount and explicit constants to hold literal values. This gives you improved maintenance qualities. The code is also easier to understand by another programmer.

Public Class Purchase
Private Const LOYAL_CUSTOMER_INDEX _
As Decimal = 0.97D
Private Const LOYAL_CUSTOMER_ _
PURCHASE_NUMBER As Integer = 3 Private customer As Customer Private items As List(Of PurchaseItem)
Public Function CalculateTotal() As Decimal
Dim total As Decimal = 0
For Each pItem As PurchaseItem In items
total += pItem.Price Next Return LoyalCustomerDiscount(total)
End Function
Private Function LoyalCustomerDiscount( _
ByVal itemCostTotal As Decimal) As Decimal
If (customer.NumberOfPurchases > _
LOYAL_CUSTOMER_ _
PURCHASE_NUMBER) Then
Return itemCostTotal * _
LOYAL_CUSTOMER_INDEX
Else
Return itemCostTotal
End If
End Function
End Class