Download presentation
Presentation is loading. Please wait.
1
General Issues in Using Variables
SCMP Special Topic: Software Development Spring 2017 James Skon
2
Implicit Declarations
Some languages support implicit variable declarations. If a variable is references that has not been declared, it is automatically created. What’s wrong with this? Consider: acctNum and acctNo
3
Implicit Declarations
What to do? Helpful tactics: Turn off implicit declarations Declare all variables Use naming conventions Check variable names
4
Improper Variable Initialization
A variable is used before it has been assigned a value. The value in the variable is outdated. Part of the variable has been assigned a value and part has not.
5
Guidelines for avoiding initialization problems
Initialize each variable as it's declared float studentGrades[ MAX_STUDENTS ] = { 0.0 }; Initialize each variable close to where it's first used
6
Examples Better! Bad! int accountIndex = 0; //code using accountIndex
// declare all variables int accountIndex; double total; boolean done; //initialize all variables accountIndex = 0; total = 0.0; done = False; ... //code using accountIndex //code using total //code using done While Not done int accountIndex = 0; //code using accountIndex ... double total = 0.0; //code using total boolean done = False; //code using done While Not done Better! Bad!
7
Guidelines for avoiding initialization problems
Use const when possible Enforce correct use Pay special attention to counters and accumulators Initialize a class's member data in its constructor Initialize named constants once; initialize variables with executable code Take advantage of your compiler's warning messages
8
Variable Scope Where is the variable “visible”?
Different languages handle scope in different ways. In C++ and similar languages, a variable can be visible to a block (a section of code enclosed in curly brackets), a routine, a class (and possibly its derived classes), or the whole program.
9
Localize References to Variables
The code between references to a variable is a "window of vulnerability." a = 0; b = 0; c = 0; a = b + c; a = 0; b = 0; c = 0; b = a + 1; b = b / c;
10
Variable Life Span Keep Variables "Live" for as Short a Time as Possible
11
Variable Life Span – Keep Short
reduces the window of vulnerability - You reduce the chance of incorrectly or inadvertently altering a variable gives you a more accurate picture of your code - you can concentrate on a smaller section of code when you're thinking about that variable reduces the chance of initialization errors makes your code more readable Easier to refactor (split) code up.
12
Measuring the Live Time of a Variable
You can formalize the concept of live time by counting the number of lines between the first and last references to a variable. Average life span should be as low as possible
13
Measuring the Live Time of a Variable
Last reference to recordIndex 1 // initialize all variables 2 recordIndex = 0; 3 total = 0; 4 done = false; ... 26 while ( recordIndex < recordCount ) { recordIndex = recordIndex + 1; 64 while ( !done ) { if ( total > projectedTotal ) { done = true; TOO LONG!! Last reference to total Last reference to done recordIndex ( line 28 - line ) = 27 total ( line 69 - line ) = 67 done ( line 70 - line ) = 67 Average Live Time ( ) / 3 54
14
Measuring the Live Time of a Variable
Initialization of recordIndex moved down ... 25 recordIndex = 0; <-- 1 26 while ( recordIndex < recordCount ) { recordIndex = recordIndex + 1; 62 total = 0; <-- 2 63 done = false; <-- 2 64 while ( !done ) { if ( total > projectedTotal ) { done = true; Initialization of total and done moved down recordIndex ( line 28 - line ) = 4 total ( line 69 - line ) = 8 done ( line 70 - line ) = 8 Average Live Time ( ) / 3 7
15
General 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 Don't assign a value to a variable until just before the value is used int receiptIndex = 0; float dailyReceipts = TodaysReceipts(); double totalReceipts = TotalReceipts( dailyReceipts ); Good!
16
Statements using two sets of variables
Group related statements Statements using two sets of variables Bad! 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 );
17
Group related statements - Better
void SummarizeData( ... ) { GetOldData( oldData, &numOldData ); totalOldData = Sum( oldData, numOldData ); | PrintOldDataSummary( oldData, totalOldData, numOldData ); SaveOldDataSummary( totalOldData, numOldData ); ... GetNewData( newData, &numNewData ); totalNewData = Sum( newData, numNewData ); | PrintNewDataSummary( newData, totalNewData, numNewData ); SaveNewDataSummary( totalNewData, numNewData ); }
18
Variable Persistence "Persistence" is another word for the life span of a piece of data. The main problem with persistence arises when you assume that a variable has a longer persistence than it really does. Like that jug of milk in your refrigerator!
19
Variable Persistence Some variables persist for the life of a particular block of code or routine. Some variables as long as you allow them to. In Java, variables created with new persist until they are garbage collected. In C++, variables created with new persist until you delete them. Forever: Global
20
Variable Persistence - hit
Set variables to "unreasonable values" when you're through with them. Write code that assumes data isn't persistent. Develop the habit of declaring and initializing all data right before it's used.
21
Binding Time Binding Time:
Java Example of a Variable That's Bound at Code-Writing Time Java Example of a Variable That's Bound at Compile titleBar.color = 0xFF; // 0xFF is hex value for color blue private static final int COLOR_BLUE = 0xFF; private static final int TITLE_BAR_COLOR = COLOR_BLUE; ... titleBar.color = TITLE_BAR_COLOR;
22
Binding Time Binding Time:
Java Example of a Variable That's Bound at Run Time titleBar.color = ReadTitleBarColor();
23
Variable Binding Summary
The following are the times a variable can be bound to a value in this example. Coding time (use of magic numbers) Compile time (use of a named constant) Load time (reading a value from an external source such as the Windows registry file or a Java properties file) Object instantiation time (such as reading the value each time a window is created) Just in time (such as reading the value each time the window is drawn)
24
Binding Time In general, the earlier the binding time, the lower the flexibility and the lower the complexity.
25
Relationship Between Data Types and Control Structures
Sequential data translates to sequential statements in a program
26
Relationship Between Data Types and Control Structures
Selective data translates to if and case statements in a program In general, selective data is a collection in which one of several pieces of data is used at any particular time, but only one
27
Iterative data translates to for, repeat, and while looping structures in a program
28
Using Each Variable for Exactly One Purpose
It's sometimes tempting to use one variable in two different places for two different activities. // 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[O] = ( -b + temp ) / ( 2 * a ); root[1] = ( -b - temp ) / ( 2 * a ); ... // swap the roots temp = root[0]; root[0] = root[1]; root[1] = temp;
29
Using Each Variable for Exactly One Purpose
C++ Example of Using Two Variables for Two Purposes---Good Practice // Compute roots of a quadratic equation. // This code assumes that (b*b-4*a*c) is positive. discriminant = Sqrt( b*b - 4*a*c ); root[0] = ( -b + discriminant ) / ( 2 * a ); root[1] = ( -b - discriminant ) / ( 2 * a ); ... // swap the roots oldRoot = root[0]; root[0] = root[1]; root[1] = oldRoot;
30
Avoid variables with hidden meanings
The variable customerId might represent a customer number, unless its value is greater than 500,000, in which case you subtract 500,000 to get the number of a delinquent account. The variable bytesWritten might be the number of bytes written to an output file, unless its value is negative, in which case it indicates the number of the disk drive used for the output.
31
Initializing Variables
Does each routine check input parameters for validity? Does the code declare variables close to where they're first used? Does the code initialize variables as they're declared, if possible? Does the code initialize variables close to where they're first used, if it isn't possible to declare and initialize them at the same time? Are counters and accumulators initialized properly and, if necessary, reinitialized each time they are used? Are variables reinitialized properly in code that's executed repeatedly? Does the code compile with no warnings from the compiler? (And have you turned on all the available warnings?) If your language uses implicit declarations, have you compensated for the problems they cause?
32
Other General Issues in Using Data
Do all variables have the smallest scope possible? Are references to variables as close together as possible, both from each reference to a variable to the next reference and in total live time? Do control structures correspond to the data types? Are all the declared variables being used? Are all variables bound at appropriate times—that is, are you striking a conscious balance between the flexibility of late binding and the increased complexity associated with late binding? Does each variable have one and only one purpose? Is each variable's meaning explicit, with no hidden meanings?
33
Other General Issues in Using Data
Do all variables have the smallest scope possible? Are references to variables as close together as possible, both from each reference to a variable to the next reference and in total live time? Do control structures correspond to the data types? Are all the declared variables being used? Are all variables bound at appropriate times—that is, are you striking a conscious balance between the flexibility of late binding and the increased complexity associated with late binding? Does each variable have one and only one purpose? Is each variable's meaning explicit, with no hidden meanings?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.