Home
Do you declare variables when you need them?
  v1.0 Posted at 25/04/2018 7:59 AM by Tiago Araujo

Should you declare variables at the top of the function, or declare them when you need to use them? If you come back to your code after a few weeks and you no longer need a variable, you are quite likely to forget to delete the declaration at the top, leaving orphaned variables. Here at SSW, we believe that variables should be declared as they are needed.​

​Private Sub Command0_Click()
Dim dteTodayDate As Date
Dim intRoutesPerDay As Integer
Dim intRoutesToday As Integer
Dim dblWorkLoadToday As Double
dblWorkLoadToday = Date.Now()
.
....many lines of code...
.
intRoutesPerDay = 2
End Sub

Figure: Bad example


Private Sub Command0_Click()
Dim dteTodayDate As Date
dteTodayDate = Date.Now()
.
....many lines of code...
.
Dim intRoutesPerDay As Integer
intRoutesPerDay = 2
.
....continuing code...
.End Sub

​Figure: Good example​​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.