Home > Mobile >  Powershell: Is it bad to omit an 'else' if I don't need it?
Powershell: Is it bad to omit an 'else' if I don't need it?

Time:09-17

I have a basic question about if/else query in Powershell.

With if I check a condition. In many cases I don't need an else to run my Code. The code works the same way. But isn't this unclean? What is best practice?

In other words: is it bad to omit an else if I don't need it after an if?

The correct way:

$foo = "bar"

    if (!$foo) {
           Write-Warning "'bar' is missing!" -WarningAction -Continue
    }
    else {
    
        # Proceed with my Code ...
    }

The lazy way:

$foo = "bar"

    if (!$foo) {
           Write-Warning "'bar' is missing!" -WarningAction -Continue
    }

    # Proceed with my Code ...

CodePudding user response:

Yes, but.

In your example, the "correct" and "lazy" versions will not behave in identical a way.

The "lazy" one has a conditional block for the first part, but the rest is always executed.

The "correct" part has two conditional blocks. The code is executed either in the if branch, or in the else branch.

The difference is quite critical. Assume you want to ask user if deleting a bunch of files is OK and then doing it. Consider the difference carefully:

# "Lazy" version
if($are_you_sure) {
    write-output "OK, deleting all your files"
}
# Oops!
Delete-My-Files --force


# "Correct" version    
if($are_you_sure) {
    write-output "OK, deleting all your files"
    Delete-My-Files --force
} else {
    write-output "Skipping over file deletion"
}

On the other hand, it's perfectly OK to skip the else{} branch iff you are going to run rest of the code regardless what the if branch does.

  • Related