280 likes | 426 Vues
Using Variables. Chapter 10-11. Outline. Variable Initialization Scope Persistence Using Each Variable for Single Purpose Variable Names. Data Literacy Test. literal local variables lookup table member data pointer private retroactive synapse referential integrity stack string
E N D
Using Variables Chapter 10-11
Outline • Variable Initialization • Scope • Persistence • Using Each Variable for Single Purpose • Variable Names
Data Literacy Test 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 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 1: familiar 0.5: know what a term means but aren’t sure
Loose Interpretation • 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
Variable Initialization Problem • 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
Guidelines for Variable Initialization • 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 intaccountIndex = 0; // code using accountIndex … double total = 0.0; // code using total … boolean done = false; // code using done while ( ! done ) { ... }
Guidelines for Variable Initialization • 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
Guidelines for Variable Initialization • 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
Scope • 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?
Localize References to Variables • 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
Variable Span a =0; b=0; c=0; b=a+1 b=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
Live Time • 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.
Measuring Live Time 1 // initialize all variables 2 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+1 total: 69-3+1 done: 70-4+1 Average: 54
Measuring Live Time - cont … 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+1 total: 69-62+1 done: 70-63+1 Average: 7
Keep Variables ‘Live’ for a Short Time • 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
What Do You Think? 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); … }
Guidelines for Minimizing Scope • 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
Guidelines for Minimizing Scope • 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
Persistence • 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
Avoiding Persistence Problem • 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.
What Do You Think? // compute roots of a quadratic equation // this code assumes that (b*b-4*a*c) is positive temp = sqrt (b*b-4*a*c); root[0] = (-b + temp) / (2*a); root[1] = (-b - temp) / (2*a); … //swap the roots temp = root[0]; root[0] = root[1]; root[1] = temp;
Using Each Variable for Single Purpose • 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
Using Each Variable for Single Purpose • 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
What Do You Think? x = x –xx; xxx = fido + SalesTax(fido); x = x +LateFee(x1, x) + xxx; x = x + Interest(x1, x);
Kinds of Names to Avoid • 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
Kinds of Names to Avoid - cont • 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
Reading • The Power of Variable Names • ‘Code Complete’ Chapter 11.