Is there a preferred practice around initialising variables which are first defined within a branch of code, or is this purely subjective / personal preference?
i.e. there are multiple ways this can be done; the most obvious of which are below:
#option 1 [string]$path = '' if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { $path = ${env:ProgramFiles(x86)} } else { $path = $env:ProgramFiles } Get-ChildItem $path #option 2 [string]$path = $env:ProgramFiles if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { $path = ${env:ProgramFiles(x86)} } Get-ChildItem $path #option 3 if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { [string]$path = ${env:ProgramFiles(x86)} } else { [string]$path = $env:ProgramFiles } Get-ChildItem $path
In most programming languages you'd go with option 1
; i.e. have the variable declared and defaulted at the top, then assign it in a later branch. You may select option 2
instead if the cost of fetching the value is insignificant (e.g. in the above we're just pulling back an environment variable, so it's a low cost operation; but if we were pulling back a value from an external resource / using an expensive query or operation we may prefer option 1
to option 2
). Equally some people may prefer option 1 to option 2 because it better illustrates the conditions under which each value should be used. Option 3
is only permissible in languages which don't require variable declaration; so is allowed in PowerShell / is the lowest cost solution (i.e. minimum number of assignments).
NB: I realize that the [string]
qualifier is superfluous / that PowerShell will automatically determine this; this is just something I include to help illustrate the idea of variable declaration (i.e. first assignment).
I feel an aversion to option 3, probably because of my background in other languages; so don't know if others would have the same aversion, or if most people just think "this is the right thing to do in this language".
Are there any guidelines on this sort of thing (i.e. when there are no considerable performance considerations or additional factors to better inform the decision)?
[string]$path = Get-ProcArchitectureDependentProgFilesPath
... simple helper function allow to avoid the very question and make the code more readable too. (I'll note that I find the accepted answer acceptable too, if the if condition is easier.)