Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables Names CSC-3004 Introduction to Software Development

Similar presentations


Presentation on theme: "Variables Names CSC-3004 Introduction to Software Development"— Presentation transcript:

1 Variables Names CSC-3004 Introduction to Software Development
Spring 2015 Dr. James Skon

2 Choosing Good Names Use names that fully and accurately describe the entity the variable represents. x = x - xx; xxx = fido + SalesTax( fido ); x = x + LateFee( x1, x ) + xxx; x = x + Interest( x1, x );

3 Choosing Good Names Use names that fully and accurately describe the entity the variable represents. balance = balance - lastPayment; monthlyTotal = newPurchases + SalesTax( newPurchases ); balance = balance + LateFee( customerID, balance ) + monthlyTotal; balance = balance + Interest( customerID, balance );

4 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.

5 Examples Purpose of Variable Good Names, Good Descriptors
Bad Names, Poor Descriptors Running total of checks written to date runningTotal, checkTotal written, ct, checks, CHKTTL, x, x1, x2 Velocity of a bullet train velocity, trainVelocity, velocityInMph velt, v, tv, x, x1, x2, train Current date currentDate, todaysDate cd, current, c, x, x1, x2, date Lines per page linesPerPage lpp, lines, l, x, x1, x2

6 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 inputRec employeeData bit field indicating printer status bitFlag printerReady.

7 Optimum Name Length The optimum length for a name seems to be somewhere between the lengths of x and maximumNumberOfPointsInModernOlympics 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.

8 Optimum Name Length Too short: Too long: Just right:
numberOfPeopleOnTheUsOlympicTeam numberOfSeatsInTheStadium maximumNumberOfPointsInModernOlympics Too short: n, np, ntm n, ns, nsisd m, mp, max, points Just right: numTeamMembers, teamMemberCount numSeatsInStadium, seatCount teamPointsMax, pointsRecord

9 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).

10 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.

11 Scope and Variable Names
If you declare an Employee class in both the UserInterfaceSubsystem and the DatabaseSubsystem, you can identify which you wanted to refer to by writing UserInterfaceSubsystem::Employee or DatabaseSubsystem::Employee.

12 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. revenueTotal, expenseTotal, revenueAverage, and expenseAverage has a pleasing symmetry. totalRevenue, expenseTotal, revenueAverage, and averageExpense seem odd.

13 Naming Specific Types of Data
Loop Indexes Status Variables Temporary Variables Boolean Variables Enumerated Types Constants

14 Naming Specific Types of Data
Loop Indexes The names i, j, and k are customary: If a variable is to be used outside the loop, it should be given a more meaningful name: for ( i = firstItem; i < lastItem; i++ ) { data[ i ] = 0; } recordCount = 0; while ( moreScores() ) { score[ recordCount ] = GetNextScore(); recordCount++; } // lines using recordCount

15 Naming Specific Types of Data
Loop Indexes If you have several nested loops, assign longer names to the loop variables to improve readability. for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) { for ( eventIndex=0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) { score[ teamIndex ][ eventIndex ] = 0; }

16 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 ( statusFlag & 0x0F ) ... if ( printFlag == 16 ) ... if ( computeFlag == 0 ) ... flag = 0x1; statusFlag = 0x80; printFlag = 16; computeFlag = 0; if ( dataReady ) ... if ( characterType & PRINTABLE_CHAR ) ... if ( reportType == ReportType_Annual ) ... if ( recalcNeeded == True ) ... dataReady = true; characterType = CONTROL_CHARACTER; reportType = ReportType_Annual; recalcNeeded = false;

17 Naming Specific Types of Data
Status Variables Assigning constants to status values can REALLY improve readability: // values for CharacterType const int LETTER = 0x01; const int DIGIT = 0x02; const int PUNCTUATION = 0x04; const int LINE_DRAW = 0x08; const int PRINTABLE_CHAR = ( LETTER | DIGIT | PUNCTUATION | LINE_DRAW ); const int CONTROL_CHARACTER = 0x80; // values for ReportType enum ReportType { ReportType_Daily, ReportType_Monthly, ReportType_Quarterly, ReportType_Annual, ReportType_All };

18 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 );

19 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  statusOK sourceFile  sourceFileAvailable

20 Naming Specific Types of Data
Public Enum Color Color_Red Color_Green Color_Blue End Enum Public Enum Planet Planet_Earth Planet_Mars Planet_Venus Public Enum Month Month_January Month_February ... Month_December Enumerated Types Use a prefix to make membership clear:

21 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

22 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. (pointTotal and totalPoints) They compensate for language weaknesses . They emphasize relationships among related items. (employeeAddress, employeePhone, and employeeName )

23 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.

24 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: variableName vs. RoutineName(). 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.

25 Naming Conventions Capitalization “a” prefix for variables
Widget widget; LongerWidget longerWidget; Widget aWidget; LongerWidget aLongerWidget; All Caps More specific names for variables WIDGET widget; LONGERWIDGET longerWidget Widget employeeWidget; LongerWidget fullEmployeeWidget; “t_” prefix on types t_Widget Widget; t_LongerWidget LongerWidget;

26 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 MixedUpperAndLowerCase(). Variable and function names use lowercase for the first word, with the first letter of each following word capitalized—for example, variableOrRoutineName. 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).

27 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.

28 Sample of UDTs for a Word Processor
UDT Abbreviation Meaning ch Character doc Document pa Paragraph scr Screen region sel Selection wn Window

29 Example of UDTs for a Word Processor
CH chCursorPosition; SCR scrUserWorkspace; DOC docActive PA firstPaActiveDocument; PA lastPaActiveDocument; WN wnMain;

30


Download ppt "Variables Names CSC-3004 Introduction to Software Development"

Similar presentations


Ads by Google