6959192061c9a298410d3d3fc2b8e790.ppt
- Количество слайдов: 30
Variables Names CSC-3004 Introduction to Software Development Spring 2015 Dr. James Skon
Choosing Good Names Use names that fully and accurately describe the entity the variable represents. x = x - xx; xxx = fido + Sales. Tax( fido ); x = x + Late. Fee( x 1, x ) + xxx; x = x + Interest( x 1, x );
Choosing Good Names Use names that fully and accurately describe the entity the variable represents. balance = balance - last. Payment; monthly. Total = new. Purchases + Sales. Tax( new. Purchases ); balance = balance + Late. Fee( customer. ID, balance ) + monthly. Total; balance = balance + Interest( customer. ID, balance );
The Most Important Naming Consideration A variable name should fully and accurately describe the entity the variable represents. An effective technique for coming up with a good name is to state in words what the variable represents. It's easy to read because it doesn't contain cryptic abbreviations, and it's unambiguous. It's easy to remember because the name is similar to the concept.
Examples Purpose of Variable Good Names, Good Descriptors Bad Names, Poor Descriptors Running total of checks written to date running. Total, check. Total written, ct, checks, CHKTTL, x, x 1, x 2 Velocity of a bullet train velocity, train. Velocity, velocity. In. Mph velt, v, tv, x, x 1, x 2, train Current date current. Date, todays. Date cd, current, c, x, x 1, x 2, date Lines per page lines. Per. Page lpp, lines, l, x, x 1, x 2
Problem Orientation A good mnemonic name generally speaks to the problem rather than the solution. A good name tends to express the what more than the how. Problem Oriented Domain Oriented A record of employee data input. Rec employee. Data bit field indicating printer status bit. Flag printer. Ready.
Optimum Name Length The optimum length for a name seems to be somewhere between the lengths of x and maximum. Number. Of. Points. In. Modern. Olympics Names that are too short don't convey enough meaning. Names that are too long are hard to type and can obscure the visual structure of a program.
Optimum Name Length Too long: number. Of. People. On. The. Us. Olympic. Team number. Of. Seats. In. The. Stadium maximum. Number. Of. Points. In. Modern. Olympics Too short: n, np, ntm n, nsisd m, mp, max, points Just right: num. Team. Members, team. Member. Count num. Seats. In. Stadium, seat. Count team. Points. Max, points. Record
Scope and Variable Names Does Scope have an impact on variable naming? Consider: When you give a variable a short name like i, the length itself says something about the variable—namely, that the variable is a scratch value with a limited scope of operation. A study by W. J. Hansen found that longer names are better for rarely used variables or global variables and shorter names are better for local variables or loop variables (Shneiderman 1980).
Scope and Variable Names Use qualifiers on names that are in the global namespace. If you have variables that are in the global namespace (named constants, class names, and so on), consider whether you need to adopt a convention for partitioning the global namespace and avoiding naming conflicts. In C++ and C#, you can use the namespace keyword to partition the global namespace.
Scope and Variable Names If you declare an Employee class in both the User. Interface. Subsystem and the Database. Subsystem, you can identify which you wanted to refer to by writing User. Interface. Subsystem: : Employee or Database. Subsystem: : Employee.
Computed-Value Qualifiers in Variable Names Many programs have variables that contain computed values: totals, averages, maximums, and so on. If you modify a name with a qualifier like Total, Sum, Average, Max, Min, Record, String, or Pointer, put the modifier at the end of the name. E. g. revenue. Total, expense. Total, revenue. Average, and expense. Average has a pleasing symmetry. total. Revenue, expense. Total, revenue. Average, and average. Expense seem odd.
Naming Specific Types of Data Loop Indexes Status Variables Temporary Variables Boolean Variables Enumerated Types Constants
Naming Specific Types of Data Loop Indexes The names i, j, and k are customary: for ( i = first. Item; i < last. Item; i++ ) { data[ i ] = 0; } If a variable is to be used outside the loop, it should be given a more meaningful name: record. Count = 0; while ( more. Scores() ) { score[ record. Count ] = Get. Next. Score(); record. Count++; } // lines using record. Count
Naming Specific Types of Data Loop Indexes If you have several nested loops, assign longer names to the loop variables to improve readability. for ( team. Index = 0; team. Index < team. Count; team. Index++ ) { for ( event. Index=0; event. Index < event. Count[ team. Index ]; event. Index++ ) { score[ team. Index ][ event. Index ] = 0; } }
Naming Specific Types of Data Status Variables Think of a better name than flag for status variables. Assign flag values meaningful names. if ( flag ). . . if ( status. Flag & 0 x 0 F ). . . if ( print. Flag == 16 ). . . if ( compute. Flag == 0 ). . . if ( data. Ready ). . . if ( character. Type & PRINTABLE_CHAR ). . . if ( report. Type == Report. Type_Annual ). . . if ( recalc. Needed == True ). . . flag = 0 x 1; status. Flag = 0 x 80; print. Flag = 16; compute. Flag = 0; data. Ready = true; character. Type = CONTROL_CHARACTER; report. Type = Report. Type_Annual; recalc. Needed = false;
Naming Specific Types of Data Status Variables Assigning constants to status values can REALLY improve readability: // values for Character. Type const int LETTER = 0 x 01; const int DIGIT = 0 x 02; const int PUNCTUATION = 0 x 04; const int LINE_DRAW = 0 x 08; const int PRINTABLE_CHAR = ( LETTER | DIGIT | PUNCTUATION | LINE_DRAW ); const int CONTROL_CHARACTER = 0 x 80; // values for Report. Type enum Report. Type { Report. Type_Daily, Report. Type_Monthly, Report. Type_Quarterly, Report. Type_Annual, Report. Type_All };
Naming Specific Types of Data Temporary Variables Be leery of "temporary" variables: Calling a them temporary may indicate that you aren't sure of their real purposes. // Compute roots of a quadratic equation. // This assumes that (b^2 -4*a*c) is positive. temp = sqrt( b^2 - 4*a*c ); root[0] = ( -b + temp ) / ( 2 * a ); root[1] = ( -b - temp ) / ( 2 * a ); // Compute roots of a quadratic equation. // This assumes that (b^2 -4*a*c) is positive. discriminant = sqrt( b^2 - 4*a*c ); root[0] = ( -b + discriminant ) / ( 2 * a ); root[1] = ( -b - discriminant ) / ( 2 * a );
Naming Specific Types of Data Boolean Variables Keep typical boolean names in mind: done error found success or ok Give boolean variables names that imply true or false: status. OK source. File. Available
Naming Specific Types of Data Enumerated Types Use a prefix to make membership clear: Public Enum Color_Red Color_Green Color_Blue End Enum Public Enum Planet_Earth Planet_Mars Planet_Venus End Enum Public Enum Month_January Month_February. . . Month_December End Enum
Naming Specific Types of Data Constants Use all CAPS Name the abstract entity the constant represents rather than the number the constant refers to. FIVE BAKERS_DOZEN CYCLES_NEEDED DONUTS_MAX
Naming Conventions Why have a Naming Convention? One global decision rather then many local ones. Transfer knowledge across projects. Learn code on a new project faster. Reduce name proliferation. (point. Total and total. Points) They compensate for language weaknesses. They emphasize relationships among related items. (employee. Address, employee. Phone, and employee. Name )
Naming Conventions When You Should Have a Naming Convention When multiple programmers are working on a project. When you plan to turn a program over to another programmer for modifications and maintenance. When your program is large. 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.
Informal Naming Conventions Differentiate between variable names and routine names A common convention is to begin variable and object names with lower case and routine names with upper case: variable. Name vs. Routine. Name(). Differentiate between classes and objects The correspondence between class names and object names—or between types and variables of those types— can get tricky. Several standard options exist, as shown in the following examples.
Naming Conventions Capitalization Widget widget; Longer. Widget longer. Widget; All Caps WIDGET widget; LONGERWIDGET longer. Widget “t_” prefix on types t_Widget; t_Longer. Widget; “a” prefix for variables Widget a. Widget; Longer. Widget a. Longer. Widget; More specific names for variables Widget employee. Widget; Longer. Widget full. Employee. Widget;
C++ Conventions i and j are integer indexes. p is a pointer. Constants, typedefs, and preprocessor macros are in ALL_CAPS. Class and other type names are in Mixed. Upper. And. Lower. Case(). Variable and function names use lowercase for the first word, with the first letter of each following word capitalized—for example, variable. Or. Routine. Name. The underscore is not used as a separator within names, except for names in all caps and certain kinds of prefixes (such as those used to identify global variables).
Standardized Prefixes Standardizing prefixes for common meanings provides a terse but consistent and readable approach to naming data. Two Parts: the user-defined type (UDT) abbreviation semantic prefix.
Sample of UDTs for a Word Processor UDT Abbreviation ch doc pa scr sel wn Meaning Character Document Paragraph Screen region Selection Window
Example of UDTs for a Word Processor CH SCR DOC PA PA WN ch. Cursor. Position; scr. User. Workspace; doc. Active first. Pa. Active. Document; last. Pa. Active. Document; wn. Main;
6959192061c9a298410d3d3fc2b8e790.ppt