Clean code: Meaningful name (Part 1)

Names appear everywhere in the software. We name variables, functions, parameter lists, classes, and packages. We then name the file and the directory name containing them. Then we name the jar file and war file, ear file. We name, name and name. Because we have to do it a lot, we need to do well. Here are some simple rules to create a good name.

Use descriptive names

It's simple to talk about the suggested names. What we want you to remember is that we need to be serious about this issue. Choosing a good name takes a lot of time but it saves a lot when using it. So pay attention to the names you set and change them when you find a better name. When you do that, everyone who reads your code (including you) will find it easier to understand.

The name of the variable, function, class should answer all the big questions. It will tell you why it exists, what it does, and how it is used. If a name needs to be explained, this name has no meaning.

int d; // time passed in the day

The variable name d shows nothing. It does not describe the feeling of time passing, nor about the day. We should choose a name that describes what is happening like:

ma1

The choice of descriptive names makes it easier to understand and change when programming. What is the purpose of this code?

ma2

Why is it difficult to explain what this code is doing? No complicated expressions, distance and indentation are perfectly reasonable. Only three variables and two constants are mentioned. Without any polymorphic class or method, it seems to be just an array list.

The problem is not the simplicity of the code, but the "implicit" nature of the code (to phrase the coin): the extent to which the context is unclear in the code itself. Underground code requires us to know the answers to questions such as:

1. What type ofList is it?

2. What is the meaning of zero starting index of an element in theList?

3. What does number 4 mean?

4. How do I use the return list?

Answers to questions not found in the code above, but they may already exist. Please understand that we are working with the game to detect ourselves. We see the table containing the list of cells called theList. Please rename the gameBoard.

Each cell on the table is represented by an array. We also see that the zero index is the position of a state and the state value 4 means "flagged". By giving concept names we can significantly improve the code:

ma3

Note that the simplicity of the code above is unchanged. The code still has exactly the same nested constants and operators. But the code has become more explicit.

We can develop more, instead of using integer arrays, we create a simple class for cells. This class contains a hint function (called isFlagged) to hide magic numbers. This is a new version of the function:

ma4

With simple name changes, it's not difficult to understand what's going on. This is the strong point of choosing good names.

Avoid misleading

Programmers must avoid leaving false clues that obscure the meaning of the code. We should avoid words that are different from our true intentions. For example, hp, aix, sco are poor names because they are descriptive names in the Unix operating system or its versions. Even if you're programming about hypotenuse and hp look like acronyms, this is not good information.

Do not call a group of accounts (accountList) unless it stores the actual list. From the list (list) means something specific to programmers. If these accounts are not stored in list form, false statements can be listed. So the name accoutGroup or bunchOfAccounts indicates that the account holder list is still better.

Be careful when using names that are not much different. How long does it take to detect the difference between XYZControllerForEfficientHandlingOfStrings in a module and XYZControllerForEfficientStorageOfStrings somewhere not far away. They have a horribly similar shape.

Variables with similar spellings also have problems like when they are similar in information. Using inconsistent writing also leads to misunderstandings. With the modern Java programming environment (IDE), we use the code autocomplete feature. We write a few characters of the name and press the shortcut (if available) and the IDE gives you a list of names to complete for naming. This is useful if the names have similar meanings, arranged in alphabetical order, because developers sometimes want to choose a name without looking at anyone's opinions even methods of that class.

A really terrible example of a misleading name when using the lowercase letter of L or the capital letter of o as a variable name. The problem, of course, is that we see these variables almost like numbers 1 or 0.

ma5

Readers may think this is a trap, and we have to check such code. In the case of the author of the code proposing to use a font other than to distinguish the difference, a solution would advise them to write a clear document or exchange to understand the problem more clearly. But the problem is that it is strongly recommended that they correct the name more clearly.

Make a clear difference

Programmers will create problems themselves when they write code just to satisfy the compiler or interpreter. For example, because you can't use the same name to refer to two different things in the same range, you might be tempted to change the name of a name in a random way. Sometimes, this is done due to a spelling error, leading to a surprisingly correct spelling error, which leads to the code being unable to compile (For example, when naming the class is kclass because the class name is already used) for another).

It is not enough to add a range of numbers or hot words, even the compiler is satisfied. If they have different meanings, they must have different names.

Name a sequence of numbers (a1, a2, …, aN) as opposed to intentional naming. These names do not mislead, but they also do not have information. They do not provide clues about the author's idea. Let's consider:

ma6

This function will be easier to understand when the source and destination variable are used as the passed parameter name.

Noise words are another case of names without significant differences. Imagine that you have a Product class. If you have another class called ProductInfo or ProductData. You put different names without making any difference. Info and Data are two words of noise.

Note that the convention of using prefixes (like a, the) has no problem because they make a difference. For example, you must use a for all local variables and the for all parameters of the function. These will be problematic when you decide to name theZork variable because you already have another variable name that is set to zork.

Noise words are redundant. A variable never has a variable name. The word table should not appear in the table name. Where is NameString better than Name? Has the name ever been a real number? If so, it breaks the previous rule about the wrong command of information. Imagine finding the class name Customer and another name set to CustomerObject. What do you see the difference between these two names? Which name will best describe a customer's payment history?

There is an application that we know to illustrate this. We changed the name to protect the error, but this is the error of the error:

ma7

How do programmers know what functions are called?

In case there is no specific convention, turning moneyAmount is no difference with money, customerInfo has no difference with customer, accountData is not different from account, and theMessage has no difference with message. The different names in this case help the person who knows the difference is made.

Use readable names

Hummans is a word that means well. An important part of our brains is dedicated concepts of words. These words are defined or pronounced. It would be a mistake to be unable to take advantage of these great advantages of our brains to deal with spoken language. So your name is pronounced.

If you can't pronounce names, you can't discuss it without thinking like an idiot.

A company I know is genymdhms (founding days, months, years, hours, minutes, seconds) they go around and say "gene why emm dee aich emm es". I have a bad habit of pronouncing issues like text, so I start saying "gen-yah-mudda-hims".

It was then called by a bunch of designers and analysts, and we still seem silly. But we were on the joke, so it was very interesting. Fun or not, we tolerated poor names. New development must have explanatory variables for them, and then they talk about it in silly from fiction instead of using proper English terms. Compare

ma8

With

ma9

A better conversation can now: "Hey, Mikey, look at this profile! Timestamp generation is set to date tomorrow! How could that be? "

Use searchable name

Single letter names and constants have a special problem in that they are not easy to locate on a body of text.

If variables and constants are used a lot in the code. Need to create a friendly search name.

Compare:

ma10

With

ma11

Notice how to turn sum, not a fully useful name, because at least it can be found. Intentionally put the code, but it is easier to find WORK_DAYS_PER_WEEK than put it with the number 5 and continue reading only the cases with the desired meaning.

Avoid duplicating the code

We have enough coding to deal with not adding to our burden. Coding type, the scope of information in the name is simply an additional burden of decoding. It hardly seems reasonable to ask each new employee to learn more of a "language" beyond learning (often significant) coding the body of the code they will work on. This is a burden. spirit is not needed when trying to solve a problem. Encryption names are rarely pronounced and are easy to miss.

Hungarian Notation

Previously, when we were working with the name-length-challenged language, we violated the necessary principle and regretted it. Fortran is required to encode by making the first letter a code for the type. The first version of BASIC allowed only one character with one digit. Hungarian Notation (HN) took this stage to a new level.

HN is considered to be quite important in the Windows C API, when everything is handled with an integer or a pointer of type long or a pointer of type void, or some implementation of "string" (with different uses and attributes). The compiler did not test the types in those days, so programmers need a crutch to help them remember the types.

In modern programming languages, data types are richer, compilers remember and implement more types. Moreover, there is a tendency to build smaller classes and shorter functions called so people often see the declaration point of each variable they are using.

Java programmers do not come to the encrypted data type. Objects are powerful data types and creating such a progressive environment can help identify a variety of errors before the compiler runs. So now HN and different forms of coding types are just simple obstacles. They only make it more difficult to change the name or data type of variables, functions, and classes. And also difficult to read the code. It is also possible to create an encryption system that will mislead readers.

PhoneNumber phoneString;

// tên không thay đổi khi kiểu thay đổi!

Prefix component

You do not need to specify a name with the prefix m_. Classes and functions should be small enough to not need to use those prefixes. And you should use the editing environment to highlight or colorize layers or functions to make a difference between them.

ma12

Besides, people often leave the prefix (or suffix) to see the more meaningful part. We read the code less prefixed than having to see multiple prefix codes. The last thing is that the prefix becomes cluttered, which is a sign of the code that has not been improved.

Interface and installation

Sometimes there are some special cases when coding. For example, if you are building an Abstract Factory to create the Shapes object (image). This factory will be created as an interface and will be executed by a specific class. So how should you name it for Factory? ShapeFactory or IShapeFactory? I prefer the ShapeFactory interface. When defining I in front of the interface, there are many distributions and bad information. Because I don't want my customers to know that I'm giving them an interface. I just want them to know that it's a ShapeFactory. So to encode or implement the interface I choose the implementation. Call it ShapeFactoryImp, or even CShapeFactory rather than interface coding.

Class name

Classes and objects should have nouns or noun phrases such as Customer, WikiPage, Account, and AddressParser. Avoid using words like Manager, Processor, Data, Infor in the name of a class. A class name should not be a verb.

Method name

The method should have verbs or phrasal verbs like postPayment, deletePage, or save. Access and change methods should be named for their values ​​and good for get, get, and is in the standard of javabean.

string name = employee.getName ();

customer.setName ("mike");

if (paycheck.isPosted ()) …

When the initialization method is overloaded, use the calculation method with the name describing the passed argument. For example:

Complex fulcrumPoint = Complex.FromRealNumber (23.0);

usually better:

Complex fulcrumPoint = new Complex (23.0);

Consider forcing them to be used by passing the corresponding initialization method to private.

Source: Journal of Programming

Share the news now