Download presentation
Presentation is loading. Please wait.
Published byHarley Wakeman Modified over 9 years ago
1
Variables and Powerful Names Nathan Scheck CS525 Software Engineering II Fall II 2007 – Sheldon X. Liang, Ph.D. Nathan Scheck CS525 Software Engineering II Fall II 2007 – Sheldon X. Liang, Ph.D.
2
Steve McConnell’s Guidelines for the Smart Use of Variables
3
Implicit Declarations Some compilers don ’ t require you to define variables before their first use. “ One of the most hazardous features in any language. ” Much easier to make mistakes. Some compilers don ’ t require you to define variables before their first use. “ One of the most hazardous features in any language. ” Much easier to make mistakes.
4
Implicit Declarations What should you do about it? Turn implicit declarations off. Declare all variables anyway. Use naming conventions (num vs. no) Check variable name listings from compiler. What should you do about it? Turn implicit declarations off. Declare all variables anyway. Use naming conventions (num vs. no) Check variable name listings from compiler.
5
Initializing Variables Improper data initialization is one of the most fertile sources of error in computer programming. This may result in some of the following problems when a variable is used: It has never been assigned a value. It is outdated. Only part of the variable is defined. Improper data initialization is one of the most fertile sources of error in computer programming. This may result in some of the following problems when a variable is used: It has never been assigned a value. It is outdated. Only part of the variable is defined.
6
Initializing Variables Initialize each variable close to where it is first used. Bad Initialization // initialize variables accountIndex = 0 total = 0.0 done = false … // code using accountIndex … // code using total … // code using done Good Initialization accountIndex = 0 // code using accountIndex … total = 0.0 // code using total … done = false // code using done
7
Initializing Variables Other guidelines Use “final” or “const” when possible. Pay special attention to counters and accumulators (i, j, k, sum) Initialize a class’s member data in its constructor. Take advantage of compiler warnings. Use a memory-access checker to find bad pointers. Other guidelines Use “final” or “const” when possible. Pay special attention to counters and accumulators (i, j, k, sum) Initialize a class’s member data in its constructor. Take advantage of compiler warnings. Use a memory-access checker to find bad pointers.
8
Scope Local is usually better than global. Keep “live time” as short as possible. Local is usually better than global. Keep “live time” as short as possible.
9
Scope General guidelines for minimizing scope Initialize variables used in a loop immediately before the loop. Don’t assign a value to a variable until just before it is used. Group related statements. (Or give them their own routine.) Begin by restricting variable visibility as much as possible. Expand scope only when necessary. General guidelines for minimizing scope Initialize variables used in a loop immediately before the loop. Don’t assign a value to a variable until just before it is used. Group related statements. (Or give them their own routine.) Begin by restricting variable visibility as much as possible. Expand scope only when necessary.
10
Binding Time When is a variable given its value? When the code is written color = 0xFF; When it is compiled define USE_COLOR = 0xFF; color = USE_COLOR; When the program is run color = getUserColorInput(); When is a variable given its value? When the code is written color = 0xFF; When it is compiled define USE_COLOR = 0xFF; color = USE_COLOR; When the program is run color = getUserColorInput();
11
Binding Time The “earlier” you bind a value to a variable, the less flexible your code is, but the more simple and less error-prone. Binding later adds more flexibility, but also complexity (and the possibility of more errors). The “earlier” you bind a value to a variable, the less flexible your code is, but the more simple and less error-prone. Binding later adds more flexibility, but also complexity (and the possibility of more errors).
12
Use Variables for One Purpose It’s sometimes tempting to use one variable in two different places for two different activities. Usually, the variable is named inappropriately for one of its uses or a “temp” variable is used in both cases. This is not helpful. It’s sometimes tempting to use one variable in two different places for two different activities. Usually, the variable is named inappropriately for one of its uses or a “temp” variable is used in both cases. This is not helpful.
13
Use Variables for One Purpose One Variable for Two Purposes // 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; Two Variables for Two Purposes // Compute roots of a quadratic equation. 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;
14
Use Variables for One Purpose Avoid variables with hidden meanings “pageCount represents the number of pages, unless it equals -1, which means there was an error.” “customerId represents the 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.” Avoid variables with hidden meanings “pageCount represents the number of pages, unless it equals -1, which means there was an error.” “customerId represents the 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.”
15
Use Variables for One Purpose Make sure that all declared variables are used. A study by Card, Church, and Agresti found that unreferenced variables were correlated with higher fault rates. Some compilers and utilities will report unused variables as warnings. Make sure that all declared variables are used. A study by Card, Church, and Agresti found that unreferenced variables were correlated with higher fault rates. Some compilers and utilities will report unused variables as warnings.
16
Choosing Variable Names Poor Variable Names x = x - xx; xxx = fido + SalesTax( fido ); x = x + LateFee( x1, x ) + xxx; x = x + Intereset( x1, x ); Good Variable Names balance = balance - lastPayment; monthlyTotal = newPurchases + SalesTax( newPurchases ); balance = balance + LateFee( customerID, balance ) + monthlyTotal; balance = balance + Interest( customerID, balance );
17
Choosing Variable Names The variable name should fully and accurately describe the entity it represents. Example: Purpose of variable: the current date Good names: currentDate, todaysDate Bad names: cd, date, current The variable name should fully and accurately describe the entity it represents. Example: Purpose of variable: the current date Good names: currentDate, todaysDate Bad names: cd, date, current
18
Choosing Variable Names The name should describe the problem, rather than the solution. (“what” instead of “how”) Examples: For a record of employee data: employeeData rather than inputRecord For a bit field indicating if printer is ready: printerReady rather than bitFlag The name should describe the problem, rather than the solution. (“what” instead of “how”) Examples: For a record of employee data: employeeData rather than inputRecord For a bit field indicating if printer is ready: printerReady rather than bitFlag
19
Choosing Variable Names The optimal length for a variable name is between 8 and 20 characters. Too long: numberOfPeopleOnTheUsOlympicTeam numberOfSeatsInTheStadium Too short: n, np, ntm n, ns, nsisd Just right: numTeamMembers, teamMemberCount numSeatsInStadium, seatCount The optimal length for a variable name is between 8 and 20 characters. Too long: numberOfPeopleOnTheUsOlympicTeam numberOfSeatsInTheStadium Too short: n, np, ntm n, ns, nsisd Just right: numTeamMembers, teamMemberCount numSeatsInStadium, seatCount
20
Choosing Variable Names Be consistent Standardize common qualifiers such as Total, Sum, Max, Str, or Ptr Consistently put qualifiers at the end of the name (costTotal, frogMax) You won’t have to guess whether it’s frogMax or maxFrogs The important part of the variable name comes first. (“What is the variable about”) Be consistent Standardize common qualifiers such as Total, Sum, Max, Str, or Ptr Consistently put qualifiers at the end of the name (costTotal, frogMax) You won’t have to guess whether it’s frogMax or maxFrogs The important part of the variable name comes first. (“What is the variable about”)
21
Naming Specific Types of Data Loop Indexes i, j, and k are customary If a “counter” variable will be used outside the loop, give it a better name. Loop Indexes i, j, and k are customary If a “counter” variable will be used outside the loop, give it a better name. Good Descriptive Loop Variable Name recordCount = 0; while ( moreScores() ) { score[ recordCount ] = GetNextScore(); recordCount++; } // lines using recordCount...
22
Naming Specific Types of Data Status Variables Don’t use “flag” in the name. It doesn’t tell you anything helpful. Remember: the name should say “what” it’s for, not how it does it. Status Variables Don’t use “flag” in the name. It doesn’t tell you anything helpful. Remember: the name should say “what” it’s for, not how it does it. Bad if ( flag )... if ( printerFlag == 16 )... if (computerFlag == 0 )... Good if ( done )... if ( printerStatus == printerStatus_Ready )... if ( recalcNeeded == false )...
23
Naming Specific Types of Data Boolean Variables Keep “typical” names in mind: done error found success Use a name that implies true or false. Use “positive” names found instead of notFound if ( not found ) is easier to understand than if ( not notFound ) Boolean Variables Keep “typical” names in mind: done error found success Use a name that implies true or false. Use “positive” names found instead of notFound if ( not found ) is easier to understand than if ( not notFound )
24
Naming Specific Types of Data Enumerated Types Use the type name as the prefix for each member of the type for clarity. Enumerated Types Use the type name as the prefix for each member of the type for clarity. Examples Public Enum Color Color_Red Color_Green Color_Blue End Enum Public Enum Planet Planet_Earth Planet_Mars End Enum
25
Naming Conventions Why have conventions? They let you take more for granted. One global decision rather than many local ones. They help you transfer knowledge across projects. They reduce name proliferation. You’re less likely to accidentally use totalPoints when you mean pointTotal. Why have conventions? They let you take more for granted. One global decision rather than many local ones. They help you transfer knowledge across projects. They reduce name proliferation. You’re less likely to accidentally use totalPoints when you mean pointTotal.
26
Naming Conventions Why have conventions? (cont.) They emphasize relationships among related items. This is especially helpful if your language doesn’t support objects. Why have conventions? (cont.) They emphasize relationships among related items. This is especially helpful if your language doesn’t support objects. Settings Data as Object settings.font = ‘helvetica’; settings.fontSize = 14; settings.fontColor = ‘red’; Settings Data without Object settings_font = ‘helvetica’; settings_fontSize = 14; settings_fontColor = ‘red’;
27
Naming Conventions When should you have a naming convention? When multiple programmers are working on a project When another programmer will be doing maintenance on your project When your code is reviewed by other programmers in the organization When should you have a naming convention? When multiple programmers are working on a project When another programmer will be doing maintenance on your project When your code is reviewed by other programmers in the organization
28
Naming Conventions When should you have a naming convention? (cont.) When your program is so large that you must think about it in pieces. When you might have to come back to it after a few weeks of being away. When you have a lot of unusual terms that are common on a project and want to have standard terms or abbreviations to use in coding. When should you have a naming convention? (cont.) When your program is so large that you must think about it in pieces. When you might have to come back to it after a few weeks of being away. When you have a lot of unusual terms that are common on a project and want to have standard terms or abbreviations to use in coding.
29
Informal Language-Independent Naming Convention Guidelines Differentiate between variables and routines variableName vs. RoutineName() Differentiate between classes and objects Use a more specific name for the variable. If class is Widget, variable could be employeeWidget. Identify global variables For example, g_RunningTotal Differentiate between variables and routines variableName vs. RoutineName() Differentiate between classes and objects Use a more specific name for the variable. If class is Widget, variable could be employeeWidget. Identify global variables For example, g_RunningTotal
30
Informal Language-Independent Naming Convention Guidelines Identify class member variables One method is to use a prefix of m_ Identify type definitions All caps, or a t_ prefix Identify named constants All caps, or a c_ prefix Identify enumerated types e_ or E_ prefix Identify class member variables One method is to use a prefix of m_ Identify type definitions All caps, or a t_ prefix Identify named constants All caps, or a c_ prefix Identify enumerated types e_ or E_ prefix
31
Informal Language-Independent Naming Convention Guidelines Identify input-only parameters in languages that don’t enforce them Use const_ or final_ prefixes on parameters that should not be modified. Format names for readibility GYMNASTICSPOINTTOTAL is harder to read than gymnasticsPointTotal or gymnastics_point_total Identify input-only parameters in languages that don’t enforce them Use const_ or final_ prefixes on parameters that should not be modified. Format names for readibility GYMNASTICSPOINTTOTAL is harder to read than gymnasticsPointTotal or gymnastics_point_total
32
Conclusion Be consistent. Be helpful. Be consistent. Be helpful.
33
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.