using variables chapter 10-11. outline 2 variable initialization scope persistence using each...

28
Using Variables Chapter 10-11

Upload: morris-morton

Post on 05-Jan-2016

233 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Using Variables

Chapter 10-11

Page 2: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Outline

2

Variable Initialization Scope Persistence Using Each Variable for Single Purpose Variable Names

Page 3: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Data Literacy Test

3

abstract data type array bitmap boolean variable b-tree character variable container class double precision elongated stream enumerated type floating point heap index integer linked list named constant

literal local variables lookup table member data pointer private retroactive synapse referential integrity stack string structured variable tree typedef union value chain variant Total Score

1: familiar 0.5: know what a term means but aren’t sure

Page 4: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Loose Interpretation

4

0-14: beginning programmer 15-19: intermediate programmer, or

An experienced programmer who has forgotten a lot

20-24: expert programmer 25-29: know more about data types than

Steve Consider writing your own book

30-32: your are a pompous fraud Elongated stream, retroactive synapse, value

chain don’t refer to data types

Page 5: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Variable Initialization Problem

5

A variable may contain an initial value that you do not expect it to contain Never been assigned a value Outdated: assigned a value at some point, but no

longer valid Part of the variable assigned a value, part has not

Page 6: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Guidelines for Variable Initialization

6

Initialize each variable as it is declared Inexpensive form of defensive programming

Initialize each var close to where it’s first used Some languages (e.g., VB) do not support initializing

variables as they are declared Principle of proximity: keep related action together

Ideally, declare and define each variable close to where it’s first used

int accountIndex = 0;// code using accountIndex …double total = 0.0;// code using total …boolean done = false; // code using done while ( ! done ) { ... }

Page 7: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Guidelines for Variable Initialization

7

Use final or const when possible Pay attention to counters and accumulators

Forget to reset before the next time it is used Initialize a class’s member data in constructor Check the need to re-initialization

Used by a loop used many times Needs to be reset between calls

Use the compiler setting that automatically initialize variables

Page 8: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Guidelines for Variable Initialization

8

Take advantage of compiler’s warning messages

Check input parameters for validity Use a memory access checker to check for

bad pointers Initialize working memory to a known value at

the beginning of your program

Page 9: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Scope

9

Scope or visibility The extent to which the variable is known and can

be referenced throughout the program Minimizing vs maximizing scope

Maximizing scope Convenience, e.g., global variables Easier to write; Harder to understand/debug/modify

Minimizing scope Keep variables as local as possible Intellectual manageability, Easier to read

Code programs to read or write?

Page 10: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Localize References to Variables

10

The code between references to a variable is a ‘window of vulnerability’ New code might be added, inadvertently altering

the variable Someone reading the code might forget the value

the variable is supposed to contain Measure how close together the references

are span

Page 11: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Variable Span

11

a =0;b=0;c=0;b=a+1b=b/c; 1 line between 1st/2nd references to b: span of 1 0 line between 2nd/3rd references to b: span of 0

Average span For b, (1+0)/2=0.5

Page 12: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Live Time

12

Total # of statements over which a variable is live

Life begins/ends at the first/last reference

isn't affected by how many times the variable is used between the first and last times it's referenced.

Page 13: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Measuring Live Time

13

1 // initialize all variables2 recordIndex = 0 ;3 total = 0;4 done = false;…26 while (recordIndex<recordCount){27 …28 recordIndex = recordIndex+1; …64 while (!done) { …69 if (total>projectedTotal) {70 done = true;

recordIndex: 28-2+1total: 69-3+1done: 70-4+1Average: 54

Page 14: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Measuring Live Time - cont

14

…25 recordIndex = 0 ;26 while (recordIndex<recordCount){27 …28 recordIndex = recordIndex+1; …62 total = 0 ;63 done = false;64 while (!done) { …69 if (total>projectedTotal) {70 done = true;

recordIndex: 28-25+1total: 69-62+1done: 70-63+1Average: 7

Page 15: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Keep Variables ‘Live’ for a Short Time

15

Keep live time as short as possible: advantages Reduce the window of vulnerability Concentrate on a smaller section of code Reduce the chance of initialization errors Make the code more readable Easier for refactoring or splitting a large routine

into smaller routines

Page 16: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

What Do You Think?

16

void SummarizeData(…){…GetOldData( oldData, &numOldData);GetnewData(newData, &numNewData);totalOldData = sum(oldData, numOldData);totalNewData = sum(newData, numNewData);PrintOldDataSummary(oldData, totalOldData, numOldData);PrintNewDataSummary(newData, totalNewData,

numNewData);SaveOldDataSummary(totalOldData, numOldData);SaveNewDataSummary(totalNewData, numNewData);…

}

Page 17: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

17

Guidelines for Minimizing Scope

Page 18: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Guidelines for Minimizing Scope

18

Group related statements, and, if necessary, break related statements into separate routines

Don't assign a value to a variable until just before the value is used

Page 19: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Guidelines for Minimizing Scope

19

Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop When modify the loop, remember to make

corresponding modifications to the initialization Favor the smallest possible scope

Local to a specific loop, local to a routine, private to a class, then protected, then package,

Global only as last resort

Page 20: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Persistence

20

Some variables persist For the life of a block of code or routine

Variables inside a for loop As long as you allow them to

Objects created with new persist until garbage collected

For the life of a program Global variables

Forever Variables include values in database

Problem If you assume that a variable has a longer

persistence than it really does

Page 21: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Avoiding Persistence Problem

21

Use debug code or assertions to check critical variables for reasonable values

Set variables to unreasonable values when you are through with them Set a pointer to null after you delete it

Write code that assumes data isn’t persistent Develop the habit of declaring and

initializing all data right before it’s used Be suspicious if data is used without a nearby

initialization.

Page 22: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

What Do You Think?

22

// compute roots of a quadratic equation// this code assumes that (b*b-4*a*c) is positivetemp = sqrt (b*b-4*a*c);root[0] = (-b + temp) / (2*a);root[1] = (-b - temp) / (2*a);…//swap the rootstemp = root[0];root[0] = root[1];root[1] = temp;

Page 23: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Using Each Variable for Single Purpose

23

Using the same variable for different purposes makes it seem as though they are related when they’re not! Use discriminant for the first temp Use oldRoot for the second temp

Page 24: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Using Each Variable for Single Purpose

24

Avoid variables with hidden meanings - different values mean different things customerID: a customer number unless its

value>=500,000, in which case subtracting 500,000 results in the number of a delinquent account

Make sure all declared variables are used

Page 25: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

What Do You Think?

25

x = x –xx;xxx = fido + SalesTax(fido);x = x +LateFee(x1, x) + xxx;x = x + Interest(x1, x);

Page 26: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Kinds of Names to Avoid

26

Avoiding misleading names or abbreviations Avoid names with similar meanings

recordNum/numRecords Avoid names that sound similar

wrap/rap Avoid numerals in names Avoid misspelled words in names Don’t differentiate names solely by

capitalization Avoid multiple natural languages

check/cheque

Page 27: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Kinds of Names to Avoid - cont

27

Avoid the names of standard types, variables, and routines

If if=then then then = else;else else = if; // PL/1

Avoid names containing hard-to-read chars (1, l, I), (0, O), (2, Z), (S, 5), ...

Don’t use names that are totally unrelated to what the variables represent

Page 28: Using Variables Chapter 10-11. Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names

Reading

28

The Power of Variable Names ‘Code Complete’ Chapter 11.