One of the biggest annoyances in everyday programming is naming variables, a good piece of code that both runs perfectly and is easy to maintain. This means that your code needs to be quickly readable by the person who will maintain it later, and that other developers will often read your code as part of a team. If your code is filled with A’s, B’s, C’s, A1’s, A2’s, A3’s… It was a nightmare. Therefore, good variable names are very important.
Choose the considerations for variable names
A variable and its name are essentially the same thing, so a variable is good or bad to a large extent depending on how good or bad its name is.
Here is an example of bad naming
$pp = ($cp > 1) ? ($cp - 1) : $cp;
$np = ($cp < $tp) ? ($cp + 1) : $tp;
$p = new P($pp, $cp, $np, $tp);
Copy the code
What is this code doing? You can probably get a sense of what information you’re counting, but what information are you counting? $p,$pp,np,$TP, etc. What do these variables represent? Seriously, without any comments, it’s impossible for anyone not to understand what this code is trying to say. If the person who wrote this code tells you that this code is computing paging information and then instantiating a paging class, what should you name it?
$prev_page_num = ($curr_page_num > 1)? ($curr_page_num - 1) : $curr_page_num); $next_page_num = ($next_page_num < $total_page_num) ? ($curr_page_num + 1) : $total_page_num); $page = new Page($prev_page_num, $curr_page_num, $next_page_num, $total_page_num);Copy the code
As you can see from the above two pieces of code, a good variable name is extremely important for readability and maintainability. And good variable names are easy to remember. These goals can be achieved by applying a number of principles.
The most important naming considerations
- The name is a complete and accurate description of what the variable represents
- What does a variable stand for in a name, without arcane abbreviations, and without ambiguity
The following table gives some examples of variable names, both good and bad.
Variable use | Good name, good description | Bad name, bad description |
---|---|---|
The sum of cheques due | runningTotal,checkTotal | written,ct,checks,CHKTTL,x,x1,x2 |
The speed of a high-speed train | velocity,trainVelocity,velocityInMph | velt,v,tv,x,x1,x2,train |
The current date | currentDate,todaysDate | cd,current,c,x,x1,x2,date |
The number of lines per page | linesPerPage | lpp,lines,l,x,x1,x2 |
CurrentDate and todaysDate are good names because they describe the concept of “currentDate” completely and accurately.
CD and C are terrible names because they use too short abbreviations and are not descriptive.
Current is also bad because it doesn’t tell you what it is.
Date looks good, but in the end it’s just a bad name, because it doesn’t mean all dates. It just means the current date, and it doesn’t mean anything like that.
X,x1 and x2 are always bad names — traditionally x is an unknown quantity, and if you don’t want your variable to be an unknown quantity, consider a better name.
The name should be as clear as possible. Names like X, temp, and I are generic and can be used for a variety of purposes, but they don’t provide as much information as they should, and are often a naming failure.
Problem oriented
A catchy name usually reflects a problem, not a solution. That is, a good name usually expresses What, not How. Generally speaking, if a name reflects some aspect of the computer rather than the problem itself, it reflects “How” rather than “What”.
For example, consider the following variable names: inputRec and employeeData. InputRec is a computer term that reflects input and records these computational concepts. EmployeeData refers to the problem domain, not the computer. Similarly, printerReady is a better representation of the printer’s state than bitFlag; In financial software, calcVar is more accurate than sum.
The most appropriate name length
Studies have found that debugging effort is minimal when the average length of variable names is between 10 and 16 characters. Programs with an average name length of 8 to 20 characters are almost as easy to debug. This doesn’t mean your variable names have to be between 8 and 20 characters long. It does mean that if you look at your code and find a lot of shorter names, you need to check them carefully to make sure they are clear.
Here is an example of a variable name that is too long, too short, or just right:
Too long: numberOfPeopleOnTheUsOlympicTeam; numberOfSeatsInTheStadium; maximumNumberOfPointsInModernOlympics
Too short: n, NP, NTM; n, ms, nsisd; m, mp, max, points
NumTeamMembers, teamMemberCount; numSeatsInStadium, seatCount; teamPointsMax, pointsRecord
A calculated value qualifier in a variable name
Many programs have variables that represent the results of a calculation: total, average, maximum, and so on. If you want to change a name with qualifiers like Total, Sum, Average, Max, Min, Record, String, Pointer, remember to add the qualifier to the end of the name.
The advantages of this approach are as follows: > * The most important part of the variable name, that is, the part that gives the main meaning to the variable, should come first so that this part stands out and is read first; > * avoiding ambiguity due to using totalRevenue and revenueTotal in programs at the same time > * using a uniform coding specification improves readability and simplifies maintenance. For example, revenueTotal, expenseTotal, revenueAverage, expenseAverage have very elegant symmetry. But totalRevenue, expenseTotal, revenueAverage, averageRevenue this group of names can not see any rules.
The exception to this rule is that the position of the determiner of Num is already a convention. Num at the beginning of a variable name represents a total number, for example, numCustomers represents the total number of employees. Num at the end of the variable name represents a subscript: customerNum represents the serial number of the current employee. The use of Num in this way is often troublesome, so it is best to avoid these problems and use Count or Total to represent the Total, and Index to refer to a particular employee. In this way, customerCount represents the total number of employees and customerIndex represents a specific employee.
Common antithesis words in variable names
Antithesis words should be used correctly, otherwise there will be ambiguity.
Commonly used antithesis words are as follows: > * begin/end > * first/last > * locked/unlocked > * min/max > * next/previous > * old/new > * opened/closed > * visible/invisible > * source/target > * source/destination > * up/down
Give names to specific types of data
In addition to the usual considerations of naming variables, naming certain types of data requires some special considerations. For example, loop variables, state variables, temporary variables, and so on.
Name the loop subscript
The most common subscript variables in a loop are I,j,k, for example:
for(i = 0; i < arrLen; i++) {
// ...
}
Copy the code
This is fine if the loop subscript variable is used only inside the loop, but if the variable needs to be used outside the loop, it should be given a name that makes more sense than I,j, and k. For example, if you read records from a file and need to keep track of the number of records read, a name like redcordCount would be more appropriate:
recordCount = 0;
while ( moreScores() ) {
score[recordCount] = GetNextScore();
recordCount++;
}
// using recordCount
Copy the code
Another case is nested loops, and a common mistake is to write I when you want to write j, j when you want to write I.
If you use multiple nested loops, you should give loop variables longer names to improve readability:
for ( teamIndex = 0; teamIndex < teamCount; teamIndex++) { for ( eventIndex = 0; eventIndex < eventCount[teamIndex]; eventIndex++) { score[teamIndex][eventIndex] = 0; }}Copy the code
Score [teamIndex][eventIndex] gives more information than score[I][J].
Note: If you must use I, j, and k, do not use them for anything other than the loop subscripts of simple loops to avoid misunderstanding. The easiest way to avoid this problem is to use better names than I, j, k.
Name state variables
Give the state variable a better name than flag.
It is best to think of tags as state variables. Flags should not have a flag in their name, because you can’t tell what the flag does.
To be clearly visible, the tag should be assigned using an enumeration variable, a named constant, or a global variable used as a named constant.
Take a look at the following poor tag naming:
if ( flag ) ...
if ( statusFlag & 0x0F ) ...
if ( printFlag == 16 ) ...
if ( computeFlag == 0 ) ...
flag = 0x1;
statusFlag = 0x80;
printFlag = 16;
computeFlag = 0;
Copy the code
The above code doesn’t reflect what you can do, and without documentation, you don’t know what statusFlag = 0x80 means. Here’s the same but clearer code:
if ( dataReady ) ...
if ( characterType & PRINTABLE_CHAR ) ...
if ( reportType == ReportTyoe_Annual ) ...
if ( recalcNeeded == false ) ...
dataReady = true;
characterType = CONTRAL_CHARACTER;
reportType = ReportType_Annual;
recalNeeded = false;
Copy the code
This code is clearer. It also shows that you can use this method in combination with enumerated types and predefined named constants.
If you find yourself guessing the meaning of a piece of code, consider renaming variables. Code should be as straightforward to read as possible.
Name temporary variables
Temporary variables are often used to store intermediate results of calculations, as temporary placeholders, and to store internal values. They are often given names like temp, TMP, X, or some other vague and undescriptive name. Often, temporary variables are a signal that the edge has not fully figured out the problem. Moreover, because these variables are officially assigned a “temporary” state, programmers tend to treat them more casually than other variables, increasing the potential for error.
Beware of temporary variables
It is necessary to hold some variables temporarily. But most variables in a program are temporary by any measure. Calling a few of them temporary may indicate that you haven’t figured out what they’re actually for. Take a look at the following example:
temp = sqrt( b^2 - 4*a*c );
root[0] = ( -b + temp ) / ( 2*a );
root[1] = ( -b - temp ) / ( 2*a );
Copy the code
Better practice:
discriminant = sqrt( b^2 - 4*a*c );
root[0] = ( -b + discriminant ) / ( 2*a );
root[1] = ( -b - discriminant ) / ( 2*a );
Copy the code
Discriminant
Name a Boolean variable
Typical Boolean variable names: > * done > * error > * found > * SUCCESS/OK
Names that give Boolean variables an implied true/false meaning. Like done and success, they either have a value of true or false to indicate that something is completed or not; Success or failure. On the other hand, names like Status are bad Boolean variable names because they don’t have an explicit true or false. What does it mean that status is true? Does something have a state? However, everything has a state. Does true indicate that something is OK? Or does false mean there is no error? You can’t say anything about Status.
For better effect, you can name status error or statusOK.
Sometimes, the Boolean variable name can also be preceded by Is. Thus, the variable name becomes a problem: isDone? isError? isFound? Answering the question with true or false gives the variable its value. The advantage is that you can’t use vague names like isStatus? It makes no sense. The disadvantage is that it reduces the readability of simple logical expressions: if(isFound) is slightly less readable than if(Found).
Use positive Boolean variable names. Avoid double negatives: not notFound.
Name the enumeration type
When enumeration types are used, use group prefixes such as Color_, Planet_, or Month_ to specify that members of this type belong to the same group. Such as:
Public Enum Color Color_Red Color_Green Color_Blue End Enum Public Enum Planet Planet_Earth Planet_Mars Planet_Venus End EnumCopy the code
In some programming languages, enumerated types are treated much like classes and are always prefixed with an enumeration name, such as color.color_red or planet.planet_earth. If you are using such a programming language, repeating the prefix above makes little sense and can be simplified to color. Red and planet.earth.
Naming constants
In the case of a named constant, the abstract thing should be named according to the meaning it represents, not the value it has. For example, FIVE is a bad constant name and CYCLES_NEEDED is a good one.
The power of naming conventions
Many programmers resist standards and conventions (and sometimes I do), and for good reason: Some standards and conventions are rigid and inefficient — they destroy creativity and program quality.
Why should there be rules
- Demanding that you play by the rules more. Focus on the more important features of your code;
- Helps transfer knowledge between projects;
- Helps you learn code faster on new projects;
- Helps to reduce name proliferation, where it is easy to give the same object two different names without rules;
- Make up for the shortcomings of programming languages;
- Emphasize the relationships between related variables.
The point is, any rule is better than no rule. Rules can be arbitrary. The power of naming conventions comes not from any particular rule you adopt, but from the fact that they add structure to your code and reduce the number of things you have to think about.
When to adopt naming rules
- When multiple programmers work together on a project
- When you plan to hand over a program to another programmer for modification and maintenance
- When other programmers in your organization evaluate your program
- When you write programs so large that you can’t see the whole picture in your head at the same time, and you have to divide and conquer
- You write a program with a lifetime long enough that you may be able to restart work on it after leaving it on hold for weeks or months
- When there are some unusual terms in a project and you want to use standard terms or abbreviations during the coding phase
Informal naming rules
Although many standard naming conventions have been introduced, most projects use relatively informal naming conventions.
Guidelines for language-independent naming conventions
- Distinguish variable names from subroutine names
- Zone categories and objects
- Identify global variables
- Identify member variables
- Identification type declaration
- Identified named constant
- An element that identifies an enumeration type
- Identify read-only parameters in languages that cannot guarantee that input parameters are read-only
- Format names to improve readability
Try not to mix the above methods; it will make the code harder to read. Honestly stick with any of these readability methods and your code quality will improve.
Guidelines for naming conventions related to languages
Follow the naming conventions of your language. For most languages, you can find reference books that describe their style principles. Here are some guidelines for C.
C naming rules
- C and CH are character variables
- I and j are integer subscripts
- N is the amount of something
- P is a pointer
- S is a string
- Preprocessor macros are all uppercase, usually including typedef
- All variable and subroutine names are lowercase
- The underscore is used as a delimiter, such as letters_in_lowercase
The standard prefix
Standardizing prefixes with common meanings provides a concise, consistent, and readable way to name data.
Standardized prefixes consist of two parts: abbreviations for user-defined types (UDT) and semantic prefixes.
User-defined type abbreviation
UDT abbreviations can identify the data type of the named object or variable. UDT abbreviations generally do not represent any preset data types provided by the programming language. An example of UDT is listed below.
UDT abbreviations | meaning |
---|---|
ch | Character (Character) |
doc | The Document (the Document) |
pa | Paragraphs (com.lowagie.text.paragraph) |
scr | Screen Region |
sel | Selection range |
wn | Window (the Window) |
The following data declarations can be defined using the UDT types listed in the table above:
CH chCursorPosition;
SCR srcUserWorkSpace;
DOC docActive;
PA firstPaActiveDocument;
PA lastPaActiveDocument;
WN wnMain;
Copy the code
Semantic prefix
Semantic prefixes go one step further than UDTs and describe how variables or objects are used. And the semantic prefixes do not vary from project to project; they are standard for different projects. Below is a list of standard semantic prefixes.
Semantic prefix | meaning |
---|---|
c | The number (count) |
first | The first element in the array to be processed |
g | The global variable |
i | The index of the array |
last | The last element in the array to process, corresponding to first |
lim | The upper limit on the number of elements in the array to process. In general, lim is equal to last+1 |
m | Class level variables |
max | The absolute last element in an array or other kind of list |
min | The absolute first element in an array or other kind of list |
p | Pointer (pointer) |
The pros and cons of standard prefixes
- Can more accurately describe some obscure names
- Make the name more compact
Bug: Programmers neglect to give variables meaningful names while using prefixes.
Create readable short names
If circumstances do require you to create shorter names, be aware that some shortening methods are better than others.
General guidelines for abbreviations
Here are a few guidelines for creating abbreviations. Some of these principles conflict with each other, so don’t try to apply them all at once. > * Use standard abbreviations > * remove all non-front vowels (computer => CMPTR, screen => SCRN, apple => appl, interger => intgr) > * Remove function words and, or, The etc. > * Use the first or first few letters of each word > * Truncate the first, second or third letters of each word consistently > * Keep the first and last letters of each word > * Use every important word in the name up to three more > * Remove the useless suffix — ing, Ed et al. > * Keep the most striking sounds in each syllable > * Be sure not to change the meaning of the variables > * Repeat the above techniques until you have reduced the length of each variable name to 8-20 characters.
Voice abbreviations
Some advocate creating abbreviations based on the sound of the word rather than the spelling, such as skating => sk8ing, before => b4… But it’s not recommended.
Comments about abbreviations
Here are some rules you can use to avoid making mistakes. > * Don’t abbreviate by removing one character from each word, either remove more than one character or spell the word completely. > * Abbreviate consistently, such as: Use either Num or No, not both, to create names that you can pronounce, e.g., xPos instead of xPstn. * Avoid misread or mispronounced character combinations, such as ENDB and BEND. To indicate the end of a B, use a good separator technique: B_end /BEnd > * Use dictionaries to resolve naming conflicts, use synonyms to resolve naming conflicts > * Use abbreviations in code to explain the meaning of extremely short names
Names to avoid
- Avoid misleading names or abbreviations, such as “Fig and Almond Season” FALSE
- Avoid names with similar meanings
- Avoid variables with similar names that have different meanings
- Avoid names that sound similar
- Avoid using numbers in names
- Avoid misspelling words in names
- Avoid English words that are often misspelled
- Do not rely on case alone to distinguish variable names
- Avoid using multiple natural languages
- Avoid standard types, variables, and subroutine names
- Do not use names that have nothing to do with the meaning of the variable
- Avoid confusing characters in names, such as 1(number 1) and L (letter L),0(number 0) and O(letter O)
conclusion
Good variable names are a key element in improving program readability. Code is read far more often than it is written, so make sure the names in your code are more about ease of reading than ease of writing. Pick a rule and stick to it.
Original article, writing is limited, talent and learning shallow, if the article is not straight, hope to inform.
If this article is helpful to you, please click the recommendation below, thanks ^_^