Presentation is loading. Please wait.

Presentation is loading. Please wait.

The IF Revisited A few more things Copyright © 1998-2014 Curt Hill.

Similar presentations


Presentation on theme: "The IF Revisited A few more things Copyright © 1998-2014 Curt Hill."— Presentation transcript:

1 The IF Revisited A few more things Copyright © Curt Hill

2 Now what? There are several more issues that need consideration
Conditions Nesting Testing If problems Copyright © Curt Hill

3 Conditions We would like to determine if a value is between two bounds
It looks good but does not work The precedence makes it this: if((1 < a) < 10) The first parenthesis produces a boolean which cannot be compared with an int Thus we must do: if(1 < a && a < 10) Copyright © Curt Hill

4 Nesting Any statement may be the THEN or ELSE statement of an if
It is most often a compound statement The interesting one is an if in an if The usual problem is how the elses match the ifs Copyright © Curt Hill

5 Which else? The else may only match one of these Which one is it?
The answer is 3! if(a>b) // 1 if(b>c) // if(c>d)// x = y; else x = z; Copyright © Curt Hill

6 Matching Elses The general rule is that an else matches the closest, previous, unmatched if The language ignores white space and also the layout on the page Thus indenting has no relevance to the compiler It may make the program more (or less) readable Copyright © Curt Hill

7 A Matched Else How is an if completed? An else is encountered for it
It is enclosed within a compound statement An unrelated statement follows Copyright © Curt Hill

8 Three examples if(a>b) // 1 if(b>c) // if(c>d)// x = y; else x = 2*y; else // matches 2 x = z; if(a>b) // 1 if(b>c){ // if(c>d)// x = y; } else // matches 2 x = z; if(a>b) // 1 x = y; y = x*z; else // error x = z; Copyright © Curt Hill

9 Testing Ifs complicate our testing
With only sequential flow we test it once and it is covered With multiple paths one test is generally inadequate Testing strategies then come into view Copyright © Curt Hill

10 Every Statement The first strategy is to make sure that in our testing every statement is tested once We generate test data accordingly We have enough test data each if has both its then and else exercised once This usually means several runs Copyright © Curt Hill

11 Every statement if(a>b) { // 1 b = a++ * 2; c /= 2; } else // 2 1 2
c = a * b / 2; 1 2 Two tests are needed. One forces a > b and the other a <= b Copyright © Curt Hill

12 A path is a unique way through the code
There are four paths 1 2 1, 3 2, 3 1, 4 3 4 2, 4 Copyright © Curt Hill

13 Another way if(a>b) x = 1; else x = 2; if(c>d) y = 3; y = 4;
Copyright © Curt Hill

14 Test Data Again In the above, every statement testing only needs two runs The paths {1,3} and {2,4} executes every statement However, there may be interactions between 1 and 4 that are not exercised Thus every path testing is always as good or better than every statement In programs without decisions or loops one set does both Copyright © Curt Hill

15 How ifs increase paths An if added at the end of a sequence doubles the number of paths An if nested within an if adds one path to the existing number The generalities do not always capture the actual practice Reconsider the quadratic formula evaluation Copyright © Curt Hill

16 Two different approaches
if(discrim < 0) … else if(discrim == 0){ } else { if(discrim < 0){ … } if(discrim == 0){ … } if(discrim > 0){ Copyright © Curt Hill

17 Commentary on above The nested if version is to be preferred
If any of the conditions is true then no further ones will be checked Typically check the most likely one first rather than the straight order I used However, provided that discrim is not changed in the ifs both have three paths Copyright © Curt Hill

18 Largest of three variables
Here are two ways to display the largest of three variables, a, b and c if(a>b) if(a>c) lab.setText(a); else lab.setText(c); else if(b>c) lab.setText(b); lab.setText(c); double big; big = a; if(big<b) big =b; if(big<c) big = c; lab.setText(big); Which do you like better? Why? Copyright © Curt Hill

19 Comparison The first one has two comparisons and one write
The second one has two comparisons, one to three assignments, one write and needs one temporary variable Both have four paths Most professional programmers like the second one Easier to categorize where you are Copyright © Curt Hill

20 Paths and Complexity More paths cause more complexity
Complexity promotes errors As programmers we work hard to subdivide the problem to manage the complexity The magic number is 7 ± 2 TMI and cockpit stories Copyright © Curt Hill

21 Comparisons Again Comparison operators are not boolean operators
A comparison may compare two integers and produce a boolean A boolean operator does a logical operation on two booleans Move this to front after this presenation Copyright Curt Hill

22 Boolean Operators Boolean operators are the AND, OR and NOT
Java operators: && || ! The single & and | are bit string operators not booleans AND, OR, and NOT have the same meaning as is commonly used in English AND/OR have lower precedence than comparisons Copyright Curt Hill

23 Java Operator Truth Table
Q P && Q P || Q !P true false Copyright Curt Hill

24 Boolean Comparisons A sure sign of a novice is to compare a boolean with a truth value: boolean b; if(b == true) // or if(b == false) // or if(b != true) A boolean is already suitable for comparison Use one of these two: if(b) // or if(!b) Copyright Curt Hill

25 Unary or Binary Operators?
There are states in the truth table where we do not care about the second operand TRUE OR TRUE is the same as TRUE OR FALSE The second operand does not matter TRUE OR ? is TRUE Similarly FALSE AND ? is FALSE Copyright © Curt Hill

26 Short Circuit Evaluation
The compiler knows this When ever it knows what the answer will be it stops evaluating Example: if(a!=0 && b/a>12) should always work When a == 0 then the compiler knows that FALSE AND ? is FALSE so does not need to evaluate the b/a>12 Avoids the zero division exception Copyright © Curt Hill

27 Reversing a Condition Suppose there is a condition like a>b && c<2*d We do not want to do anything if this condition is true but if it is false There are several solutions to this DeMorgan’s Laws Negation operator Empty statement Copyright © Curt Hill

28 DeMorgan’s Laws Cover how to reverse an And or Or
!(a && b) = (!a || !b) !(a || b) = (!a && !b) Thus we could reverse a>b && c<2*d into a<=b || c>=2*d Copyright © Curt Hill

29 Negation Operator With an extra set of parentheses we could also use the ! for logical negation: Change: if(a>b && c<2*d) into if(!(a>b && c<2*d)) Copyright © Curt Hill

30 Empty Statement We could also do nothing in the Then part if(a>b && c<2*d || a<c*b) ; else // do what we intended The semicolon by itself is the empty statement It means do nothing Copyright © Curt Hill

31 Empty Statement One nice thing about the empty statement is that it eats extra semicolons: a = b+c;; This will not cause a syntax error The bad news is that it can separate an if from its then part if(a>b); a = b+c; No error, assignment is always executed Only if there is an else will syntax error occur Copyright © Curt Hill

32 Readability The compiler ignores white space!
People do not ignore white space! Use indentation to improve the readability of your programs Indent the statements controlled by an If or any other flow of control statement The change in left margin is a powerful visual clue to the reader Copyright © Curt Hill

33 Example Use: if(a>b){ x = a*b; y += 5; } System. out.print(s);
Do not: if(a>b){ x = a*b; y += 5; } System. out.print(s); Do not: if(a==c){ x = a*b; y += 5; ... else { y *= 2; . . . Use: if(a==c){ x = a*b; y += 5; ... else { y *= 2; Copyright © Curt Hill

34 Error Checking If an error is found do one of two things
Do no other processing Correct and continue At least two ways to do the former The latter cannot be done in general way For any particular program there may be a good correction Copyright © Curt Hill

35 Do Nothing Further Again two ways
Place rest of method in an else Use the return statement Big else: if(a.getText().length() < 1) // complain else { // rest of method in this Copyright © Curt Hill

36 Problems with this If there are lots of separate checks then the ifs and else get nested rather deeply Deep nesting causes problems with complexity Use the return statement: if(a.getText().length() < 1){ a.setText(“Empty field.”); return; } No else is needed Copyright © Curt Hill

37 Return Statement Two forms In a void method: return ;
In a method that returns a value: return expr; This form will be considered during method definition presentations Return exits the method and optionally returns a value No else is needed following Copyright © Curt Hill

38 Correction If there is an obvious correction use that
Empty fields imply zero: if(s.getText().length()<1){ s.setText(“0”); } d = Integer.parseInt( s.getText()); However, there is usually no easy fix We will examine this again later Copyright © Curt Hill

39 Separating Ranges Often we want to classify a value by range
For instance a descriptive word for the age of person: infant is less than 1 year preschool is less than 5 years etc This is usually done with a series of ifs There is a right and wrong way Copyright © Curt Hill

40 Wrong Way Not nested: if(age < 1) s = “infant”; if(age>=1 && age < 5) s = “preschool”; if(age>=5 && age < 12) … This works but there is lots of redundancy If s was set to “preschool” do we want to do another test Copyright © Curt Hill

41 Right Way Nested with simple conditions: if(age < 1) s = “infant”; else if(age < 5) s = “preschool”; else if(age < 12) … Also works, but the first one to find it eliminates any further test Copyright © Curt Hill

42 Not so right Way Nested with anded conditions: if(age < 1) s = “infant”; else if(age>=1 && age<5) s = “preschool”; else if(age>=5 && age < 12) … Also works, but the age>=1 can never be false because of the nesting Copyright © Curt Hill

43 Finally This should be all you need to know about the if
It is the most important decision statement What shall we do for a demo? Copyright © Curt Hill


Download ppt "The IF Revisited A few more things Copyright © 1998-2014 Curt Hill."

Similar presentations


Ads by Google