[RESOLVED] How to improve this code?
Hi!
I have written a small method that keeps track of a pivot control containing months from jan-dec. The pivot can scroll both ways and I have to keep track of which way the scrolling occurs, and either reduce or increase the selecteddatetime by one month.
Here is the code so far
Code:
Private Sub CalculateSelectedDate(lastSelected As Integer, selectedPivotIndex As Integer)
Dim diff = lastSelected - selectedPivotIndex
' From feb-mar
If diff < 0 AndAlso Math.Abs(diff) = 1 Then
SelectedDate = SelectedDate.AddMonths(1)
' From mar-feb
ElseIf diff > 0 AndAlso Math.Abs(diff) = 1 Then
SelectedDate = SelectedDate.AddMonths(-1)
' From dec to jan
ElseIf diff < 0 AndAlso Math.Abs(diff) > 1 Then
SelectedDate = SelectedDate.AddMonths(-1)
' From jan to dec
ElseIf diff > 0 AndAlso Math.Abs(diff) > 1 Then
SelectedDate = SelectedDate.AddMonths(1)
End If
End Sub
I am almost certain this code can be written in a better way, and I am interested in knowing your opinions on how to refactor it?
What I check is
* which way the navigation is going by comparing last index and current index
* and two special cases for navigating between years
/Henrik
Re: How to improve this code?
Why do you think it needs improving? What calculation do you think could be extracted out and performed only once?
Re: How to improve this code?
If diff < 0 AndAlso Math.Abs(diff) = 1 Then 'That is the same as diff = -1
ElseIf diff > 0 AndAlso Math.Abs(diff) = 1 Then 'This is the same as 1
ElseIf diff < 0 AndAlso Math.Abs(diff) > 1 Then 'This is the same as <-1
ElseIf diff > 0 AndAlso Math.Abs(diff) > 1 Then 'And finally the same as >1
Code:
Dim intMonths As Integer = 0
Select Case lastSelected - selectedPivotIndex
Case Is < -1, 1
intMonths = -1
Case Is > 1, -1
intMonths = 1
End Select
SelectedDate = SelectedDate.AddMonths(intMonths)
Numerous ways to do that.
Re: How to improve this code?
Thanks, I figured the code was overly complex!
/H