|
-
Feb 24th, 2015, 05:19 AM
#1
Thread Starter
Frenzied Member
[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
-
Feb 24th, 2015, 07:47 AM
#2
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?
"Ok, my response to that is pending a Google search" - Bucky Katt.
"There are two types of people in the world: Those who can extrapolate from incomplete data sets." - Unk.
"Before you can 'think outside the box' you need to understand where the box is."
-
Feb 24th, 2015, 08:06 AM
#3
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.
-
Feb 26th, 2015, 01:11 AM
#4
Thread Starter
Frenzied Member
Re: How to improve this code?
Thanks, I figured the code was overly complex!
/H
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|