Presentation is loading. Please wait.

Presentation is loading. Please wait.

Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 5 Last time: –Method Overloading –Arrays –A few useful classes in Java: System Wrapper classes String.

Similar presentations


Presentation on theme: "Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 5 Last time: –Method Overloading –Arrays –A few useful classes in Java: System Wrapper classes String."— Presentation transcript:

1 Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 5 Last time: –Method Overloading –Arrays –A few useful classes in Java: System Wrapper classes String class StringTokenizer ArrayList

2 Summer 2007CISC121 - Prof. McLeod2 You Should Be: Getting your assn 1 marks soon. Nearly finished Exercise 2.

3 Summer 2007CISC121 - Prof. McLeod3 You Will Need To: Finish Assn 2 by Thursday.

4 Summer 2007CISC121 - Prof. McLeod4 Today Encapsulation Javadoc Testing and Debugging (some slides for reading?)

5 Summer 2007CISC121 - Prof. McLeod5 Encapsulation An OOP programming technique that: –Supports the re-usability of code. –Provides a well-defined user interface. –Builds into an Object the code that ensures the integrity of the data stored in the Object by: Making sure that initial data values are “legal”. Controlling (or preventing) changes to data. Preventing “privacy leaks” when data is returned out of an Object. –Works well with modular design practices making code easier to write, test and debug.

6 Summer 2007CISC121 - Prof. McLeod6 Encapsulation, Cont. This is the driving principle for the design of all Objects in the Java API! –So, maybe you should design your own Objects using the same principle? Java API Your class

7 Summer 2007CISC121 - Prof. McLeod7 An Example Suppose you want to create a database to store records of Halloween visits. For each year, you wish to record: –Number of munchkins banging at your door. –Outdoor temperature in deg C. –Weather condition – “rain”, “snow”, or “clear”. You could create three arrays for each of the fields. –Difficult to code when moving records around…

8 Summer 2007CISC121 - Prof. McLeod8 An Example, Cont. It would be easier to create an Object that contains these three fields and then design a collection of these Objects. –No way the fields could get out of order since moving a record moves all fields at once. The collection could be an array, an ArrayList or some other structure. So, how to design an Object to hold this information?

9 Summer 2007CISC121 - Prof. McLeod9 Halloween1 public class Halloween1 { public int numMunchkins; public int temperature; public String weatherCondition; } // end Halloween1

10 Summer 2007CISC121 - Prof. McLeod10 Halloween1, Cont. In the main method in some other class: Halloween1[] hwDB = new Halloween1[100]; hwDB[0] = new Halloween1(); hwDB[0].numMunchkins = 200; hwDB[0].temperature = 10; hwDB[0].weatherCondition = "rain";

11 Summer 2007CISC121 - Prof. McLeod11 Halloween1, Cont. Or with an ArrayList : ArrayList hwDBA = new ArrayList (); Halloween1 hw = new Halloween1(); hw.numMunchkins = 200; hw.temperature = 10; hw.weatherCondition = "rain"; hwDBA.add(hw);

12 Summer 2007CISC121 - Prof. McLeod12 Halloween1, Cont. A question: Why not declare the attributes in Halloween1 static ?

13 Summer 2007CISC121 - Prof. McLeod13 Halloween1, Cont. Another question: What is wrong with the following?: hwDB[1] = new Halloween1(); hwDB[1].numMunchkins = -200; hwDB[1].temperature = 100; hwDB[1].weatherCondition = "frogs";

14 Summer 2007CISC121 - Prof. McLeod14 Halloween1, Cont. The object, hwDB[1] is not particularly realistic. How can we prevent the creation of an object like this? Who is responsible for checking for realistic, or “legal” values for the attributes? The Halloween1 class or the class that uses it? Where is it easiest to put these checks?

15 Summer 2007CISC121 - Prof. McLeod15 Encapsulation, Cont. Attributes must be declared private, so that the class that owns them can control how they are set. If attributes are private then how can a user of the class assign the values of the attributes? Through methods, of course! –Constructor(s) –Mutator(s)

16 Summer 2007CISC121 - Prof. McLeod16 Encapsulation, Cont. Within these methods, you can write code to check the parameters for validity. What do you do if the values are not legal? Throw an exception!

17 Summer 2007CISC121 - Prof. McLeod17 Defining Exceptions You can throw an exception already defined in java, but: Most of the time you will want to throw your own exception objects. Why not? It’s easy! See the next slide for the definition of an Exception object. (Please ignore indentation and line wrapping…)

18 Summer 2007CISC121 - Prof. McLeod18 Defining Exceptions, Cont. public class IllegalHalloweenParametersException extends Exception { public IllegalHalloweenParametersException() { super("Illegal parameter value supplied to Halloween object."); } public IllegalHalloweenParametersException(String message) { super(message); } } // end IllegalHalloweenParametersException

19 Summer 2007CISC121 - Prof. McLeod19 Defining Exceptions, Cont. Inside a method that detects an illegal parameter: throw new IllegalHalloweenParametersException("Illegal number of kids."); At the end of the method header that contains the above line of code: … throws IllegalHalloweenParametersException {

20 Summer 2007CISC121 - Prof. McLeod20 Defining Exceptions, Cont. This example contains a few Java keywords that we have not yet discussed: –extends –super –throw –throws The exact meaning and usage of extends and super is beyond CISC121, but you can still write your own exceptions by following the provided pattern!

21 Summer 2007CISC121 - Prof. McLeod21 Assigning Private Attributes - Constructor Methods Constructors are special methods that have the same name as the class in which they reside, but have no return type (not even void ). They must be public. They are only executed once, when the object is being instantiated. You can’t invoke them later. Constructors are often overloaded. This means you can have many constructors with different parameter lists. Why do that?

22 Summer 2007CISC121 - Prof. McLeod22 Halloween2 Halloween2.java uses a constructor to set all parameters. It also throws an exception if illegal values are encountered. See how this object is used in TestHalloween2.java. Note that this class is not complete – it only has the one constructor, for now.

23 Summer 2007CISC121 - Prof. McLeod23 Assigning Private Attributes - Constructor Methods, Cont. Note that once you have written a constructor with parameters, you can no longer use a constructor without any parameters, called the default constructor. If you want an empty constructor, you must write one yourself, in addition to the parameterized constructor(s). Why would you want an empty constructor?

24 Summer 2007CISC121 - Prof. McLeod24 Assigning Private Attributes - Constructor Methods, Cont. Suppose you don’t want to have to force the user to supply all parameters when he instantiates the object? How are you going to do this? Suppose you want to edit parameters after you have created the object? How are you going to do this, too? Overload the constructors. Provide mutator(s).

25 Summer 2007CISC121 - Prof. McLeod25 Assigning Private Attributes - Mutator Methods Called “set” methods – in fact, by convention, the word “set” is the first word in the method name. These methods must also check for legal parameters. Usually the constructor invokes mutators, when they exist. Should you write a mutator for each parameter?

26 Summer 2007CISC121 - Prof. McLeod26 Halloween3 Has overloaded constructors. Has mutators. A Halloween3 object can be created with or without the weather condition, but must have both the number of munchkins and the temperature. All parameters can be changed later. (Is still not yet complete…)

27 Summer 2007CISC121 - Prof. McLeod27 Halloween3, Cont. Note how the constructor invokes the mutators. Mutators and constructors can throw the exception. Note how the second, 2 parameter constructor uses the this keyword to invoke the three parameter constructor. Note how the second constructor has to make an assumption for the value of weatherCondition ( “unknown” ). Can you create an empty Halloween3 object?

28 Summer 2007CISC121 - Prof. McLeod28 Aside, The this Thing Can be used to supply a reference to the current object in that object’s code. this means “myself”. (When you invoke a method inside the same class, the compiler adds an implicit this keyword to each of those invocations.)

29 Summer 2007CISC121 - Prof. McLeod29 Accessors We have some useful ways to assign attributes, but how about getting them back out again? Accessor methods return the value of an attribute. By convention, accessor methods start with the word “ get ”. One accessor per attribute. For example: public int getNumMunckins () { return numMunchkins; } // end getNumMunchkins Accessor

30 Summer 2007CISC121 - Prof. McLeod30 Accessors, Cont. These are pretty simple methods. Except when you are returning an object. Suppose we measured the temperature every hour and stored the values in an array of int[] called hourlyTemps. What is wrong with the following? public int[] getHourlyTemps { return hourlyTemps; } // end getHourlyTemps Accessor

31 Summer 2007CISC121 - Prof. McLeod31 Accessors, Privacy Leaks Could the method receiving the pointer to the array hourlyTemps change the contents of the array? How else can you do this?

32 Summer 2007CISC121 - Prof. McLeod32 Accessors, Privacy Leaks, Cont. public int[] getHourlyTemps { int[] temp = new int[hourlyTemps.length]; for (int i = 0; i < hourlyTemps.length; i++) temp[i] = hourlyTemps[i]; return temp; } // end getHourlyTemps Accessor

33 Summer 2007CISC121 - Prof. McLeod33 Accessors, Privacy Leaks, Cont. Or: public int[] getHourlyTemps { return hourlyTemps.clone(); } // end getHourlyTemps Accessor clone() is the only method that an array has. It creates a deep (or non-aliased) copy of an array. Either of these methods would prevent privacy leaks.

34 Summer 2007CISC121 - Prof. McLeod34 Other Standard Methods –toString() –equals() –compareTo() –clone() These are all properly coded in the, now complete, Halloween4 class. –It also contains Javadoc comments, which you can ignore for now.

35 Summer 2007CISC121 - Prof. McLeod35 toString() Method As it is, if we try to print a Halloween object, we will just get “gobbldeygook”: Halloween2@923e30 (This String is composed of the object type and its hash code…) So, to get a more useful view of the contents of the object, define a toString() method that returns a String.

36 Summer 2007CISC121 - Prof. McLeod36 toString() Method, Cont. This method will be called automatically whenever a String version of the object is needed. (It overrides the toString() method from the parent Object class…) You decide on how you want to represent your object as a String. See the method in Halloween4, for example:

37 Summer 2007CISC121 - Prof. McLeod37 In Halloween4: public String toString () { String s = numMunchkins + " kids, "; s += temperature + " deg C. and "; s += weatherCondition + "."; return s; } // end toString

38 Summer 2007CISC121 - Prof. McLeod38 In TestHalloween4 For example, the code: System.out.println(hwDB[0]); Would print out: 200 kids, 10 deg C. and clear. Note that you don’t need an explicit toString() call (but you can, if you want).

39 Summer 2007CISC121 - Prof. McLeod39 equals() Method Accepts another object of type Halloween4 and returns true of they are equal, false otherwise. You get to define what “equality” means. (Usually all the attributes have to match.) Remember why you cannot use == to compare objects?

40 Summer 2007CISC121 - Prof. McLeod40 equals() Method, Cont. Two ways to write an equals() method (both will return true or false ): –Accept a Halloween4 object as a parameter. –Accept an Object as a parameter ( Object is the base class for all objects in Java!) The proper way is the second one – then you will overwrite the equals() method inherited from the base, Object class (just take my word for this!). (Outside the scope of CISC121, again…)

41 Summer 2007CISC121 - Prof. McLeod41 equals() Method, Cont. public boolean equals (Object otherObject) { if (otherObject instanceof Halloween4) { Halloween4 otherH = (Halloween4)otherObject; return numMunchkins == otherH.numMunchkins && temperature == otherH.temperature && weatherCondition.equalsIgnoreCase (otherH.weatherCondition); } // end if return false; } // end equals

42 Summer 2007CISC121 - Prof. McLeod42 equals() Method, Cont. The instanceof keyword checks to see if the supplied Object is indeed a Halloween4 object before it attempts to cast it. Treat this code like the code you saw for the Exception class – follow the formula, and it will work!

43 Summer 2007CISC121 - Prof. McLeod43 compareTo() Method Compares a supplied Halloween4 object with the current one, based on your comparison criteria. It returns an int value. (Like the compareTo() method in the String class.) You have to decide on the basis for comparison. For Halloween4 you could just use numMunchkins, for example.

44 Summer 2007CISC121 - Prof. McLeod44 compareTo() Method, Cont. The base Object class does not have this method, so you don’t have to worry about writing one to take an Object as a parameter.

45 Summer 2007CISC121 - Prof. McLeod45 clone() Method Returns a deep copy of the current object. Pretty easy for our Halloween4 object since it only stores primitive types and an immutable object. See Halloween4.java for a complete version of the Halloween object!

46 Summer 2007CISC121 - Prof. McLeod46 Javadoc Javadoc.exe is a program that comes with the JDK. (It is in the same directory as javac.exe and java.exe). If I have written a class, “ MyClass.java ”, that contains properly formatted comments (more below), then running “ javadoc MyClass.java ” generates a file “ MyClass.html ”. The html file contains external documentation generated from the formatted comments in the source code.

47 Summer 2007CISC121 - Prof. McLeod47 Javadoc - Cont. Normal block comments in Java are delimited by “ /* ” and “ */ ”. Everything between these delimiters, usually multiple lines, is a comment. Javadoc block comments are delimited by “ /** ” and “ */ ”.

48 Summer 2007CISC121 - Prof. McLeod48 Javadoc - Cont. The general form of a Javadoc comment: /** * Summary sentence. * More general information about the * class, attribute or method which * follows the comment, using as many lines * as necessary. (html tags can be included) * * javadoc tags to specify more specific * information, such as parameters and * return values for a method */

49 Summer 2007CISC121 - Prof. McLeod49 Javadoc - Cont. The general form of a Javadoc tag is: @tagName comment The tags you use depend on what you are describing (class, method or attribute). In the case of methods, you can have a tag for each parameter, the return value, and a tag for each thrown exception. Eclipse (really nice!!) will generate a blank tag for you after you type “ /** ”. Typically, you will only write javadoc comments for public attributes and methods…

50 Summer 2007CISC121 - Prof. McLeod50 Common Javadoc Tags @paramParameter_name description @throwsException_name description @returndescription @seepackageName.ClassName, packageNamme.ClassName#methodName, etc. @author @version

51 Summer 2007CISC121 - Prof. McLeod51 Javadoc - Cont. Html tags can also be added to the comments to add more formatting to the resulting document: – for emphasis – for code font – for images – for bulleted lists –Etc…

52 Summer 2007CISC121 - Prof. McLeod52 Javadoc Reference The best reference for javadoc is at: http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/

53 Summer 2007CISC121 - Prof. McLeod53 Javadoc - Cont. The output from Javadoc looks exactly like the API documentation you have already seen - since that is the way it has been generated! The advantage is that when source code is changed, the Javadoc comments can be changed in the source, at the same time. The external documentation is then easily re-generated. Javadoc also provides a consistent look and feel to these API documents.

54 Summer 2007CISC121 - Prof. McLeod54 Javadoc - Cont. Most modern IDE’s (like JBuilder and Eclipse) allow you to run Javadoc from within the environment, and provide tools and wizards to help you create comments. For example, in Eclipse, select “Project”, then “Generate Javadoc…”. Halloween4 is fully commented using javadoc style comments, for example. Let’s have a look and then generate the documentation.

55 Summer 2007CISC121 - Prof. McLeod55 Class Structure, Summary Private attributes (or fields). Constructor(s). Mutators and Accessors. toString(), equals(), compareTo(), clone() All public methods and attributes documented using Javadoc.

56 Summer 2007CISC121 - Prof. McLeod56 Variations on a Theme… This class structure is followed by every class in Java. Some classes don’t need all the pieces. For example: –Attributes but no mutators. –No attributes – then you don’t need constructors, mutators or accessors. (This class is probably just composed of utility methods, maybe all static.) –An object that will never be part of a collection – you might not need equals or compareTo. –A class that just has a main method. This is just the starting point of a program – possibly no other methods are required.

57 Summer 2007CISC121 - Prof. McLeod57 Three Quotes on Testing Kent Beck: “Optimism is the occupational hazard of programming; testing is the treatment.” Brian Marick: “The first mistake people make is thinking that the testing team is responsible for assuring quality.” Me: “Don’t rely on testing to make good code out of bad – write your best code from the beginning!”

58 Summer 2007CISC121 - Prof. McLeod58 Testing – Some Definitions Reliability – A measure of how well a system conforms to its specifications. Software Reliability – The probability that a software system will not cause system failure for a specified time under specified conditions (IEEE982-1989). Failure – Is any deviation of the observed behaviour from the specified bahaviour. Erroneous State (or Error!) – The system is in a state where further processing will lead to failure.

59 Summer 2007CISC121 - Prof. McLeod59 Testing – Some Definitions, Cont. Fault (or Defect or “Bug”) Cause of erroneous state. The goal of Testing is to discover as many faults as possible, allowing them to be corrected in order to increase the reliability of the system. Testing is the systematic attempt to find faults in a planned way, NOT the process of demonstrating that faults are not present.

60 Summer 2007CISC121 - Prof. McLeod60 Verification and Validation Testing is part of Verification and Validation: Verification is a set of activities used to make sure that the software correctly implements a certain function. Validation is the process of making sure that the system matches the established requirements. Verification – “Are we building the product right? Validation – “Are we building the right product?

61 Summer 2007CISC121 - Prof. McLeod61 Fault Detection Techniques A Review – Manual inspection of the system’s code without executing it. Two kinds of Reviews: –A Walkthrough – the review team comments, informally, on how the code relates to use cases and other analysis documents. –An Inspection – More formal. Done without the developer present. Check the code against requirements, non-functional requirements and design goals. Check for efficiency. Check documentation and style. Tough on the developer!, but it has been shown that 85% of faults are found during Review.

62 Summer 2007CISC121 - Prof. McLeod62 Fault Detection Techniques, Cont. Debugging –Locate a fault starting from an unplanned failure. –Concerned with faults and performance issues. Testing –Try to create failures in a planned way. –A successful test is one that causes the system to fail!

63 Summer 2007CISC121 - Prof. McLeod63 More Definitions… A Component is the class, the cluster of classes, the package or one or more subsystems that is being tested. A Test Case is a set of inputs and expected results that exercises a component with the purpose of causing failures and detecting faults. A Test Stub is partial implementation of a component upon which the component being tested depends. A Test Driver is a partial component that depends on the component being tested. –Stubs and Drivers allow the component to be harnessed – isolated from the rest of the system.

64 Summer 2007CISC121 - Prof. McLeod64 More Definitions, Cont. A Correction is a change to a component made to repair a fault. A correction can introduce new faults… “Round and round we go – where we’ll stop nobody knows!”

65 Summer 2007CISC121 - Prof. McLeod65 More Definitions, Cont. A system that fails after a correction has regressed. Carrying out the previous set of integration tests again is called Regression Testing.

66 Summer 2007CISC121 - Prof. McLeod66 Test Cases You must select a range of values to fully test your code. This may take many tests! The selection of the set of test values is something of an art: –Every statement in the code must be exercised at least once. –Make sure every if and while statement is evaluated to both a true and a false result. –Test each label of a switch statement. –Test with a minimum and a maximum “legal” input value for each parameter in turn.

67 Summer 2007CISC121 - Prof. McLeod67 Test Cases, Cont. –Test with a few “normal” values. –If the code is supposed to handle “illegal” input values, then test with a slightly illegal value (like being “slightly pregnant”…) and a highly illegal value (jail time…). –If the code has loops see if you can construct a set of test values for which the loop will not execute. –See if you have values within the code that represent composite values derived using a number of your input parameters. Select test values to see if you can “blow up” this composite value. –Test any conditions or design specs that the code is supposed to handle.

68 Summer 2007CISC121 - Prof. McLeod68 Test Cases, Cont. If you are finding that you have to write an excessive number of test cases to test a single method, then maybe that method is too large? Always walk through the code in your head first before going to testing. Document the tests performed and their results. If you find one particular area providing errors - it may be time to re-write that code. Complete the test set of values, even if you have encountered errors in your code - a few extra tests may help to confirm the location of the error.

69 Summer 2007CISC121 - Prof. McLeod69 Testing Tools The driver and stub code that you write. Results Comparators - Allow for automated comparison of results to expected results. Test Data Generators - Automated generation of a range of test values, including random values in the “legal” range. Coverage Monitors - Reports on which parts of the code are exercised by your tests. Symbolic Debuggers - Usually part of the development environment. Allows you to establish break points in the program, run the program step by step, and to watch the values of selected variables. System Perturbers - Simulates OS and/or hardware problems such as running out of memory or memory failure.

70 Summer 2007CISC121 - Prof. McLeod70 Testing, Cont. Testing alone does not guarantee that your program does what it was designed to do: “Testing can show the presence of errors, but never their absence.” In other words, you can never test every possibility. Often you will need to use another technique in conjunction with testing to prove “correctness”. –This technique is accomplished by using assertions and invariants to prove correctness by a logical means.

71 Summer 2007CISC121 - Prof. McLeod71 Testing, Cont. - An Example A method to test the dimensions of a triangle: –“equilateral” if all sides are equal –“isosceles” if two sides are equal –“scalene” if no sides are equal Can you spot the logic error in the following method? (the syntax is fine) (OK to assume that only positive int ’s are used, and that the three values will form a triangle.)

72 Summer 2007CISC121 - Prof. McLeod72 public static String testTriangle (int a, int b, int c) { if (a == b) { if (b == c) { return "equilateral"; } else { return "isosceles"; } else { if (b == c) { return "isoscles"; } else { return "scalene"; } } //end testTriangle

73 Summer 2007CISC121 - Prof. McLeod73 Testing, Cont. - An Example - Cont. Devise test cases to exercise each branch of the method’s if statements, and run them from a main method driver program: System.out.println("2, 2, 3: " + testTriangle(2,2,3)); System.out.println("2, 2, 2: " + testTriangle(2,2,2)); System.out.println("1, 2, 2: " + testTriangle(1,2,2)); System.out.println("1, 2, 3: " + testTriangle(1,2,3));

74 Summer 2007CISC121 - Prof. McLeod74 Testing, Cont. - An Example - Cont. Output: 2, 2, 3: isosceles 2, 2, 2: equilateral 1, 2, 2: isoscles 1, 2, 3: scalene

75 Summer 2007CISC121 - Prof. McLeod75 Looks OK, right? (We have exercised every branch of the program without finding an error!) What about: System.out.println("1, 2, 1: " + testTriangle(1,2,1)); Output: 1, 2, 1: scalene Ooooops!! Testing, Cont. - An Example - Cont.

76 Summer 2007CISC121 - Prof. McLeod76 Testing, Cont. - An Example - Cont. The method does not test for (a == c). So, even though we built our test cases correctly and exercised all the code, the logic error was not found. Suppose we tested with a large set of random numbers instead. (Naturally I tried it…)

77 Summer 2007CISC121 - Prof. McLeod77 Testing, Cont. - An Example - Cont. With sets of three random int ’s between 1 and 100 it takes between about 50 and 200 sets before this particular error is encountered. Using a range of 1 to 1000 it takes between 200 and 300 sets before the error is encountered. So maybe, even an automated testing program which generates random tests would not have found this error. Soon, I will show that the use of assertions and invariants (a fancy way of “walking through” the code) would have shown the error.

78 Summer 2007CISC121 - Prof. McLeod78 Debugging - Error Types Three kinds of errors: –Syntax Errors Improper use of the Java language. The compiler (and pre-compiler) will pick these up and prevent your program from running - so they are fairly easy to correct. Sometimes syntax errors “cascade” and many error messages are given. Fix the first one or two syntax errors and ignore the rest of the error messages. Note some programming languages will give error “warnings”, but still run your program. It is never a good idea to ignore these warnings for too long!

79 Summer 2007CISC121 - Prof. McLeod79 Debugging - Error Types - Cont. –Runtime Errors Program crashes when run. Your code compiles OK, but will not run properly. Typical causes are out-of-range errors, memory overflow, infinite loops, and file problems. These errors are usually easy to reproduce, and not too difficult to fix.

80 Summer 2007CISC121 - Prof. McLeod80 Debugging - Error Types - Cont. –Logic Errors Your program is working fine, but is not doing what it is supposed to do - results are not valid. Or, it works OK sometimes, but crashes, or produces invalid results under other conditions. Errors are more difficult to reproduce. Hardest “bugs” to find!

81 Summer 2007CISC121 - Prof. McLeod81 Debugging - Cont. How NOT to debug (I do it this way all the time): –Scatter random println statements throughout the offending code. Keep moving them around until you have a pretty good idea of where the error is by looking at the output. –Don’t worry about why the error is taking place, just change what might be the offending line and run it again to see if it is fixed. –Don’t change test cases to see if the fix is universal or only works for the first test case that failed before. –It is OK to make multiple fixes at once if you are pretty sure that they will all be necessary. –Don’t bother keeping track of the changes, you can easily remember them and how the code looked before you started messing with it… (yah, right!!)

82 Summer 2007CISC121 - Prof. McLeod82 Debugging - Cont. The only worse thing you can do is to assume that you will never code an error and not test at all! The above technique will work sometimes, but to use it you should first decide how long you are going to give this “trial and error” approach to work, before trying something else. Oh, and back up your program to a separate file before you “go to it”…

83 Summer 2007CISC121 - Prof. McLeod83 Aside - Version Tracking in Eclipse You can right click on a file name and choose “Replace with” followed by “Previous from Local History” or “Local History…” to view the saved history of your changes. You can alter the number of changes tracked in Preferences (“General” then “Workspace” then “Local History”). Don’t forget that only a finite number of changes are tracked – don’t rely on this feature to make up for you not keeping track of your changes!

84 Summer 2007CISC121 - Prof. McLeod84 Debugging - Cont. Consider trying a more “scientific approach” to debugging: –Make sure you understand the exact conditions that cause the error. Can you reproduce the error? –Continue to test until you have a good idea of what kind or range of input causes the error. –Form a “hypothesis” about where the error is. Design a specific test case or inspect the code to confirm the hypothesis, or form another one. –Fix this one error. –Test the fix. –Look for similar errors in the code. –Learn from the error, so maybe next time you won’t write it into the code!

85 Summer 2007CISC121 - Prof. McLeod85 Debugging - Cont. Finding the error is 90% of the work. If you are having problems finding the bug: –Run more and different tests. –Try reproducing the error in different ways. –Divide the code into smaller pieces, if you have been testing a large program, and test them separately. –Check code that has been changed recently. –Don’t get into a mindset that the error can only be in a certain location (like code written by someone else…) –Talk to someone else. –Take a break and let your subconscious have a try. –Send the code to your TA. (“community support” in other words.) –Send the code to your Prof! (obviously, a last resort…)

86 Summer 2007CISC121 - Prof. McLeod86 Debugging - Cont. Fixing the error: –Run a specific test case or do a thorough walk-through of the bad code to confirm that this is the error. –Take your time - never debug “standing up”! –Save the original source code before making any changes. –Fix the problem, not the symptom! –Don’t make random changes just to see if it works, make sure you have a reason and understand why you are changing the code.

87 Summer 2007CISC121 - Prof. McLeod87 Debugging - Cont. Fixing the error, cont.: –Make one change at a time! –Re-test after you have made the one fix. Test the larger program to see if there is any “domino effect” from your change. –Sometimes, especially after multiple bug fixes, you may have to face the choice of completely re-writing a section of code… –Document all changes in your code, and change any other comments so that they are current with the code. (You might even comment out the old code, in case your fix does not work.) –Look for similar errors.

88 Summer 2007CISC121 - Prof. McLeod88 Debugging - Cont. If you write well documented code in the first place, using good style techniques, your code will be much easier to fix. Code Development Documentation consists of: –Regular internal documentation (method descriptions don’t have to be too complete). –Comments that stand out where you are not sure of your code. –Comments where you have made any changes, what the change is, and when it was made. Maybe even include the old code as a comment. –A version history. –If multiple authors, “initial” the changes you make.

89 Summer 2007CISC121 - Prof. McLeod89 Debugging - Cont. Debugging tools: –Compiler Warnings –Source Code Comparator - can point out differences between versions of your program. –Extended Syntax and Logic Checkers - Can test your code in more detail than the compiler. –Execution Profiler - Tells you how long your code is taking to execute - you may find unexpected bottle- necks! –Driver and stub codes. –Debuggers. But, don’t rely on them! A debugging tool can become a crutch - preventing you from learning good coding style in the first place.

90 Summer 2007CISC121 - Prof. McLeod90 Aside – Debugging in Eclipse If you have not used Debug before – the “Debug Perspective” button will not show up at the top right. To use debug mode, you must put a breakpoint into your program, by left-clicking on the bar at the left of your program, and choosing “Toggle Breakpoint”. Then choose “Debug As” followed by “Java Application”.

91 Summer 2007CISC121 - Prof. McLeod91 Debugging in Eclipse, Cont. Now you are in the “Debug Perspective”! Lots of fun things to do here! –You can examine the current contents of variables and objects. –You can continue your program one line of code at a time. –etc.!


Download ppt "Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 5 Last time: –Method Overloading –Arrays –A few useful classes in Java: System Wrapper classes String."

Similar presentations


Ads by Google