1 / 46

CIS 234: Preventing and Removing Bugs

CIS 234: Preventing and Removing Bugs. Dr. Ralph D. Westfall May, 2010. Two Ways to Handle Bugs. prevent them from happening use good design and coding practices takes longer initially fix them after they occur saves time initially costs much more in long run

betty_james
Download Presentation

CIS 234: Preventing and Removing Bugs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS 234: Preventing and Removing Bugs Dr. Ralph D. Westfall May, 2010

  2. Two Ways to Handle Bugs • prevent them from happening • use good design and coding practices • takes longer initially • fix them after they occur • saves time initially • costs much more in long run • "Pay me now, or pay me later!"

  3. Error Handling/Debugging • syntax errors • logical errors • good coding practices to minimize errors • testing your code

  4. Syntax Errors: Misspellings • Java keywords can be misspelled • els, fales, prinln • identifiers for variables, objects, etc. • capitalization: myObject != myobject • names and types must match declarations, otherwise you get a compiler error • can turn off some variable name checking in Visual Basic.NET, but NOT in Java

  5. Syntax: Control Structures • missing parts • semicolons, curly brackets, parentheses • missing break; in a switch statement • can cause errors in some situations • used deliberately in others • extra parts • duplicated open { or close } curly brackets • unnecessary semicolons (esthetic error)

  6. Semicolon Problems public TestAge(int age) ; • // semicolon kills method (won't compile) { if (age > 60) // don't put ; on this line retirement = (wages * 0.15); // needs ; else if (age > 55); // semicolon kills test retirement = (wages * 0.10); // always runs • result of these 5 lines?

  7. Curly Brace Problems • in what % of YOUR code problems? public class SaySomething {{ // problem? public static void main(String[] args) { System.out.println("Hi"); { // problem? }}

  8. CONSTANTS • value must be assigned initially public class Constantly { private static final int VALUE; // missing public static void main(String[] args) { System.out.println("Hi!"); } } /* in some languages can declare as constant and provide value later, but then can't change */

  9. Syntax: Methods & Variables • can't use a method as a property System.out.println = "Welcome"; • methods always have ( ), not = • shouldn't use a variable as a method • variables never have ( ) • int theQuantity; • int amount = theQuantity(); • // could this line ever work?

  10. Java Fluke? Actually Works! public class SaySomething { public static void main(String[] args) { int theNum; System.out.println("Hi"); theNum = theNum(); System.out.println(theNum()); } public static int theNum() { return 5; } }

  11. Method & Variable Errors - 2 • writing to a static (constant) property • Math.PI = 3.2; // 3.1416 too hard!! • not using correct syntax to create an object ________ total = new CalculateTotal(); OrderSlip mySlip = ______ OrderSlip(); // each of the above lines has // something different missing

  12. Logical Errors • division by variable equal to zero • int x; //member variable default • double total = 25; • double average = total/x; • average = total/(total – 25); • mismatch between variable types • e.g., can't do arithmetic with text • int result = 5/"hello";

  13. Type Conversions • if data is wrong type, may be able to change type so it's usable • convert JOptionPane inputs from strings • int itemsOrdered = Integer.parseInt(JOptionPane....); • convert DOS window inputs to characters char initial = (char)System.in.read();

  14. Casting to a Different Type • to avoid type conversion problems, can put a different type, in parentheses, in front of a variable (primitive or object) int a; double b = 4321142.243; a = (int) b;

  15. Need to Force to a Type • int ramAge = 4, consuelaAge = 3, total = 0, divisor = 2; • double average; • total = ramAge + consuelaAge; • average = total / divisor; • What is the result? • What might be a problem? • How could the problem be fixed?

  16. Good Coding Practices • organize your code within methods • all declarations at top (method or class) private static final int YEAR_DAYS = 362; • followed by object declarations Employee boss; • followed by action code and instantiations shirtsYear = shirtsDay * YEAR_DAYS; boss = new Employee(bossWages);

  17. Code Organization • calculate values in order in which they will be needed • keep related activities together, as much as possible • don't start calculating something, then something else, and then back to the other (avoid "spaghetti code", another) • do all calculations before printing

  18. Code Organization - 2 • Spaghetti code is bad • Ravioli code is better • Lasagna code is good too

  19. Coding Style • skip lines between sections (<10 lines?) • indent code • "pretty printing" loops and conditionals • for (int i = 0; i<= 10; i++) • { • if (item[i] < smallest) • smallest = item[i]; } //what does this code do? • recommendations from Java's creator: Sun

  20. Comments • use meaningful comments • use comments for things that you won't remember next day, week or month • /* • * comments on multiple lines • */ • // trailing comment on code line • Sun recommendations

  21. Use Meaningful Variable Names • identifier should tell what is in variable • should not have to guess String name1; //1st and/or last? String name2; // difference from above? String lastName; // why better?

  22. Variable Naming Conventions • in other programming languages, some people like to attach the data type to the front of the variable name • used to be popular at Microsoft • also known as "Hungarian notation" • this is NOT a common practice in Java • cultural issue between Microsoft and rest of world?

  23. Naming Conventions - 2 • 1-character convention from Visual Basic textbook (CIS 338) • nIndex 'an integer • sName 'text string • 3-character convention from ASP textbook (CIS 451) • intIndex 'an integer • strName 'text string

  24. Modularizing Code • use separate classes where appropriate, rather than one long program • use separate methods for common actions, rather than repeating code within main() or other methods • separate the code whenever a similar thing (similar lines) is done in 2 different places, or more than 2 times (unless lines are few)

  25. Modularizing Code - 2 • grouping similar activities into separate methods (or classes) is very common e.g., • 1-input, 2-calculations, 3-output • very specialized processing • high speed, extensive mathematical calculations, etc. • in video games, image processing, artificial intelligence, data mining, etc.

  26. Modular Code Advantages • shorter programs • easier to debug and maintain • 2 x 100 lines vs. 200 lines? • reusable classes available to other programs • students sometimes cut-and-paste code into a method • this loses many of modular advantages

  27. Class vs. Object Methods • need to create an object to run object methods • objects store data, and their methods use this data • should NOT create any objects to run class methods • use class methods when it isn't necessary to store the arguments for later use after a class method runs

  28. Class Method Example public class This { // no constructor private static int factor = 2;public static double calcThis(int a) { return 2 * factor; } } // end of This.java code

  29. Object Method Example public class CreditCardMerchant { // this class is designed to create objects private final double PER_SLIP_EXP = .20; private final double PER_DOLLAR = .02; private final double ANNUAL_FEE = 100.00; private int slips; private double dollarAmount; // next slide

  30. Object Method - 2 public CreditCardFee(int slips, double dollarAmount) // object constructor { this.slips = slips; this.dollarAmount = dollarAmount; } // next slide

  31. Object Method - 3 public double calcForProfitsAnnualFee() { // this method's code gets used by objects double forProfitsYearlyFee; yearlyFee = slips * PER_SLIP_EXP + dollarAmount * PER_DOLLAR + ANNUAL_FEE; //not on nonprofits return yearlyFee; } }

  32. "Seventh-Inning Stretch" • "The seventh-inning stretch is a tradition in baseball that takes place between the halves of the seventh inning of any game. Fans generally stand up and stretch out their arms and legs and sometimes walk around." Wikipedia"Take Me Out to the Ball Game"

  33. "Bullet-Proofing" Your Code • try to make it impossible for a user to enter bad data • write code that checks user inputs and rejects bad values • example: make it impossible to put in a zip-code longer than 5 digits • can do this in VB but not with Java • Java TextField component can't do, but can create a new class that inherits from it, or use a Formatted Text Field

  34. Types of Testing • beta – let users test it in typical operational situations • alpha – developers test code • their own employees (not programmers?) • alpha is first letter of Greek alphabet • alpha testing is supposed to happen before outside users (beta) test the system

  35. Types of Testing - 2 • top down (system/integration testing) • use dummy coding ("stubs") for classes/methods that aren't completed yet System.out.println("testing [identifier]"); return [typical value for other code to use]; • bottom up (unit testing) • use short, simple classes ("drivers") to test individual methods whose coding is (supposedly) completed

  36. Types of Testing - 3 • "black box" (specifications based) • test inputs and outputs based on what the program is supposed to do • testers might not know anything about code • "white box" ("glass box") • testing guided by looking at the code • which is better? why? how do I grade?

  37. Testing Your Code • you test the different ways a user could use the application (alpha testing) • what happens if user clicks OK button before entering any data in a JOptionPane? • what happens if user hits Enter key while in a JOptionPane? • get someone else to try it (beta testing)

  38. Testing Navigation Sequences • example: multi-level JOptionPane menus (Sun documentation) • two choices on first menu • three choices on first submenu • two choices on other submenu • how many navigation routes?

  39. Testing Possible Data Values • example: zip codes • boundary values (used or not?) • e.g., 00000 and 99999 • test loops to avoid "off by one" errors • values in between boundaries • 00001 to 99998 • out-of-bounds values • negative #s? 6 digit #s? • text #s? (e.g., seven)

  40. Exercise: Create a Test Plan • Project 3 application class • uses menus to decide what to do • calculates totals, uses methods to create objects and calculate data, prints results • write down list of steps that you think would be adequate to test navigation • indicate reasons for each test and possible ways code could fail

  41. Review • What is the difference between syntax and logical errors? • Which are generally more dangerous? • Misspelling causes which type of error? • Curly brace problems • They are easy to find? T or F? • They always show close to the missing or extra curly brace? T or F?

  42. Review - 2 • What happens when you divide an integer by zero (also an integer)? • Is this a syntax error? • How does “pay me now or pay me later” relate to software development?

  43. Review - 3 • What is wrong with the following code? if(a==b); x = 2; • How many times can the value of a constant: • Be assigned? • Be changed?

  44. Review - 4 • What does casting mean? • Identify situations where you might cast • A double to an int? • An int to a double?

  45. Review - 5 • Connect matching items: method () (draw lines) property = • Provide an example of a good coding practice • What does “modularizing code” mean? • To use a class method, you need to create an object from the class? T or F

  46. Review - 6 • What is the difference between alpha and beta testing? • What does “bulletproofing” mean? • Give an example • Give an example of a “boundary value”

More Related