Current location - Quotes Website - Team slogan - Programming slogan
Programming slogan
Naming can be seen everywhere in software: naming variables, functions, parameters, classes and packages, naming source codes and their directories, and even naming jar files, war files and ear files.

However, seemingly simple naming is also a headache for many programmers. Some friends, when naming variables, even use English to name their familiar English. If the parts that need to be named are not expressed in English, they may just use pinyin.

Some children's shoes suddenly can't remember how to name them. It is meaningless to name directly with pinyin and letters such as aa and bb. They are poorly readable. Maybe they wrote it today and came back a week later and forgot the meaning of the specific representative.

Therefore, many people always think and think before writing code. What naming method should be used? For obsessive-compulsive patients who often switch between mainstream languages such as C++, Java and Python, it should not be too confusing to change the language and naming style.

Since there are so many names to be made, it is better to do them well. In this issue, Asynchronous Jun brings you a few simple rules to follow when making a good name. Let's have a look.

— 0 1 —

worthy of one’s name

Being worthy of the name is simple to say. What we want to emphasize is that this matter is very serious. It takes time to choose a good name, but it saves more time than it takes. Pay attention to naming. Once you find a better name, replace the old one. By doing so, people who read your code (including yourself) will be happier.

The name of a variable, function or class should have answered all the big questions. It should tell you why it exists, what it does and how to use it. If the name needs additional comments, it is not worthy of the name.

The name d means nothing. It doesn't cause the reader the feeling of time passing, let alone counting by day. We should choose names that represent objects and units of measurement:

Choosing a name that reflects the original meaning can make it easier for people to understand and modify the code. What is the purpose of the following code?

Why is it difficult to explain what the above code is going to do? There are no complicated expressions, spaces and indents are quite satisfactory, only three variables and two constants are used, and even other classes or polymorphic methods are not involved, just (or seem to be) an array list.

The problem is not the simplicity of the code, but the fuzziness of the code: that is, the degree to which the context is not clearly reflected in the code. The above code requires us to know the answers to the following questions:

(1) What kinds of things are there in the list?

(2) What is the significance of the items marked below zero in the list?

(3) What is the meaning of the value 4?

(4) How to use the returned list?

The answers to the questions are not reflected in the code snippet, but the code snippet is where they should be. For example, we are developing a mine-sweeping game. We found that the disk is a list of cells named theList, so we changed its name to gameBoard.

Each cell on the disk is represented by a simple array. We also find that the marked item below zero is a status value, and the status value of 4 means "marked". As long as it is changed to a meaningful name, the code will be improved to a considerable extent:

Note that the simplicity of the code is not touched. The number of operators and constants remains the same, and the number of nesting remains the same, but the code becomes much clearer.

You can go one step further and write another class to represent cells instead of int arrays. This class contains a veritable function (called isFlagged), thus masking the magic number [1]. So you get a new version of the function:

You can easily know what happened by simply changing the name. This is the power of choosing a good name.

— 02 —

Avoid misleading

Programmers must avoid leaving false clues to hide the original intention of the code. Words that are contrary to the original intention should be avoided. For example, hp, aix and sco should not be used as variable names, because they are proprietary names of Unix platforms or Unix-like platforms. Even if you are writing a trigonometric calculation program, hp seems to be a good abbreviation [2], but it may also provide wrong information.

Don't use accountList to refer to a group of accounts unless it is a true list type. Word lists are of special significance to programmers. If the container containing the account number is not a real list, it will lead to wrong judgment.

Therefore, it is best to use accountGroup or bunchOfAccounts, or even directly use Accounts.

Beware of using names with high similarity in appearance. For example, how long does it take to distinguish between Xyzcontroller efficiently processing strings in one place and Xyzcontroller efficiently processing strings in another place in the module? These two words are so similar in shape.

Spell the same concept in the same way is information. Inconsistent spelling can cause misunderstanding. We like the automatic code completion feature of modern Java programming environment. Type the first few letters of the name, and then click the hotkey combination (if any) to get a list of possible forms of the name.

If you put similar names together in alphabetical order, and the difference is obvious, it will be quite helpful, because programmers will probably not look at your detailed comments, or even the list of such methods, and choose an object directly by looking at the name.

A terrible example of a misleading name is the use of lowercase letters L and uppercase letters O as variable names, especially when used in combination. Of course, the problem is that they look exactly like constants "one" and "zero".

Readers may think that this is pure fiction, but we have indeed seen code full of such names. On one occasion, the code author suggested writing variable names in different fonts to make them clearer, but only if this scheme was communicated to all future developers orally and in writing. Later, just a simple renaming operation solved the problem and did not cause other problems.

— 03 —

Make a meaningful distinction

If programmers just write code to meet the needs of compilers or interpreters, it will be troublesome. For example, because two different things in the same scope can't have the same name, you may change the name of one of them at will, and sometimes you simply misspell it, and the result will be that the compiler will make mistakes after correcting the spelling mistakes.

Just adding a sequence or nonsense is not enough, even if it is enough to satisfy the compiler. If the names must be different, then their meanings should also be different.

Named after a number sequence (a 1, a2 ... an), as opposed to naming according to meaning. Such a name is purely misleading-it does not provide correct information at all, nor does it provide clues to the author's intention. Give it a try:

This function would be better if the parameter names were changed to source and destination.

Nonsense is another meaningless distinction. Suppose you have a product category. If there is another class named ProductInfo or ProductData, they have different names but the same meaning. Information and data, like A, an and the, are meaningless things with vague meanings.

Please note that the prefixes A and The are correct, as long as they reflect meaningful differences. For example, you can use for domain variables and for function parameters [5]. But if you already have a variable named zork and want to call a variable named theZork, the trouble is coming.

Nonsense is superfluous. The word variable should not appear in the variable name. The word table should not appear in the table name. Will NameString be better than Name? Could the name be a floating-point number? If so, it violates the regulations on misleading.

Suppose there is a class named Customer and a class named CustomerObject. What's the difference between them? Which method can best express the historical payment situation of customers?

There is an application that reflects this situation. For the sake of the client, we changed it, but the wrong code really looks like this:

How do programmers know which function to call?

If there is no clear agreement, then there is no difference between the variables moneyAmount and money, between customerInfo and customer, between accountData and account, and between Message and message. To distinguish names, it is necessary to distinguish them in a way that readers can recognize the differences.

— 04 —

Use a readable name.

Humans are good at memorizing and using words. A considerable part of the brain is used to contain and process words. Words can be read. It is a pity that there is such a large area in the human brain for processing speech, if it is not used properly.

I can't pronounce the name, and the discussion is like a stupid bird. "Hey, here, there is an integer named Peeess Zee Kyew [7] at the top of the square arr three chee enntee, see?" This is no small matter, because programming is a social activity.

One company wrote a genymdhms (for day, year, month, day, hour, minute and second) in the program, which is generally read as "GenWhy EMM Di Aiqi Emmess" [8]. I have a bad habit of spelling every word, so I pronounce "gen-yah-mudda-hims" as soon as I open my mouth.

Later, many designers and analysts followed suit, which sounded silly. We know the story, so we think it is very interesting. Funny is funny, but it is actually trying to resist bad naming. When explaining the meaning of variable names to new developers, they always read silly self-made words instead of formal English words. compare

Now it reads like human words: "Hey, Mike, look at this record!" " Generation timestamp [9] is set to tomorrow! Can't do this? "

— 05 —

Use a searchable name

One problem with single-letter names and numeric constants is that it is difficult to find them in large text.

It is easy to find MAX_CLASSES_PER_STUDENT, but it is troublesome to find the number 7, which may be part of some file names or other constant definitions and appear in various expressions used for different purposes. If the constant is a long number, it will evade the search and cause an error.

Similarly, e is not a good variable name that is easy to search. It is the most commonly used letter in English, and it may appear in every program and every piece of code. Thus, the long name is better than the short name, and the searched name is better than the code written by yourself.

I thought one-letter names were only used for local variables in short methods. The length of a name should correspond to its scope size [N5]. If a variable or constant can be used in many places in your code, you should give it a name that is easy to search. Compare again:

Note that the sum in the above code is not a particularly useful name, but at least it can be searched. Using a name that can express the intention seems to lengthen the function code, but think about it, WORK_DAYS_PER_WEEK is much easier to find than the number 5, and only the name that reflects the author's intention is left in the list.

— 06 —

Avoid using coding.

There is already too much code, so there is no need to ask for trouble. Encoding a type or range into a name will increase the burden of decoding in vain. There is no reason to ask every newcomer to know another coding "language" besides the code to be processed (that's normal). This is an unnecessary burden to solve the problem. Names with codes are usually inconvenient to pronounce and easy to make mistakes.

Hungarian symbol

In the past, when the length of the name was very important, we broke the rule of unnecessary coding, and now we regret it. Fortran language requires the first letter to reflect the type, which leads to the emergence of coding. Early versions of the BASIC language only allowed one letter plus one number. The Hungarian symbol [10] (HN) aggravates this situation.

In the era of Windows C language API, HN is very important. At that time, all the names were either integer handles, long pointers, null pointers, or one of several implementations of string (with different uses and attributes). At that time, compilers didn't do type checking, and programmers needed Hungarian symbols to help them remember types.

Modern programming languages have a richer type system, and compilers also remember and force the use of types. And programmers tend to use smaller classes and shorter methods, so that the definition of each variable is in the field of vision.

Java programmers don't need type coding, because objects are strongly typed, and the code editing environment is advanced enough to detect type errors before compilation begins! Therefore, HN and other types of coding forms are purely redundant today. They increase the difficulty of modifying the names or types of variables, functions or classes, they increase the difficulty of reading codes, and they create the possibility that the coding system will mislead readers.

Member prefix

It is not necessary to use the m_ prefix to represent member variables. Classes and functions should be small enough to eliminate the need for member prefixes. You should use an editing environment where members can be highlighted or colored.

In addition, people will soon learn to ignore prefixes (or suffixes) and only see the meaningful parts of names. The more codes you look at, the fewer prefixes you see. In the end, the prefix has become an unsightly waste and a symbol of the old code.

Interface and implementation

Sometimes there are special cases where coding is used. For example, you are creating an abstract factory for creating shapes, which is an interface implemented by a concrete class. What are the names of factories and specific classes? IShapeFactory and ShapeFactory? I like the plain interface. The first letter I is abused to the extent that it is interference at best and nonsense at worst.

I don't want users to know that I gave them an interface, just want them to know that this is a ShapeFactory. If I have to choose between interface and implementation to code, I'd rather choose implementation. ShapeFactoryImp, even the ugly CShapeFactory, is better than coding interface names.

-End-

Code neatness

Author: [America] Robert C. Martin

Translator: Han Lei

Content introduction:

Software quality depends not only on architecture and project management, but also on code quality. This point, whether agile developers or traditional developers, have to admit.

This book puts forward the view that the quality of code is directly proportional to its cleanliness. Clean code quality is reliable, which lays a good foundation for later maintenance and upgrade. As a leader in the field of programming, the author of this book gives a series of effective clean code operation practices. These practices are embodied in this book as rules (or "revelations"), supplemented by positive and negative examples from actual projects. As long as you follow these rules, you can write clean code, thus effectively improving the quality of the code.

This book is aimed at all programmers and technical managers who are interested in improving code quality. The rules introduced in the book come from the author's years of practical experience, covering many programming aspects from naming to refactoring. Although it is a saying of "home", it is of great reference value.