cis 234: preventing and removing bugs dr. ralph d. westfall may, 2010
TRANSCRIPT
CIS 234: Preventing and Removing Bugs
Dr. Ralph D. WestfallMay, 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!"
Error Handling/Debugging syntax errors logical errors good coding practices to minimize
errors testing your code
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
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)
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?
Curly Brace Problems in what % of YOUR code problems?public class SaySomething{{ // problem?
public static void main(String[] args){
System.out.println("Hi");{ // problem?
}}
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
*/
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?
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;}
}
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
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";
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();
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;
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?
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);
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
Code Organization - 2 Spaghetti code is bad Ravioli code is better Lasagna code is good too
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
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
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?
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?
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
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)
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.
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
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
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
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
Object Method - 2
public CreditCardFee(int slips, double dollarAmount) // object constructor
{ this.slips = slips;
this.dollarAmount = dollarAmount; } // next slide
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;
}}
"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"
"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
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
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
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?
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)
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?
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)
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
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?
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?
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?
Review - 4 What does casting mean? Identify situations where you might
cast A double to an int? An int to a double?
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
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”