You are on page 1of 37

Testing and Debugging,

Refactoring and Code Review

1
Contents
• Testing fundamentals and test-case generation
• Debugging
• Simple refactoring
• Code reviews

2
Testing

3
Reflection
• Imagine you are cooking but bugs
(flies) keep falling in from the ceiling
• What do you do?
• check for bugs in the food you are
cooking
• testing
• keep lid closed
• defensive programming
• clean kitchen
• eliminate source of bugs (debugging)

4
Terms
• An error is a mistake made by a developer
• often a misunderstanding of a requirement or design specification
• A fault is a manifestation of that error in the code
• what we often call “a bug”
• A failure is an incorrect output/behaviour that is caused by
executing a fault
• The failure may occur immediately (crash!) or much, much later in the
execution
• Testing attempts to surface failures in our software systems
• Debugging attempts to associate failures with faults so they can
be removed from the system
• If a system passes all of its tests, is it free of all faults?
5
Testing
• Software testing is the process of evaluation a software item to detect
differences between given input and expected output
• Does it meet the specification?
• Is the program correct?
• How can I break my program?
 Verification: is the process to make sure the product satisfies the conditions
imposed at the start of the development phase. In other words, to make sure
the product behaves the way we want it to.
 Validation: is the process to make sure the product satisfies the specified
requirements at the end of the development phase. In other words, to make
sure the product is built as per customer requirements.

6
When?
• testing takes place at various stages of development in programming
• ensure code runs
• remove syntax errors
• remove static semantic errors
• C++ compliler can usually find these for you
• have a set of expected results
• an input set
• for each input, the expected output
• Include normal, abnormal, extreme, Boundary
• E.g course marks 65, 50 abc, -600, 1000 0,100 0,100 -1, 101
Test Case Description Input Expected Output Actual Result
1 Prints a comment when a mark 65 “Passed”
greater than 50 is entered

7
Classes of Testing
• Unit testing
• validate each piece of program
• testing each function separately (e.g test the product function)
• Regression testing
• Retesting what you had already tested after making changes
to the code
• catch reintroduced errors that were previously fixed
• Integration testing
• does overall program work?
• tend to rush to do this
• Acceptance testing, system testing, performance testing,
stress testing
8
Testing approaches
• black box testing
• explore paths through specification
• tester doesn't have any information about the internal
working of the software system.
• focuses on the behaviour of the software
• Can be applied to unit, integration, system, and
acceptance.
• White (Glass) box testing
• checks the internal functioning of the system
• explore paths through code
• testing is based on coverage of code statements, branches, int main() { }
paths or conditions
• assumes that the path of the logic in a unit or program
is known.

9
• designed without looking at the code
• can be done by someone other than the implementer to
avoid some implementer biases
• testing can be reused if implementation changes
• Paths through specification
• build test cases in different natural space partitions
• also consider boundary conditions (empty lists, singleton list,
large numbers, small numbers)

10
Glass Box Testing
• use code directly to guide design of test cases
• called path-complete if every potential path through code is
tested at least once
• what are some disadvantages of this type of testing?
• can go through loops arbitrarily many times
• missing paths
• guidelines
• Branches (exercise all parts of a conditional)
• for loops (loop not entered, body of loop executed exactly one, body
of the loop executed more than once)
• while loops (same as for loops)

11
Debugging

12
Debugging
• goal is to have a bug-free program
• Study events leading up to an error
• Why is it not working?
• How can I fix my program?
• Tools
• Desk checking (hand tracing)
• Using cout statement
• Use a debugger
13
Debugging Steps
• study program code
• don’t ask what is wrong
• ask how did I get the unexpected result
• is it part of a family?
• scientific method
• study available data
• form hypothesis
• repeatable experiments
• pick simplest input to test with

14
Debugging Error Messages -Easy
• forgetting to close parenthesis, quotation, etc.
• Mixing data types
• referencing a non-existent variable

15
Logical Errors : Challenging
• Think before writing new code
• Draw pictures, take a break
• Explain the code to
• someone else
• a rubber ducky (Imaginary person)

16
Debugging Do’s and Dont’s
• Write entire program • Write a function
• Test entire program • Test the function, debug the function
• Debug entire program • Write a function
• Test the function, debug the function
• Change code • Do integration testing
• Remember where bug was
• Test code • Backup code
• Forget where bug was or what change • Change code
you made • Write down potential bug in a comment
• Panic • Test code
• Compare new version with old version

17
Hand Tracing :Example 1
Debug the following pseudocode
L1: Program TotalPurchasePrice;
L2: Data Units as Integer;
L3: Data UnitPrice as Float;
L4: Data TotalPrice as Float;

L5: Input Units;


L6: Input UnitPrice;

L7: TotalPrice = Units + UnitPrice;

L8: Output “The Amount Payable is “,TotalPrice;

L9: End TotalPurchasePrice;

18
DeskDesk
Checking
checking for Example 1 would be documented as follows;

Line No. Units UnitPrice TotalPrice Comment

int units =0; L1 Start of the program TotalPurchasePrice


float unitPrice =0.0; L2 0 Data declaration of the variable: Units
float totalPrice =0.0; L3 0 0 Data declaration of the variable: UnitsPrice

L4 0 0 0 Data declaration of the variable: TotalPrice


cout<<"Enter number of Units \n"
L5 6 0 0 User Input: Units (6)
cin>>units;
L6 6 20 0 User Input: UnitsPrice (20)

L7 6 20 26 Data Manipulation: Units(6)+UnitPrice(20)=


cout<<"Enter the unit price \n"
TotalPrice(26)
cin>>unitPrice;
L8 6 20 26 Data Output: The Amount Payable is 26
totalPrice=units+unitPrice; L9 6 20 26 End of the program TotalPurchasePrice

cout<<"The amount payable is "<<totalPrice;

19
cout Statements
• good way to test hypothesis
• when to print
• enter function
• parameters
• function results
• use bisection method
• put print halfway in code
• decide where bug may be depending on values
20
Built in Debugger

21
Code Refactoring

22
What is Refactoring
• Its origin = Factoring
• In mathematics, factorization or factoring is the
decomposition of an object into an expression of smaller
objects, or factors, which multiplied together give the
original
• E.g , the number 15 factors into primes as 3 * 5; and the
polynomial x2 – 4 factors as (x - 2)(x + 2)
• Refactoring is the process of rewriting written material to
improve its readability or structure, with the explicit purpose
of keeping its meaning or behaviour

23
Software Refactoring
• “Restructuring existing code by altering its internal structure
without changing its external behavior” Martin Fowler
• Why? Improve code structure and design
• more maintainable
• easier to understand
• easier to modify
• easier to add new features

24
When to apply refactoring
• “Anyone can write code that a computer can understand. Good
programmers write code that humans can understand”
• Bad code smells:
• Duplicate code : (create a function)
• Complex control,
• Long method
• Comments in the middle of the method
• Complex data,
• Long parameter list (replace parameter with a function)
• OO specific: large class, switch statements, temporary fields, etc.
• you add new features and the code is brittle or hard to understand.
Refactoring makes this feature and future features easier to build.
• you fix bugs.
• during code review.

25
Example 1:
• Consolidate Duplicate Conditional Fragments
if (isSpecialDeal()) {
total = price * 0.95;
send()
} else {
total = price * 0.98;
send()
}
• becomes this
if (isSpecialDeal()) {
total = price * 0.95;
} else {
total = price * 0.98;
}
send();

26
Example 2:
• Replace Magic Number with Symbolic Constant
double potentialEnergy(double mass, double height) {
return mass * 9.81 * height;
}
• becomes this
double potentialEnergy(double mass, double height) {
return mass * GRAVITATIONAL_CONSTANT * height;
}
const double GRAVITATIONAL_CONSTANT = 9.81;

27
Refactoring Vs Optimization
• The purpose of refactoring is
• to make software easier to understand and modify
• contrast this with performance optimization
• again functionality is not changed, only internal structure;
• however performance optimizations often involve making
code harder to understand (but faster!)

28
Example 3
double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
===================================================================
if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;

double basePrice() {
return _quantity * _itemPrice;
}

29
Conclusion

• Refactoring is a useful technique for making non-functional


changes to a software system that result in
• better code structures
• less code
• Many refactoring's are triggered via the discovery of duplicated
code
• The refactoring's then show you how to eliminate the duplication
• Bad Smells
• Useful analogy for discovering places in a system suitable for
refactoring
30
Code Review

31
Code Review
• Code review (Peer Code Review) is careful, systematic study
of source code by people who are not the original author of
the code. It’s similar to proofreading a written piece of work
• Code review really has two purposes:
• Improving the code. Finding bugs, anticipating possible bugs,
checking the clarity of the code, and checking for consistency
with the project’s style standards.
• Improving the programmer. Code review is an important way
that programmers learn and teach each other, about new
language features, changes in the design of the project or its
coding standards, and new techniques
• Code review is widely practiced in open source projects
32
Why code review?
• When done correctly, peer reviews save time,
• restructuring the development process upfront and drastically reducing
the amount of work required later of Quality Assurance teams.
• Save costs, by identifying bugs that might go undetected through
testing and onto the end-users
• Promotes greater communication and companionship in
programmers work environment
• distribute the sense of "ownership" for any piece of code
• Serves as an educational tool for junior developers
• as senior colleagues demonstrate, through real instances, better ways to
write clean code, solve common problems with useful shortcuts, and
visually identify any number of potential trouble spots, such as memory
leaks, buffer overflows, or scalability issues.
33
Code Review Best Practices
• Set goals and standards
• decide important metrics and define unambiguous goals (e.g
acceptable coding standards)
• Communicate Goals and Expectations
• Easier for the team to make progress as a unit when everyone
is on the same page)
• Define a Code Review Process
• A defined code review process will help everyone stay on track
• Use a code review checklist
• Helps the reviewer to ensure nothing is missed out

34
Code Review Best Practices Cont.
• Authors should put comments in source code before the review
• Review for no more than 60 minutes at a time
• According to research, a reviewers efficiency reduces after 60 minutes
and some defects can go unnoticed
• Put in place a process for fixing defects
• A process brings about efficiency
• Promote a positive code review culture
• Encourage learning to solve faults instead of just pointing out mistakes
• Automate to save time

35
Code Review Techniques
• Instant Code Review
• the developer is writing code while the reviewer sits beside
reading the code simultaneously and correcting it on the go
• Ad-hoc (synchronous) Code Review /”Over the
Shoulder”
• the coder produces the code and then asks the reviewer to
review the code. The reviewer joins the coder at the screen,
reviews the code while discussing it, over the shoulder
• It’s the most commonly used process

36
Code Review Techniques Cont.
• Meeting Based Code Review
• coders complete their work, and a meeting is called. The whole tech
team sits, commenting, and attempting to improve the code together
• Least used and is a temporary process
• Tool Based Code Review
• once the code gets finished, the coder makes it available for others to
review.
• The reviewer will review the code on their screen commenting, or even
amending the errors in the codes.
• May require automated code review tools
• Click Here to View an Automated Tool sample
37

You might also like