Code indentation

From HashVB
Revision as of 13:16, 8 March 2006 by Dee (Talk | contribs)

Jump to: navigation, search

Code indentation is a technique used to make multiple levels of nested code far easier to read and understand.

Take the follwing example:

Private Sub mnuFile_Click()
Dim Index As Long
Dim FileName As String
Dim ShortFileName As String
For Index = 1 To 4
FileName = MRU.Item(Index - 1)
If FileName = "" Then
mnuFileItem(4 + Index).Enabled = False
mnuFileItem(4 + Index).Caption = "-Empty-"
Else
If InStrRev(FileName, "\") = 0 Then
ShortFileName = FileName
Else
ShortFileName = Mid(FileName, InStrRev(FileName, "\") + 1)
End If
mnuFileItem(4 + Index).Enabled = True
mnuFileItem(4 + Index).Caption = "&" & CStr(Index) & ") " & ShortFileName
mnuFileItem(4 + Index).Tag = FileName
End If
Next
End Sub

Compared to:

Private Sub mnuFile_Click()
Dim Index As Long
Dim FileName As String
Dim ShortFileName As String

  For Index = 1 To 4
    FileName = MRU.Item(Index - 1)
    If FileName = "" Then
      mnuFileItem(4 + Index).Enabled = False
      mnuFileItem(4 + Index).Caption = "-Empty-"
    Else
      If InStrRev(FileName, "\") = 0 Then
        ShortFileName = FileName
      Else
        ShortFileName = Mid(FileName, InStrRev(FileName, "\") + 1)
      End If
      mnuFileItem(4 + Index).Enabled = True
      mnuFileItem(4 + Index).Caption = "&" & CStr(Index) & ") " & ShortFileName
      mnuFileItem(4 + Index).Tag = FileName
    End If
  Next
End Sub

The 2nd example is significantly easier to follow what is happening as you can see at a glance what code is dependant on what without having to study each line.