Simpler Is Better
From Huben's Wiki
(Created page with "When we are confronted with a large algebraic expression or lots of ifs, we normally need to slow down and analyze it carefully. Wouldn't it be better if we could write it more ...") |
|||
Line 53: | Line 53: | ||
</pre> | </pre> | ||
It may seem more difficult to factor out a not (!) using De Morgan's Law: see the homework. | It may seem more difficult to factor out a not (!) using De Morgan's Law: see the homework. | ||
+ | |||
+ | Why use De Morgan's Law? Sometimes it simplifies the code very nicely. | ||
+ | ==Short Circuit Evaluation== | ||
+ | Sometimes a boolean expression's value can be decided before the whole expression is evaluated. Java exploits this opportunity for optimization. For example: | ||
+ | <pre> | ||
+ | (a !=0 && c == b/a) | ||
+ | </pre> | ||
+ | If a is 0, then the left argument of the && is false, and no matter what the right argument is, the result is false. So Java will not even evaluate the right argument: it will just decide the expression is false. In this example, we use that feature to avoid dividing by zero. If a is not zero, the division will take place. There is a similar short circuit: | ||
+ | <pre> | ||
+ | (a == 0 || c == b/a) | ||
+ | </pre> | ||
+ | Here when the left argument of the || is true, we do not need to evaluate the right argument. |