Inferential Transformations
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
boolean
Values:
if
)while
,
for
)boolean
Values:
>
, ==
)
evaluate to a boolean
value||
,
&&
) can be performed on
boolean
values and evaluate to a
boolean
valueboolean
expressions to reduce the mess
if
or else
blocks
if
statementsif
statementsif (x <= limit) { } else { message = x + " exceeds the limit."; }
!
operatorif (!(x <= limit)) { message = x + " exceeds the limit."; }
!(a > b)
becomes (a <= b)
!(a >= b)
becomes (a < b)
!(a < b)
becomes (a >= b)
!(a <= b)
becomes (a > b)
!(a == b)
becomes (a != b)
or
((a < b) || (a > b))
!(a && b)
becomes (!a) || (!b)
!(a || b)
becomes (!a) && (!b)
if
Statementsif
Statements (cont.)if (speed > limit) { if (type == SPORTSCAR) { // Additional Statements } }
if ((speed > limit) && (type == SPORTSCAR)) { // Additional Statements }
if
Statementsif
statements with identical
ramifications. For example:if (weight > safeWeight) { atRisk = true; } if (bloodSugar > safeBloodSugar) { atRisk = true; }
if ((weight > safeWeight) || (bloodSugar > safeBloodSugar)) { atRisk = true; }
||
if ((weight > safeWeight) || (bloodSugar > safeBloodSugar)) { ++risk; }
if (weight > safeWeight) { ++risk; } if (bloodSugar > safeBloodSugar) { ++risk; }
if (weight > safeWeight) { ++risk; } else { if (bloodSugar > safeBloodSugar) { ++risk; } }
||
||
(cont.)||
is simpler and
clearer!if
Statements with a Twist:
if (Array.getLength(sales) > 1) { if (sales[1] == 0) { // Additional statements } }
if ((Array.getLength(sales) > 1) && (sales[1] == 0)) { // Additional statements }
sales[1]
doesn't exist if sales
has
a length of 1
boolean
expression when
the outcome can be determinedfalse && x
evaluates to false
(sometimes called the simplification rule)true || x
evaluates to true
(sometimes called the addition rule)