我有这个代码:
Private Sub carButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles carButton.Click
fTrafficSurveyA.incrementCount("Car")
Call updateView()
End Sub
Private Sub bicycleButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bicycleButton.Click
fTrafficSurveyA.incrementCount("Bicycle")
Call updateView()
End Sub
Private Sub lorryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lorryButton.Click
fTrafficSurveyA.incrementCount("Lorry")
Call updateView()
End Sub
我已将其更改为以下内容:
Private Sub carButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles carButton.Click
ButtonClickCode(CType(sender, Button))
End Sub
Private Sub bicycleButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bicycleButton.Click
ButtonClickCode(CType(sender, Button))
End Sub
Private Sub lorryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lorryButton.Click
ButtonClickCode(CType(sender, Button))
End Sub
Private Sub ButtonClickCode(ByVal mySender As Button)
Dim incrementVehicle As String
Select Case mySender.Name
Case "carButton"
incrementVehicle = "Car"
Case "bicycleButton"
incrementVehicle = "Bicycle"
Case "lorryButton"
incrementVehicle = "Lorry"
Case Else
incrementVehicle = ""
End Select
fTrafficSurveyA.incrementCount(incrementVehicle)
Call updateView()
End Sub
新代码有更多的代码行。
新版本是更好的做法,还是我应该遵循第三种模式?
编辑
使用 Guffa 的回答 + 其他评论,我更改了基础TrafficSurveyA
模型以包含枚举类型并更改了它的功能incrementCount
,如下所示......这个枚举类型是否在正确的位置?
Enum vehicleType
Car
Lorry
Bicycle
End Enum
Public Sub incrementCount(ByVal vehicle As vehicleType)
' Preconditions: none
' Postconditions: If vehicle is "Car", "Bicycle" or "Lorry" then 1 is added
' to the corresponding count. Otherwise nothing is done.
Select Case vehicle
Case vehicleType.Car : fCars = fCars + 1
Case vehicleType.Bicycle : fBicycles = fBicycles + 1
Case vehicleType.Lorry : fLorries = fLorries + 1
Case Else 'do nothing
End Select
End Sub
接口代码最终是这样的:
Private Sub carButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles carButton.Click
ButtonClickCode(TrafficSurveyA.vehicleType.Car)
End Sub
Private Sub bicycleButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bicycleButton.Click
ButtonClickCode(TrafficSurveyA.vehicleType.Bicycle)
End Sub
Private Sub lorryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lorryButton.Click
ButtonClickCode(TrafficSurveyA.vehicleType.Lorry)
End Sub
Private Sub ButtonClickCode(ByVal incrementVehicle As TrafficSurveyA.vehicleType)
fTrafficSurveyA.incrementCount(incrementVehicle)
Call updateView()
End Sub