cis 234: preventing and removing bugs dr. ralph d. westfall may, 2010

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

Upload: zoe-palmer

Post on 01-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

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

CIS 234: Preventing and Removing Bugs

Dr. Ralph D. WestfallMay, 2010

Page 2: 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 "Pay me now, or pay me later!"

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

Error Handling/Debugging syntax errors logical errors good coding practices to minimize

errors testing your code

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

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

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

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)

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

Semicolon Problemspublic 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?

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

Curly Brace Problems in what % of YOUR code problems?public class SaySomething{{ // problem?

public static void main(String[] args){

System.out.println("Hi");{ // problem?

}}

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

CONSTANTS value must be assigned initiallypublic 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

*/

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

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?

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

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;}

}

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

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

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

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";

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

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();

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

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;

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

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?

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

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 declarationsEmployee boss;

followed by action code and instantiationsshirtsYear = shirtsDay * YEAR_DAYS; boss = new Employee(bossWages);

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

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

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

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

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

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

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

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

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

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?

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

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?

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

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

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

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)

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

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.

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

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

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

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

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

Class Method Example

public class This { // no constructorprivate static int factor = 2;public static double calcThis(int a) {

return 2 * factor; }

} // end of This.java code

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

Object Method Examplepublic class CreditCardMerchant{ // this class is designed to create objectsprivate 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

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

Object Method - 2

public CreditCardFee(int slips, double dollarAmount) // object constructor

{ this.slips = slips;

this.dollarAmount = dollarAmount; } // next slide

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

Object Method - 3public 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;

}}

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

"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"

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

"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

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

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

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

Types of Testing - 2 top down (system/integration testing)

use dummy coding ("stubs") for classes/methods that aren't completed yetSystem.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

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

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?

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

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)

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

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?

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

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)

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

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

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

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?

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

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?

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

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?

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

Review - 4 What does casting mean? Identify situations where you might

cast A double to an int? An int to a double?

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

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

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

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”