• Non ci sono risultati.

Programmazione Avanzata Vittorio Ruggiero

N/A
N/A
Protected

Academic year: 2021

Condividi "Programmazione Avanzata Vittorio Ruggiero"

Copied!
289
0
0

Testo completo

(1)

Programmazione Avanzata

Vittorio Ruggiero

(v.ruggiero@cineca.it)

Roma, Marzo 2017

(2)

Outline

Bugs and Prevention Testing

Static analysis Run-time analysis Debugging

Parallel debugging

(3)

As soon as we started programming, we found to our surprise that it wasn’t as easy to get programs right as we had thought.

Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.!

Maurice Wilkes discovers debugging, 1949.

(4)

Testing-Debugging

I TESTING: finds errors.

I DEBUGGING: localizes and repairs them.

TESTING DEBUGGING CYCLE:

we test, then debug, then repeat.

Program testing can be used to show the presence of bugs, but never to show their absence!

Edsger Dijkstra

(5)

Testing-Debugging

I TESTING: finds errors.

I DEBUGGING: localizes and repairs them.

TESTING DEBUGGING CYCLE:

we test, then debug, then repeat.

Program testing can be used to show the presence of bugs, but never to show their absence!

Edsger Dijkstra

(6)

What is a bug?

I Defect: An incorrect program code

=⇒a bug in the code.

I Infection: An incorrect program state =⇒ a bug in the state.

I Failure: An osservable incorrect program behaviour =⇒ a bug in the behaviour.

(7)

What is a bug?

I Defect: An incorrect program code =⇒ a bug in the code.

I Infection: An incorrect program state =⇒ a bug in the state.

I Failure: An osservable incorrect program behaviour =⇒ a bug in the behaviour.

(8)

What is a bug?

I Defect: An incorrect program code =⇒ a bug in the code.

I Infection: An incorrect program state

=⇒a bug in the state.

I Failure: An osservable incorrect program behaviour =⇒ a bug in the behaviour.

(9)

What is a bug?

I Defect: An incorrect program code =⇒ a bug in the code.

I Infection: An incorrect program state =⇒ a bug in the state.

I Failure: An osservable incorrect program behaviour =⇒ a bug in the behaviour.

(10)

What is a bug?

I Defect: An incorrect program code =⇒ a bug in the code.

I Infection: An incorrect program state =⇒ a bug in the state.

I Failure: An osservable incorrect program behaviour

=⇒a bug in the behaviour.

(11)

What is a bug?

I Defect: An incorrect program code =⇒ a bug in the code.

I Infection: An incorrect program state =⇒ a bug in the state.

I Failure: An osservable incorrect program behaviour =⇒ a bug in the behaviour.

(12)

Infection chain

Defect

=⇒Infection=⇒Failure

I The programmer creates adefectin the program code (also known as bug or fault).

I Thedefectcauses an ininfectionin the program state.

I Theinfectioncreates afailure- an externally observable error.

(13)

Infection chain

Defect=⇒Infection

=⇒Failure

I The programmer creates adefectin the program code (also known as bug or fault).

I Thedefectcauses an ininfectionin the program state.

I Theinfectioncreates afailure- an externally observable error.

(14)

Infection chain

Defect=⇒Infection=⇒Failure

I The programmer creates adefectin the program code (also known as bug or fault).

I Thedefectcauses an ininfectionin the program state.

I Theinfectioncreates afailure- an externally observable error.

(15)

Tracking down defect

Defect⇐=Infection⇐=

Failure

I AFailureis visible to the end user of a program. For example, the program prints an incorrect output.

I Infectionis the underlying state of the program at runtime that leads to aFailure. For example, the program might display the incorrect output because the wrong value is stored in avariable.

I ADefectis the actual incorrect fragment of code that the programmer wrote; this is what must be changed to fix the problem.

(16)

Tracking down defect

Defect⇐=

Infection⇐=Failure

I AFailureis visible to the end user of a program. For example, the program prints an incorrect output.

I Infectionis the underlying state of the program at runtime that leads to aFailure. For example, the program might display the incorrect output because the wrong value is stored in avariable.

I ADefectis the actual incorrect fragment of code that the programmer wrote; this is what must be changed to fix the problem.

(17)

Tracking down defect

Defect⇐=Infection⇐=Failure

I AFailureis visible to the end user of a program. For example, the program prints an incorrect output.

I Infectionis the underlying state of the program at runtime that leads to aFailure. For example, the program might display the incorrect output because the wrong value is stored in avariable.

I ADefectis the actual incorrect fragment of code that the programmer wrote; this is what must be changed to fix the problem.

(18)

First of all..

THE BEST WAY TO DEBUG A PROGRAM IS TO MAKE NO MISTAKES

I Preventing bugs.

I Detecting/locating bugs.

Ca. 80 percent of software development costs spent on identifying and correcting defects.

It is much more expensive (in terms of time and effort) to detect/locate exisisting bugs, than prevent them in the first place.

(19)

First of all..

THE BEST WAY TO DEBUG A PROGRAM IS TO MAKE NO MISTAKES

I Preventing bugs.

I Detecting/locating bugs.

Ca. 80 percent of software development costs spent on identifying and correcting defects.

It is much more expensive (in terms of time and effort) to detect/locate exisisting bugs, than prevent them in the first place.

(20)

First of all..

THE BEST WAY TO DEBUG A PROGRAM IS TO MAKE NO MISTAKES

I Preventing bugs.

I Detecting/locating bugs.

Ca. 80 percent of software development costs spent on identifying and correcting defects.

It is much more expensive (in terms of time and effort) to detect/locate exisisting bugs, than prevent them in the first place.

(21)

IfSQ Institute for Software Quality

www.ifsq.org

I We have an agreed common goal: to raise the standard of software (and software development) around the world by promoting Code Inspection as a prerequisite to Software Testing in the production and delivery cycle.

I Our strong hope is that eventually the idea of inspecting code before testing will be as self-evident as testing software before using it.

(22)

IfSQ Institute for Software Quality

www.ifsq.org

I We have an agreed common goal: to raise the standard of software (and software development) around the world by promoting Code Inspection as a prerequisite to Software Testing in the production and delivery cycle.

I Our strong hope is that eventually the idea of inspecting code before testing will be as self-evident as testing software before using it.

(23)

The Fundamental question

How can I prevent Bugs?

I Design.

I Good writing.

I Self-checking code.

I Test scaffolding.

(24)

The Fundamental question

How can I prevent Bugs?

I Design.

I Good writing.

I Self-checking code.

I Test scaffolding.

(25)

Preventing bugs via design

Programming is a design activity.

It’s a creative act, not mechanical code generation.

I Good modularization.

I Strong encapsulation/information hiding.

I Clear,simple pre- and post-processing.

I Requirements of operations should testable.

(26)

Preventing bugs via design

Programming is a design activity.

It’s a creative act, not mechanical code generation.

I Good modularization.

I Strong encapsulation/information hiding.

I Clear,simple pre- and post-processing.

I Requirements of operations should testable.

(27)

What is a module?

I A module is a discrete, well-defined, small component of a system.

I The smaller the component, the easier it is to understand.

I Every component has interfaces with other components, and all interfaces are sources of confusion.

39% of all errors are caused by internal

interface errors / errors in communication between routines.

I Large components reduce external interfaces but have complicated internal logic that may be difficult or impossible to understand.

I The art ofsoftware engineeringis setting component size and boundaries at points that balance internal complexity against interface complexity to achieve an overall complexity minimization. A study showed that when routines averaged 100 to 150 lines each, code was more stable and required less changes.

(28)

What is a module?

I A module is a discrete, well-defined, small component of a system.

I The smaller the component, the easier it is to understand.

I Every component has interfaces with other components, and all interfaces are sources of confusion.

39% of all errors are caused by internal

interface errors / errors in communication between routines.

I Large components reduce external interfaces but have complicated internal logic that may be difficult or impossible to understand.

I The art ofsoftware engineeringis setting component size and boundaries at points that balance internal complexity against interface complexity to achieve an overall complexity minimization. A study showed that when routines averaged 100 to 150 lines each, code was more stable and required less changes.

(29)

What is a module?

I A module is a discrete, well-defined, small component of a system.

I The smaller the component, the easier it is to understand.

I Every component has interfaces with other components, and all interfaces are sources of confusion.

39% of all errors are caused by internal

interface errors / errors in communication between routines.

I Large components reduce external interfaces but have complicated internal logic that may be difficult or impossible to understand.

I The art ofsoftware engineeringis setting component size and boundaries at points that balance internal complexity against interface complexity to achieve an overall complexity minimization.

A study showed that when routines averaged 100 to 150 lines each, code was more stable and required less changes.

(30)

What is a module?

I A module is a discrete, well-defined, small component of a system.

I The smaller the component, the easier it is to understand.

I Every component has interfaces with other components, and all interfaces are sources of confusion.

39% of all errors are caused by internal

interface errors / errors in communication between routines.

I Large components reduce external interfaces but have complicated internal logic that may be difficult or impossible to understand.

I The art ofsoftware engineeringis setting component size and boundaries at points that balance internal complexity against interface complexity to achieve an overall complexity minimization.

A study showed that when routines averaged 100 to 150 lines each, code was more stable and required less changes.

(31)

Good modularization...

I reduces complexity

I avoids duplicate code

I facilitates reusable code

I limits effects of the changes

I facilitates test

I results in easier implementation

(32)

Strong encapsulation/information hiding

I The principle of information hiding suggests that modules be characterized by design decisions that each hides from all others.

I The information contained within a module is inaccesible to other modules that have no need for such information.

I Hiding implies that effective modularity can be achieved by defining a set of independent modules that communicate with one another only that information necessary to achieve software function.

I Because most data and procedure are hidden from other parts of software , inadvertent errors introduced during modification are less likely to propagate to other locations within the software.

(33)

Cohesion & Coupling

I Cohesion: a measure of how closely the instructions in a module are related to each other.

I Coupling: a measure of how closely a modules’ execution depends upon other modules.

I Avoid global variables.

I As a general rule, you should always aim to create modules that have strong cohesion and weak coupling.

I The routines with the highest coupling-to-cohesion ratios had 7 times more errors than those with the lowest ratios.

Spaghetti codeis characterized by very strong coupling.

(34)

Cohesion & Coupling

I Cohesion: a measure of how closely the instructions in a module are related to each other.

I Coupling: a measure of how closely a modules’ execution depends upon other modules.

I Avoid global variables.

I As a general rule, you should always aim to create modules that have strong cohesion and weak coupling.

I The routines with the highest coupling-to-cohesion ratios had 7 times more errors than those with the lowest ratios.

Spaghetti codeis characterized by very strong coupling.

(35)

Cohesion & Coupling

I Cohesion: a measure of how closely the instructions in a module are related to each other.

I Coupling: a measure of how closely a modules’ execution depends upon other modules.

I Avoid global variables.

I As a general rule, you should always aim to create modules that have strong cohesion and weak coupling.

I The routines with the highest coupling-to-cohesion ratios had 7 times more errors than those with the lowest ratios.

Spaghetti codeis characterized by very strong coupling.

(36)

Preventing bugs via good writing

I Clarity is more important than efficiency: clarity of writing and style.

I Use simple expressions, not complex

I Use meaningful names

I Clarity of purpose for:

I Functions.

I Loops.

I Nested constructs.

Studies have shown that few people can understand nesting of conditional statements to more than 3 levels.

I Comments,comments,comments.

I Small size of functions,routines.

A study at IBM found that the most error-prone routines were those larger than 500 lines of code.

(37)

Preventing bugs via good writing

I Clarity is more important than efficiency: clarity of writing and style.

I Use simple expressions, not complex

I Use meaningful names

I Clarity of purpose for:

I Functions.

I Loops.

I Nested constructs.

Studies have shown that few people can understand nesting of conditional statements to more than 3 levels.

I Comments,comments,comments.

I Small size of functions,routines.

A study at IBM found that the most error-prone routines were those larger than 500 lines of code.

(38)

Preventing bugs via good writing

I Clarity is more important than efficiency: clarity of writing and style.

I Use simple expressions, not complex

I Use meaningful names

I Clarity of purpose for:

I Functions.

I Loops.

I Nested constructs.

Studies have shown that few people can understand nesting of conditional statements to more than 3 levels.

I Comments,comments,comments.

I Small size of functions,routines.

A study at IBM found that the most error-prone routines were those larger than 500 lines of code.

(39)

Preventing bugs via good writing

I Clarity is more important than efficiency: clarity of writing and style.

I Use simple expressions, not complex

I Use meaningful names

I Clarity of purpose for:

I Functions.

I Loops.

I Nested constructs.

Studies have shown that few people can understand nesting of conditional statements to more than 3 levels.

I Comments,comments,comments.

I Small size of functions,routines.

A study at IBM found that the most error-prone routines were those larger than 500 lines of code.

(40)

Preventing bugs via good writing 2

I Use the smallest acceptable scope for:

I Variable names.

I Static/local functions.

I Use named intermediate values.

I Avoid "Magic numbers".

I Generalize your code.

I Document your program.

I Write standard language.

(41)

Clarity of writing

...

do j=1,n do i=1,n

v(i,j)=(i/j)*(j/i) end do

end do ...

... do j=1,n

do i=1,n v(i,j)=0.0 v(i,i)=1.0 end do

end do ...

(42)

Clarity of writing

...

do j=1,n do i=1,n

v(i,j)=(i/j)*(j/i) end do

end do ...

...

do j=1,n do i=1,n

v(i,j)=0.0 v(i,i)=1.0 end do

end do ...

(43)

Use meaningful names

The name of a variable, function, etc. should answer all the big questions:

I why it exists

I what it does

I how it is used.

If a name requires a comment, then the name does not reveal its intent.

(44)

Use meaningful names

The name of a variable, function, etc. should answer all the big questions:

I why it exists

I what it does

I how it is used.

If a name requires a comment, then the name does not reveal its intent.

(45)

Use meaningful names

The name of a variable, function, etc. should answer all the big questions:

I why it exists

I what it does

I how it is used.

If a name requires a comment, then the name does not reveal its intent.

(46)

Use meaningful names

The name of a variable, function, etc. should answer all the big questions:

I why it exists

I what it does

I how it is used.

If a name requires a comment, then the name does not reveal its intent.

(47)

Use meaningful names

The name of a variable, function, etc. should answer all the big questions:

I why it exists

I what it does

I how it is used.

If a name requires a comment, then the name does not reveal its intent.

(48)

Use meaningful names

Purpose of variables Good names Bad names Good descriptors Bad descriptors Running total of runningTotal,checkTotal written,ct,checks, checks written to date nChecks CHKTTL,x,x1,x2

Velocity of a bullet velocity,trainVelocity velt,v,tv,

train velocityInMph x,x1,x2,train

Current date currentDate,todaysDate cd,current,c,x,x1,x2,date Lines per page LinesPerPage lpp,lines,l,x,x1,x2

(49)

Optimum name length

Too long: numberOfPeopleOnTheUsOlympicteam numberOfSeatsInTheStadium

maximumNumberOfPointsModernOlympics

Too short: n,np,ntn n,ns,nsisd m,mp,max,points

Just right: numberTeammembers,teamMemberCount numSeatInStadium,seatCount

teamPointsMax,pointsRecord

The effort required to debug a program is minimized when variables had names averaging 10 to 16 characters long.

(50)

Optimum name length

Too long: numberOfPeopleOnTheUsOlympicteam numberOfSeatsInTheStadium

maximumNumberOfPointsModernOlympics

Too short: n,np,ntn n,ns,nsisd m,mp,max,points

Just right: numberTeammembers,teamMemberCount numSeatInStadium,seatCount

teamPointsMax,pointsRecord

The effort required to debug a program is minimized when variables had names averaging 10 to 16 characters long.

(51)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(52)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(53)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(54)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(55)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(56)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(57)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(58)

Comments in the code

I Make sure comments and code are agree.

I Don’t comment bad code - rewrite it.

I Use variable names that mean something.

I Don’t over-comment,favor quality not quantity.

I Good comments explain why not how.

I Don’t duplicate code in a comment.

I Format a program to help the reader understand it.

I Indent to show the logical structure of a program.

(59)

Avoid magic numbers:example

Conversion of mass mixing ratio in units of g/kg to volume mixing ratio in units of ppmv

...

REAL(8) :: ppmv

REAL(8) :: Mixing_Ratio REAL(8) :: Molecular_Weight ...

ppmv = 1.0e+03 * Mixing_Ratio * 28.9648 / Molecular_Weight

REAL(8), PARAMETER :: G_TO_KG = 1.0d-03 REAL(8), PARAMETER :: PPV_TO_PPMV = 1.0d+06

REAL(8), PARAMETER :: SCALE_FACTOR = G_TO_KG * PPV_TO_PPMV REAL(8), PARAMETER :: MW_DRYAIR = 28.9648

...

REAL(8) :: ppmv

REAL(8) :: Mixing_Ratio REAL(8) :: Molecular_Weight ...

ppmv = SCALE_FACTOR * Mixing_Ratio * MW_DRYAIR / Molecular_Weight

(60)

Avoid magic numbers:example

Conversion of mass mixing ratio in units of g/kg to volume mixing ratio in units of ppmv

...

REAL(8) :: ppmv

REAL(8) :: Mixing_Ratio REAL(8) :: Molecular_Weight ...

ppmv = 1.0e+03 * Mixing_Ratio * 28.9648 / Molecular_Weight

REAL(8), PARAMETER :: G_TO_KG = 1.0d-03 REAL(8), PARAMETER :: PPV_TO_PPMV = 1.0d+06

REAL(8), PARAMETER :: SCALE_FACTOR = G_TO_KG * PPV_TO_PPMV REAL(8), PARAMETER :: MW_DRYAIR = 28.9648

...

REAL(8) :: ppmv

REAL(8) :: Mixing_Ratio REAL(8) :: Molecular_Weight ...

ppmv = SCALE_FACTOR * Mixing_Ratio * MW_DRYAIR / Molecular_Weight

(61)

Avoid magic number

I Changes can be made more reliably.

I Changes can be made more easily.

I Your code is more readable.

(62)

Preventing bugs via Self-checking code

I Checking assumptions.

I "assert" macro.

I Custom "assert" macros.

I Assertions about intermediate values.

I Preconditions,postcondition.

Defensive programming.

(63)

Preventing bugs via Self-checking code

I Checking assumptions.

I "assert" macro.

I Custom "assert" macros.

I Assertions about intermediate values.

I Preconditions,postcondition.

Defensive programming.

(64)

Checking assumptions

I That an input parameter’s value falls within its expected range (or an output parameters’ value does)

I That the value of an input-only variable is not changed by a routine.

I That a pointer is non-NULL.

I That an array or other container passed into a routine can contain at least X data number of data elements.

I That a table has been initialized to contain real values.

I Etc.

(65)

Assertions

I An assertion is a code (usually routine or macro) that allows a program to check itself as runs.

I When an assertion is true, that means everything is operating as expected

I When it’s false, that means it has detected an unexpected error in the code.

I Use error handling code for conditions you expected to occur.

(66)

Error handling technique

I Return a neutral value.

I Substitute the closest legal value.

I Log a warning message to a file.

I Return an error code.

I Set a value of a status variable.

I Return status as the function’s return value.

I Throw an exception using the language’s build-in exception mechanism.

I Display an error message wherever the error is encountered.

I Handle the error in whatever way works best locally.

I Shutdown.

(67)

Rules of programming style

From"The Elements of Programming Style" Kernighan and Plauger I Write clearly don’t be too clever.

I Say what you mean, simply and directly.

I Use library functions whenever feasible.

I Avoid too many temporary variables.

I Write clearly - don’t sacrifice clarity for "efficiency".

I Let the machine do the dirty work.

I Replace repetitive expressions by calls to common functions.

I Parenthesize to avoid ambiguity.

I Choose variables names that won’t be confused.

I Avoid unnecessary branches.

(68)

Rules of programming style

I If a logical expression is hard to understand, try transforming it.

I Choose a data representation that makes the program simple.

I Write first in easy-to-understand pseudo language; then translate into whatever language you have to use.

I Modularize. Use procedures and functions.

I Avoid gotos completely if you keep the program readable.

I Don’t patch bad code - rewrite it.

I Write and test a big program in small pieces.

I Use recursive procedures for recursively-defined data structures.

I Test input for plausibility and validity.

I Make sure input doesn’t violate the limits of the program.

(69)

Rules of programming style

I Terminate input by end-of-file marker, not by count.

I Identify bad input; recover if possible.

I Make input easy to prepare and output self-explanatory.

I Use uniform input formats.

I Make input easy to proofread.

I Use self-identifying input. Allow defaults. Echo both on output.

I Make sure all variables are initialized before use.

I Don’t stop at one bug.

I Use debugging compilers.

I Watch out for off-by-one errors.

(70)

Rules of programming style

I Take care to branch the right way on equality.

I Avoid multiple exits from the loops.

I Make sure your code does "nothing" gracefully.

I Test programs at their boundary values.

I Check some answers by hand.

I 10.0 times 0.1 is hardly ever 1.0.

I 7/8 is zero while 7.0/8.0 is not zero.

I Don’t compare floating point numbers solely equality.

I Make it right before you make it faster.

I Make it fail-safe before you make faster.

(71)

Rules of programming style

I Make it clear before you make it faster.

I Don’t sacrifice clarity for small gains of "efficiency".

I Let your compiler do the simple optimizations.

I Don’t strain to re-use code; reorganize instead.

I Make sure special cases are truly special.

I Keep it simple to make it faster.

I Don’t diddle code to make it faster - find a better algorithm.

I Instrument yout programs. Measure before making "efficiency" changes.

I Make sure comments and code agree.

I Don’t just echo the code with comments - make every comment count.

(72)

Rules of programming style

I Don’t comment bad code - rewrite it.

I Use variable names taht mean something.

I Use statement labels that mean something.

I Format a program to help the reader understand it.

I Document your data layouts.

I Don’t over-comment.

(73)

Outline

Bugs and Prevention Testing

Static analysis Run-time analysis Debugging

Parallel debugging

(74)

Testing: a simple program

Input

Read three integer values from the command line.

The three values represent the lengths of the sides of a triangle.

Output

Tell whether the triangle is: Scalene

Isosceles Equilater.

Create a set of test cases for this program. ("The art of sotware testing" G.J. Myers)

(75)

Testing: a simple program

Input

Read three integer values from the command line.

The three values represent the lengths of the sides of a triangle.

Output

Tell whether the triangle is:

Scalene Isosceles Equilater.

Create a set of test cases for this program. ("The art of sotware testing" G.J. Myers)

(76)

Testing: a simple program

Input

Read three integer values from the command line.

The three values represent the lengths of the sides of a triangle.

Output

Tell whether the triangle is:

Scalene Isosceles Equilater.

Create a set of test cases for this program.

("The art of sotware testing" G.J. Myers)

(77)

Testing: a simple program

Input

Read three integer values from the command line.

The three values represent the lengths of the sides of a triangle.

Output

Tell whether the triangle is:

Scalene Isosceles Equilater.

Create a set of test cases for this program.

("The art of sotware testing" G.J. Myers)

(78)

Testing: a simple program

Q:1 Do you have a test case with three integers greater than zero such that the sum of two of the numbers is less than the third ?

(4,1,2) is an invalide triangle. (a,b,c) with a > b+c

4 2 1

Define valide triangles a < b + c

(79)

Testing: a simple program

Q:1 Do you have a test case with three integers greater than zero such that the sum of two of the numbers is less than the third ?

(4,1,2) is an invalide triangle.

(a,b,c) with a > b+c

4 2 1

Define valide triangles a < b + c

(80)

Testing: a simple program

Q:2 Do you have a test case with some permutations of previous test?

(1,4,2) (4,1,2)

Fulfill above definition, but are still invalid. Patch definition of valid triangles:

a < b + cb < a + c and c < a + b

(81)

Testing: a simple program

Q:2 Do you have a test case with some permutations of previous test?

(1,4,2) (4,1,2)

Fulfill above definition, but are still invalid.

Patch definition of valid triangles:

a < b + cb < a + c and c < a + b

(82)

Testing: a simple program

Q:3 Do you have a test case with three integers greater than zero such that the sum of two numbers is equal to the third?

(4,2,2) is invalid triangle with equal sum.

4

2 2

Fulfill above definition, but is invalid: a<b+c and b<a+c and c<a+b

(83)

Testing: a simple program

Q:3 Do you have a test case with three integers greater than zero such that the sum of two numbers is equal to the third?

(4,2,2) is invalid triangle with equal sum.

4

2 2

Fulfill above definition, but is invalid:

a<b+c and b<a+c and c<a+b

(84)

Testing: a simple program

Do you have a test case:

4. with some permutations of previous test?(2,4,2) (2,2,4) 5. that represents a valid scalene triangle?(3,4,5) 6. that represents a valid equilateral triangle?(3,3,3) 7. that represents a valid isosceles triangle?(4,3,3) 8. with some permutations of previous test? (3,4,3) (3,3,4) 9. in which one side has a zero value?(0,4,3)

10. in which one side has a negative value?(-1,4,3) 11. in which all sides are zero?(0,0,0)

12. specifying at least one noninteger value?(2,2.5,4) 13. specifying the wrong number of values?(2,3) or (2,3,5,4)

Q:14 For each test case did you specify the expected output from the program in addition to the input values?

(85)

About the example

I A set of test case that satisfies these conditions does not guarantee that all possibile errors would be found.

I An adeguate test of this program should expose at least these errors.

I Higly qualified professional programmers score, on the average,7.8out of a possibile 14.

(86)

Classification of errors

Syntax

I Definition: errors in grammar (violations of the "rules" for forming legal language statements).

I Examples: undeclared identifiers, mismatched parentheses in an expression, an opening brace without a matching closing brace, etc.

I Occur: an error that is caught in the process of compiling the program.

The easiest errors to spot by a compiler or some aid in checking the syntax.

As you get more practice using a language, you naturally make fewer errors, and will be able to quickly correct those that do occur.

(87)

Classification of errors

Syntax

I Definition: errors in grammar (violations of the "rules" for forming legal language statements).

I Examples: undeclared identifiers, mismatched parentheses in an expression, an opening brace without a matching closing brace, etc.

I Occur: an error that is caught in the process of compiling the program.

The easiest errors to spot by a compiler or some aid in checking the syntax.

As you get more practice using a language, you naturally make fewer errors, and will be able to quickly correct those that do occur.

(88)

Classification of errors

Runtime

I Definition: "Asking the computer to do the impossible!"

I Examples: division by zero, taking the square root of a negative number, referring to the 101th on a list of only 100 items, deferencing a null pointer, etc.

I Occur: an error that is not detected until the program is executed, and then causes a processing error to occur.

They are not easy to spot because they are not syntax or grammar errors, they are subtle errors and develop in the course of program’s execution.

Avoiding exceptions and correcting program behaviour is also largely a matter of experience.

To prevent use defensive programming.

(89)

Classification of errors

Runtime

I Definition: "Asking the computer to do the impossible!"

I Examples: division by zero, taking the square root of a negative number, referring to the 101th on a list of only 100 items, deferencing a null pointer, etc.

I Occur: an error that is not detected until the program is executed, and then causes a processing error to occur.

They are not easy to spot because they are not syntax or grammar errors, they are subtle errors and develop in the course of program’s execution.

Avoiding exceptions and correcting program behaviour is also largely a matter of experience.

To prevent use defensive programming.

(90)

Classification of errors

Logic (semantic, meaning)

I Definition: the program compiles (no syntax errors) and runs to a normal completion (no runtime erros), but the output is wrong. A statement may be syntactically correct, but mean something other than what we intended. Therefore it has a different effect, causing the program output to be wrong.

I Examples: improper initialization of variables, performing arithmetic operations in the wrong order, using an incorrect formula to compute a value, etc.

I Occur: an error that affect how the code works.

It is a type of error that only the programmer can

recognize.Finding and correcting logic errors in a program is known as debugging.

(91)

Classification of errors

Logic (semantic, meaning)

I Definition: the program compiles (no syntax errors) and runs to a normal completion (no runtime erros), but the output is wrong. A statement may be syntactically correct, but mean something other than what we intended. Therefore it has a different effect, causing the program output to be wrong.

I Examples: improper initialization of variables, performing arithmetic operations in the wrong order, using an incorrect formula to compute a value, etc.

I Occur: an error that affect how the code works.

It is a type of error that only the programmer can

recognize.Finding and correcting logic errors in a program is known as debugging.

(92)

Outline

Bugs and Prevention Testing

Static analysis Compiler options Static analyzer Run-time analysis Debugging

Parallel debugging

(93)

Definitions

Static analysis refers to a method of examinig software that allows developers to discover dangerous programming pratices or potential errors in source code, without actually run the code.

I Using compiler options.

I Using static analyzer.

(94)

Definitions

Static analysis refers to a method of examinig software that allows developers to discover dangerous programming pratices or potential errors in source code, without actually run the code.

I Using compiler options.

I Using static analyzer.

(95)

Compiler and errors

Source Program =⇒ Compiler =⇒ Target program

Status Messages and/or Warning Messages and/or Error Messages

Compiler checks:

I Syntax.

I Semantic.

(96)

Compiler and errors

Source Program =⇒ Compiler =⇒ Target program

Status Messages and/or Warning Messages and/or Error Messages

Compiler checks:

I Syntax.

I Semantic.

(97)

Lexical (Syntactic) errors

I Characters in the source that aren’t in the alphabet of the language.

I Words in the source that aren’t in the vocabulary of the language.

(98)

Syntactic errors

I Comment delimiters that have been put in wrong place or omitted.

I Literal delimiters that have been put in wrong place or omitted.

I Keywords that have been misspelled.

I Required punctuation that is missing.

I Construct delimiters such as parentheses or braces that have been missplaced.

I Blank or tab characters that are missing.

I Blank or tab characters that shouldn’t occur where they’re found.

(99)

Semantic errors

I Names that aren’t declared.

I Operands of the wrong type for the operator they’re used with.

I Values that have the wrong type for the name to which they’re assigned.

I Procedures that are invoked with the wrong number of arguments.

I Procedures that are invoked with the wrong type of arguments.

I Function return values that are the wrong type for the context in which they’re used.

(100)

Semantic errors

I Code blocks that are unreachable.

I Code blocks that have no effect.

I Local variables that are used before being initialized or assigned.

I Local variables that are initialized or assigned but not used.

I Procedures that are never invoked.

I Procedures that have no effect.

I Global variables that are used before being initialized or assigned.

I Global variables that are initialized or assigned, but not used.

(101)

Compilers

I Not all compilers find the same defects.

I The more information a compilers has, the more defects it can find.

I Some compilers operate in "forgiving" mode but have "strict" or

"pedantic" mode, if you request it.

(102)

Outline

Bugs and Prevention Testing

Static analysis Compiler options Static analyzer Run-time analysis Debugging

Parallel debugging

(103)

Static analysis:example 1 part one

1 # include <stdio.h>

2 i n t main (void)

3 {

4 printf ("Two plus two is %f\n", 4);

5 r e t u r n 0;

6 }

<ruggiero@shiva ~/CODICI>gcc bad.c

<ruggiero@shiva ~/CODICI>./a.out

Two plus two is 0.000000

(104)

Static analysis:example 1 part one

1 # include <stdio.h>

2 i n t main (void)

3 {

4 printf ("Two plus two is %f\n", 4);

5 r e t u r n 0;

6 }

<ruggiero@shiva ~/CODICI>gcc bad.c

<ruggiero@shiva ~/CODICI>./a.out

Two plus two is 0.000000

(105)

Static analysis:example 1 part two

<ruggiero@shiva ~/CODICI>gcc -Wall bad.c

bad.c: In function main:

bad.c:4: warning: format ’%f’ expects type ’double’, but argument 2 has type ’int’

1 # include <stdio.h>

2 i n t main (void)

3 {

4 printf ("Two plus two is %

fd

\n", 4);

5 r e t u r n 0;

6 }

(106)

Static analysis:example 1 part two

<ruggiero@shiva ~/CODICI>gcc -Wall bad.c

bad.c: In function main:

bad.c:4: warning: format ’%f’ expects type ’double’, but argument 2 has type ’int’

1 # include <stdio.h>

2 i n t main (void)

3 {

4 printf ("Two plus two is %f

d

\n", 4);

5 r e t u r n 0;

6 }

(107)

Static analysis:example 1 part two

<ruggiero@shiva ~/CODICI>gcc -Wall bad.c

bad.c: In function main:

bad.c:4: warning: format ’%f’ expects type ’double’, but argument 2 has type ’int’

1 # include <stdio.h>

2 i n t main (void)

3 {

4 printf ("Two plus two is %

f

d\n", 4);

5 r e t u r n 0;

6 }

(108)

gcc options

-Wall

turns on the most commonly-used compiler warnings option

-Waddress -Warray-bounds (only with -O2) -Wc++0x-compat -Wchar-subscripts -Wimplicit-int -Wimplicit-function-declaration -Wcomment-Wformat-Wmain (only for C/ObjC and unless -ffreestanding) -Wmissing-braces -Wnonnull -Wparentheses -Wpointer-sign -Wreorder -Wreturn-type -Wsequence-point -Wsign-compare (only in C++) -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtrigraphs -Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wvolatile-register-var

(109)

Oher compilers

[ruggiero@matrix1 ~]$ pgcc bad.c

[ruggiero@matrix1 ~]$ icc bad.c

bad.c(4): warning #181: argument is incompatible with corresponding format string conversion

printf ("Two plus two is %f\n", 4);

^

Riferimenti

Documenti correlati

I vi è alta probabilità di accedere nuovamente, entro un breve intervallo di tempo, ad una cella di memoria alla quale si è appena avuto accesso (es: ripetuto accesso alle

I OMP: quelle che contengono costrutti di parallellizazione (OpenMP in questo caso, altrimenti MPI o anche entrambi).. I COM:tutte quelle routines che interagiscono con quelle

Nelle architetture a memoria condivisa con processori multicore vi sono generalmente due tipologie di accesso alla memoria principale. I Uniform Memory Access dove tutti i cores

A debugger is a tool that controls the application being debugged so as to allow the programmer to follow the flow of program execution and , at any desired point, stop the program

I Un &#34;page-fault&#34; è un segnale generato dalla CPU, con conseguente reazione del sistema operativo, quando un programma tenta di accedere ad una pagina di memoria virtuale

I Modern multicore systems have shared memory on node and distributed memory between nodes...

I Automatic vectorization (use of packed SIMD instructions) I Loop interchange (for more efficient memory access) I Loop unrolling (more instruction level parallelism). I

I Login nodes are reserved solely for the purpose of managing your files and submitting jobs to the batch system?. I CPU time and memory usage are severely limited on the