When should I apply demorgans law in programming? -
i think programmer has taken intro programming class had memorize demorgan's law.
in case don't know is, here gist
!(a && b) = !a || !b
!(a || b) = !a && !b
i under assumption if had memorize it, find applicable in programming situation. haven't had use @ all.
is there reason why should use in programming? make program faster, or make conditions easier read?
keeping code readable big reason, , i'm sure whoever works on code after agree it's important one. , you'll save cpu cycle or 2 if invert (!) 1 value instead of two.
another reason bypass short-circuiting. when many languages see !a || !b
stop evaluating if !a true because doesn't matter if !b true or not. !a enough or true.
if , b functions instead of variables, , want both execute, you're gonna have problem:
if( !save_record() || !save_another_record() ) { echo 'something bad happened'; }
demorgan's laws let replace or and. both sides of , need evaluated make sure it's true:
if( !( save_record() && save_another_record() ) ) { echo 'something bad happened'; }
Comments
Post a Comment