Which of the following is more readable and preferable?
This, where the default value is assigned in the declaration:
Dim isLastWeekOfPeriod As Boolean = False
If periodInfo.WeekCount = weekInfo.Week Then
isLastWeekOfPeriod = True
End If
Or this, where the value is set in the else clause:
Dim isLastWeekOfPeriod As Boolean
If periodInfo.WeekCount = weekInfo.Week Then
isLastWeekOfPeriod = True
Else
isLastWeekOfPeriod = False
End If
Neither.
Write the assignment directly in the initialisation, don’t use
Ifhere at all:The parentheses are not necessary but make the assignment-vs.-comparison more readable. By the way, with
Option Infer Onyou can also safely remove the type name, it’s obvious from the initialisation expression and the variable name prefixis:Remember: Short is good (as long as it doesn’t negatively affect readability).
Rationale
Your first code is acceptable but it does more or less the same as my above code and has four times more lines of code, without any benefit whatsoever.
The second code does the initialisation twice: once in the declaration, since every variable is implicitly default-initialised in VB (thus
isLastWeekOfPeriodtakes on the valueFalsein the first line). And once in the conditional block after that. Oh, and finally this code is five times as long as mine.Furthermore, writing
If a Then result = True Else result = Falseis always doing redundant work. There is no reason not just to writeresult = adirectly.