Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name for this concept?

I have a negligible attention span, and since I'm immersed in La Vida Powershell at the moment, my code will be formatted as such

I apologize in advance if this has been discussed elsewhere, but since my problem is that I don't know what this is called, my googling efforts have been understandibly fruitless.

imagine three functions:

function GrowGrapes(){...} #grows grapes.
function MakeWine(){...} #uses said grapes to make wine
function DrinkWine(){...} #drinks said wine

if the first fails, then you don't want to, and must not, attempt the 2nd. If the 2nd fails, or is never ran, then there is no point in ever attempting to perform the 3rd.

rather than a big obnoxious nest of IF statements like this...

IF ([bool]GrowGrapes()) {
   IF ([bool]MakeWine()) {
      DrinkWine()
   }
}

in certain languages (I BELIEVE I learned this in reference to C...) you can do the following:

IF ([bool]GrowGrapes() -AND [bool]MakeWine()) {DrinkWine()}

or even

$rslt = ([bool]GrowGrapes() -AND [bool]MakeWine()) -AND [bool]DrinkWine()

and trust that the 2nd half of your conditional would only ever execute if the first came back as true/success/whatever.

likewise you could OR two expressions, and trust that the 2nd would only ever be executed and tested if the first came back as false

[bool]MakeWine() -OR [bool]BuyWine()      #only attempt to purchase wine if 
                                          #the attempt to make it has failed

My question is: What is this behavior called? Also, does powershell support it?

like image 840
TheGreatTriscuit Avatar asked Nov 22 '25 09:11

TheGreatTriscuit


1 Answers

It is called short-circuit evaluation, and Powershell does support it. See the sections on -and and -or here.

EDIT The original link appears to be broken (as of 2014-11-05); a suitable alternative is about_Logical_Operators.

like image 144
Gabe Moothart Avatar answered Nov 24 '25 23:11

Gabe Moothart