2. General Issues in Using Variables:
Guidelines for Initializing Variables.
Scope
Persistence.
Binding time.
Using each variable for exactly one purpose.
Variables declaration.
2
3. The Power of Variable Names:
Considerations in choosing good names.
The power of naming conventions.
Informal naming conventions.
Standardized prefixes.
Creating short names that are Readable.
Kinds of names to avoid.
3
5. Improper initialization problem.
Reasons:
The variable has never been assigned a value.
Part of the variable has been assigned a value and part has
not.
The value in the variable is outdated .
5
6. Solutions:
Initialize each variable as it's declared.
Use const when possible.
Pay attention to counters and accumulators.
Initialize a class's member data in its constructor.
Check the need for re-initialization.
Take advantage of your compiler's warning messages
Check input parameters for validity .
Use a memory-access checker to check for bad pointers.
Initialize working memory at the beginning of your program.
6
7. Scope is variable visibility.
We can measure scope by:
Live time.
Span.
7
8. live time is total number of statements over which a
variable is live .
1 int recordIndex = 0;
2 bool done = false;
...
...
26 while ( recordIndex < 10)
{...}
64 while ( !done )
{ ... }
1 int recordIndex = 0;
2 while ( recordIndex < 10)
{...}
...
...
63 bool done = false;
64 while ( !done )
{ ... }
8
9. Why we try to restrict live time?
You can concentrate on a smaller section of code.
Code more readable.
reduces the chance of initialization errors .
Easy to modify.
9
10. Span is how you keep variable references close.
1.
2.
3.
4.
1.
2.
3.
4.
a = 0;
a++;
a+= 10;
a = 3;
Life time = (4-1 +1) = 4
Average span = (0+0+0)/3 = 0;
a = 0;
b= 1;
c = 0;
a = b + c;
Life time = (4-1 +1) = 4
Average span = 2/1 = 2;
10
12. Initialize variables used in a loop immediately
before the loop .
Don't assign a value to a variable until just before
the value is used.
Break groups of related statements into separate
routines .
Begin with most restricted visibility, and expand
the scope if necessary .
Keep both span and live time as short as you can.
12
13. Persistence is life span of a piece of data .
Problem:
When you assume variable is persist but it's not .
Solution:
Set variables to "unreasonable values" when they doesn’t
persist.
Use assertions to check critical variables.
Declare and Initialize all data right before it's used.
13
14. The time at which the variable and its value are
bound.
titleBar.color = 0xFF;
titleBar.color = TITLE_BAR_COLOR;
titleBar.color = ReadTitleBarColor( )
Code-Writing Time
Compile Time
Run Time
The later you bind, the more flexibility you get and
the higher complexity you need .
14
15. Use each variable for one purpose only.
// Compute roots of a quadratic equation
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 ;
Creating unique variables for each purpose makes code more
readable.
15
16. Avoid hybrid coupling.
Double use is clear to you but it won't be to someone else.
Make sure all declared variables are used.
16
17. 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?
Are counters and accumulators initialized properly and, if
necessary, reinitialized each time they are used?
Does the code compile with no warnings from the compiler?
17
18. Other General Issues in Using Data
Do all variables have the smallest lift time possible?
Are references to variables as close together as possible?
Are all the declared variables being used?
Are all variables bound with balance between the
flexibility and the complexity associated?
Does each variable have only one purpose?
Is each variable's meaning explicit, with no hidden
meanings?
18
20. x = x - xx;
xxx = fido + SalesTax( fido );
x = x + LateFee( x1, x ) + xxx;
x = x + Interest( x1, x );
balance = balance - lastPayment;
monthlyTotal = newPurchases + SalesTax( newPurchases );
balance = balance + LateFee( customerID, balance ) +
monthlyTotal;
balance = balance + Interest( customerID, balance );
A good variable name is readable, memorable, and
appropriate .
20
21. The Most Important Naming Consideration:
Good name is to state what the variable represents.
Optimum Name Length.
Don’t be maximumNumberOfPointsInModernOlympics or np But
be teamPointsMax
21
22. Are short names always bad?
Common Opposites in Variable Names.
maxPoints OR pointsMax OR both ?
Avoid the confusion between maxPoints and
pointsMax .
The most significant part of the variable name is at the
front.
22
23. loop variables:
Don’t use i, j, and k if:
1. variable is to be used outside the loop.
2. the loop is longer than a few lines.
3. you write nested loops.
Try to avoid altogether .
Code is so often changed, expanded, and copied
into other programs.
23
24. Naming Status Variables:
A flag should never have flag in its name .
Use constants and enumerator for its value.
reportType == ReportType_Annual is more meaningful
than reportflag == 0x80 .
Naming Temporary Variables:
Use descriptive variable name instead of temp.
24
25. Naming Boolean Variables:
Give Boolean variables names that imply true or false.
(done , error ,found ,success)
Don’t use negative boolean variable names .
(if not notFound)
Naming Enumerated Types:
Using group prefix if your language doesn’t support.
Enum Color {Color_Red , Color_Green }
enum type itself can include prefix (enColor).
25
26. When Should Have a Naming Convention
When multiple programmers are working on a project
When you plan t turn a program over to another
programmer
When programs are reviewed by other programmers
When program is so large that you think about it in
pieces
When the program will be long-lived enough
26
27. Why we Have Conventions?
One global decision rather than many local ones .
They help you transfer knowledge across projects.
They reduce name proliferation.
They compensate for language weaknesses.
You work with a consistent code.
27
28. Differentiate between classes and objects via:
Initial Capitalization
Widget widget.
All Caps
WIDGET widget.
"t_" Prefix for Types
t_Widget Widget.
More Specific Names for the Variables
Widget employeeWidget .
Identify member variables.
with an m_ prefix.
28
29. Identify named constants .
Via uppercase letters.
Identify elements of enumerated types.
Use all caps or an e_ or E_ prefix for the name of the type.
Use a prefix based on the specific type like Color_Red.
Format names to enhance readability.
CIRCLEPOINTTOTAL is less readable than circlePointTotal or
circle_point_total.
29
30. Guidelines for Language-Specific Conventions:
i and j are integer indexes.
p is a pointer.
Constants and macros are in ALL_CAPS.
Class and other types are in MixedUpperAndLowerCase().
Variable and function names as variableOrRoutineName.
The underscore is not used as a separator within names, except
for names in all caps and certain kinds of prefixes
30
31. As avgSize, maxNum, firsIndex.
Advantages of Standardized Prefixes:
Naming conventions advantage +
You have fewer names to remember.
Make names more compact.
31
32. General Abbreviation Guidelines:
Remove all nonleading vowels (screen becomes scrn).
Remove and, or, the, and so on.
Use the first/first few letters of the name.
Keep the first and last letters of each word.
Remove useless suffixes—ing, ed, and so on.
Keep the most noticeable sound in each syllable.
Be sure not to change the meaning of the variable.
32
33. Comments on Abbreviations:
Don't abbreviate by removing one character from a word.
Abbreviate consistently.
Num everywhere or No .
Create names that you can pronounce
Use xPos rather than xPstn.
Avoid combinations that result in misreading .
Use bEnd/b_Endrather than bend
Use a thesaurus to resolve naming collisions.
Document all abbreviations in a document.
A reader of the code might not understand the abbreviation.
Other programmers might use multiple abbreviations to refer
to the same word.
33
34. Avoid misleading names or abbreviations.
As FALSE as abb for "Fig and Almond Season.“.
Avoid names with similar meanings.
As fileNumber and fileIndex .
Avoid variables with different meanings but similar names.
As clientRecs and clientReps .
Avoid names that sound similar.
As wrap and rap.
Avoid numerals in names.
As file1,file2
34
35. Avoid words that are commonly misspelled in English.
As occassionally, acummulate, and acsend.
Don't differentiate variable names solely by capitalization.
As count and Count.
Avoid multiple natural languages
As "color" or "colour”.
35
36. ?
programmers over the lifetime of a system
spend more time reading code than writing
code.
36
37. Steve McConnell, June 2004, Code Complete: A Practical Handbook of
Software Construction, 2nd edn.
37