Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1101: Programming Methodology

Similar presentations


Presentation on theme: "CS1101: Programming Methodology"— Presentation transcript:

1 CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101/ http://www.comp.nus.edu.sg/~cs1101/

2 Week 6: Writing Modular Programs & Testing and Debugging  Last week:  Chapter 5: Selection Statements (cont’d)  Chapter 6: Repetition Statements  This week:  Chapter 6: Repetition Statements (cont’d)  Writing Modular Programs  Testing and Debugging  Next week:  Recess! (yeah!)  The week after next:  Chapter 7: Defining Your Own Class – Part 2 © CS1101 (AY2009-2010 Semester 1)Week6 - 2

3 Last Week’s Exercise #4: Prime-Number Your DL should have discussed this in last week’s discussion session. Write a program PrimeTest.java to check if a positive integer is a prime. Sample runs: © CS1101 (AY2009-2010 Semester 1)Week6 - 3 Enter a positive integer: 131 131 is a prime. Enter a positive integer: 713 713 is not a prime.

4 Modular Programming (1/6) Download PrimeTestNonModular.java and PrimeTest.java. Study and discuss them. Modular programming  Goes hand-in-hand with stepwise refinement and incremental development  Makes the code easier to develop, test and debug  Promotes reusability of codes In general a problem is solved in 3 steps: input  computation  output. © CS1101 (AY2009-2010 Semester 1)Week6 - 4

5 Modular Programming (2/6) It is customary to write a separate module to perform the computation step. If the computation is complex, it should be further split into smaller steps and each step performed by a module. A ‘module’ (in Java, it is a method)  Should be well-defined  Should do one task © CS1101 (AY2009-2010 Semester 1)Week6 - 5

6 Modular Programming (3/6) A well-defined module  Has a good name (for readability and documentation)  Has a clear interface (what parameters does it take?)  May pass back to its caller no result or a single result (what value does it return?) It’s nothing new! You have seen them before.  Example: setColour(String c) in the Ball class  Example: getColour() in the Ball class © CS1101 (AY2009-2010 Semester 1)Week6 - 6 public void setColour(String c) { colour = c; } Takes in String c. Does not return any value (void). public String getColour() { return colour; } Takes in no parameter. Returns a String.

7 Modular Programming (4/6) Advantages of modular programming:  Easy to replace  E.g.: When you discover a better algorithm for isPrime(int), you just replace that method without affecting any other parts of the program or other programs.  Easy to reuse  E.g.: Suppose you want to write a program to count the number of prime numbers between two integers a and b.  Compare how you would need to modify PrimeTestNonModular.java and PrimeTest.java to do the above. © CS1101 (AY2009-2010 Semester 1)Week6 - 7

8 Modular Programming (5/6) Reusability of code  If isPrime(int) is a very commonly used method, we could even go a step further…  See Prime.java where we define the Prime class in which it contains a class method isPrime(int).  See CountPrimes.java which is an application program that makes use of the Prime class.  It is so short and sweet!  Any other application that requires the isPrime(int) method can use the method in a similar fashion.  As the creator of Prime.java, you can hide the source code and provide only Prime.class. © CS1101 (AY2009-2010 Semester 1)Week6 - 8

9 Modular Programming (6/6) A method should not mix computation with input/output. (Except for very special situation.)  Example: The following is not desirable. © CS1101 (AY2009-2010 Semester 1)Week6 - 9 public static boolean isPrime(int num) { boolean isPrime = false; if (num > 1) { isPrime = true; for (int i = (int) Math.sqrt(num); i>1 && isPrime; i--) if (num % i == 0) isPrime = false; } if (isPrime) System.out.println(num + " is prime."); else System.out.println(num + " is not prime."); return isPrime; } 

10 Last Week’s Exercise #2: AsterisksV1.java Complete AsterisksV1.java to read in an integer n and print n asterisks on a single line. (If n is non-positive, then no asterisk will appear.) Sample runs: © CS1101 (AY2009-2010 Semester 1)Week6 - 10 Enter n: 7 ******* Done! Enter n: -2 Done! Download AsterisksV1Completed.java and study it.

11 AsterisksV2.java Now, write AsterisksV2.java to read in a positive integer n and display n rows of asterisks in the following fashion.  First row has 1 asterisk, second row 3 asterisks, third row 5 asterisks, etc. Your program should be modular. There should be a method printStars(int k) to print a row of k asterisks. Sample runs: © CS1101 (AY2009-2010 Semester 1)Week6 - 11 Enter n: 4 * *** ***** ******* Enter n: 7 * *** ***** ******* ********* *********** *************

12 AsterisksV3.java Now, write AsterisksV3.java to read in a positive integer n and display n rows of asterisks in a “Christmas Tree” pattern. How do you adapt AsterisksV2.java for this? Sample runs: © CS1101 (AY2009-2010 Semester 1)Week6 - 12 Enter n: 4 * *** ***** ******* Enter n: 7 * *** ***** ******* ********* *********** *************

13 Take-home lab assignment #3 It has been released. Deadline is the Monday when school reopens after the recess, 28 September 2009, 23:59hr. Any questions? © CS1101 (AY2009-2010 Semester 1)Week6 - 13

14 Programming Errors Compilation errors  Syntax error (example: missing a semi-colon).  Semantic error. (For example, applying modulus % on floating-point value for certain programming languages. In Java,is it fine? Yes!)  Easiest type of errors to fix. Runtime errors  Occur at runtime.  Java’s exception mechanism can catch such errors. Logic errors  Program runs but produces incorrect result.  Hard to characterize, hence hardest to fix. Programming errors are also known as bugs  Origin: a moth in the Mark I computer. © CS1101 (AY2009-2010 Semester 1)Week6 - 14

15 Testing and Debugging (1/5) Testing  To determine if a code contains errors. Debugging  To locate the error and fix it. Documentation  To improve maintainability of the code.  Include sensible comments, good coding style and clear logic. © CS1101 (AY2009-2010 Semester 1)Week6 - 15 Testing Yes Error? Debug

16 Testing and Debugging (2/5) Modularization and interfaces  Problem is broken into sub-problems and each sub-problem is tackled separately – divide-and-conquer.  Such a process is called modularization.  The modules are possibly implemented by different programmers, hence the need for well-defined interfaces.  The signature of a method (its return type, name and parameter list) constitutes the interface. The body of the method (implementation) is hidden – abstraction.  Good documentation (example: comment to describe what the method does) aids in understanding. © CS1101 (AY2009-2010 Semester 1)Week6 - 16 static double maxmax(double a, double b) Returns the greater of two double values.

17 Testing and Debugging (3/5) Manual walkthroughs  Tracing with pencil-and-paper.  Verbal walkthroughs Print statements  Easy to add  Provide information:  Which methods have been called  The value of parameters  The order in which methods have been called  The values of local variables and fields at strategic points  Disadvantages  Not practical to add print statements in every method  Too many print statements lead to information overload  Removal of print statements tedious © CS1101 (AY2009-2010 Semester 1)Week6 - 17

18 Testing and Debugging (4/5) Example on writing print statements © CS1101 (AY2009-2010 Semester 1)Week6 - 18 System.out.print("Enter 6-digit Matriculation number: "); int number = scanner.nextInt(); // Extract the digits int digit6 = number%10; number /= 10; int digit5 = number%10; number /= 10; int digit4 = number%10; number /= 10; int digit3 = number%10; number /= 10; int digit2 = number%10; int step1 = digit2*2 + digit3*6 + digit4*2 + digit5*4 + digit6; System.out.println("Step 1 = " + step1); // for checking int step2 = step1 % 13; System.out.println("Step 2 = " + step2); // for checking int step3 = 13 - step2; System.out.println("Step 3 = " + step3); // for checking :

19 Testing and Debugging (5/5) Tips and techniques  Start off with a working algorithm  Incremental coding/test early/fix bugs as you find them  Simplify the problem  Explain the bug to someone else  Recognize common errors (such as using ‘=’ instead of ‘==’, using ‘==’ instead of equals( ), infinite loop, etc.)  Recompile everything  Test boundaries  Test exceptional conditions  Take a break © CS1101 (AY2009-2010 Semester 1)Week6 - 19

20 Testing Thoroughly (1/3) Test your programs with your own data  Do not rely on CourseMarker to test your programs! We discussed this in week 4. Richard couldn’t spot the error in this code (FindMaxV2.java) of his: © CS1101 (AY2009-2010 Semester 1)Week6 - 20 // To find the maximum among 3 integer // values in variables num1, num2, num3. int max = 0; if (num1 > num2 && num1 > num3) max = num1; if (num2 > num1 && num2 > num3) max = num2; if (num3 > num1 && num3 > num2) max = num3;  He claimed that he tested it on many sets of data:,,, etc. and the program works for all these.  What did he miss out in his testing?

21 Testing Thoroughly (2/3) In testing your programs thoroughly, do not forget about boundary or special cases!  These are the cases where the program may give the wrong answer – a common error In the Primality Test problem (checking if an integer is a prime), what are the boundary cases? © CS1101 (AY2009-2010 Semester 1)Week6 - 21

22 Testing Thoroughly (3/3) It is also important to test all the paths that your program control flow can take  Design test data to check all paths  Example © CS1101 (AY2009-2010 Semester 1)Week6 - 22 if (x != 3) { y = 5; } else { z = z - x; } if (z > 1) { z = z / x; } else { z = 0; } if (x != 3) y = 5z = z - x if (z > 1) z = z / x z = 0 A B C D E F G H Test data: to test path A, B, G, H; to test path E, F, C, D; etc.

23 Debugger Debugger usually provides the following  Stepping  Breakpoint  Watches (inspecting variables) We will illustrate these on DrJava © CS1101 (AY2009-2010 Semester 1)Week6 - 23

24 Other readings You will learn other advance testing techniques when you do Software Engineering. Some websites  http://www.cs.wustl.edu/~kjg/CS101_SP97/Notes/Debugging/debug ging.html http://www.cs.wustl.edu/~kjg/CS101_SP97/Notes/Debugging/debug ging.html  http://www.csl.mtu.edu/cs2321/www/SELectures/SELeccture3_Deb ugingAndTesting.htm http://www.csl.mtu.edu/cs2321/www/SELectures/SELeccture3_Deb ugingAndTesting.htm © CS1101 (AY2009-2010 Semester 1)Week6 - 24 Program testing can be used to show the presence of bugs, but never to show their absence. ~ Edgar Dijkstra

25 MasterMind (1/3) Let’s play the game! © CS1101 (AY2009-2010 Semester 1)Week6 - 25

26 MasterMind (2/3) You will be given the following on the module website (“Resources” – “Lectures”). Look for “Week 6”, “MasterMind”.  Peg.java  You are not to modify this file.  MMCode.java  You are to complete the countSinks(MMCode) and countHits(MMCode) methods.  You should not change the other methods in the program.  MasterMindGUI.class  This is the GUI interface. You do not need the source code, but if you have problem with this class file, you may request for the source code so that you can compile it. .gif files  These are the gif files you need for the GUI interface.  MasterMind.java  This is the application program (with the main method). You are to complete this program. © CS1101 (AY2009-2010 Semester 1)Week6 - 26

27 MasterMind (3/3) Treat this as your holiday exercise!  This is actually a past year’s lab exercise. You may see the write-up on the module website, “CA – Labs”, under “Old Labs (AY2007/8 Semester 1)”, “Lab #4: Selection and Repetition II”. If you do not want the GUI features, just remove those statements in MasterMind.java which are suffixed with the comment “– GUI enhancement”. Note that the programs may contain some Java syntax/features not yet covered:  ‘this’, overloaded constructors, etc. These will be explained in the next lecture when we cover Chapter 7.  ‘char’ data type which is covered in Chapter 9. You may read up on your own. © CS1101 (AY2009-2010 Semester 1)Week6 - 27

28 Summary for Today Writing modular programs How to test your programs Using the debugger © CS1101 (AY2009-2010 Semester 1)Week6 - 28

29 Announcements/Things-to-do (1/2) Complete the following  MasterMind Take-home lab #3 deadline: 28 September 2009, Monday, 23:59hr. Next week is recess  Revise and prepare for mid-term test  Mid-term test on 3 October 2009, Saturday To prepare for next lecture  Read Chapter 7 and its PowerPoint file before you come for lecture. © CS1101 (AY2009-2010 Semester 1)Week6 - 29

30 Announcements/Things-to-do (2/2) Sit-in Lab #1  To be conducted during this week’s discussion session.  Please be punctual.  Make-up lab will only be allowed if you miss the lab with valid reason and proof.  Topics tested include everything you have learned.  Sit-in lab #1 constitute 5% of your final grade. © CS1101 (AY2009-2010 Semester 1)Week6 - 30 Happy Recess!

31 End of File © CS1101 (AY2009-2010 Semester 1)Week6 - 31


Download ppt "CS1101: Programming Methodology"

Similar presentations


Ads by Google