Home  >  Article  >  Backend Development  >  Write high-quality code—start with naming

Write high-quality code—start with naming

WBOY
WBOYOriginal
2016-07-25 08:43:411049browse

Beginners to programming always spend a lot of time learning programming languages, syntax, techniques and the use of programming tools. They believe that if they master these technical skills, they can become good programmers. However, the purpose of computer programming is not about mastering these technologies and tools. It is about creating solutions to specific problems in specific fields, and programmers work with each other to achieve these. Therefore, it is very important that you can accurately express your thoughts in code so that others can understand your intentions through code.

Let’s first take a look at a sentence from the masterpiece "Clean Code" by programming master Robert C. Martin:

The purpose of comments is to make up for the lack of expression in the code itself.

This sentence can be simply understood as if your code needs comments, it is most likely that your code is poorly written. Similarly, if you cannot fully express your thoughts on a problem or an algorithm in code without comments, then this is a sign of failure. Ultimately, this means that you need to use comments to clarify parts of your thinking that are not visible in the code. Good code can be understood by anyone without any comments. Good coding style contains all the information that helps to understand the problem in the code.
 In programming theory, there is a concept called "self-describing source code". For a piece of code, a common self-describing mechanism is to follow some non-strictly defined naming rules for variables, methods, and objects. The main effect of this is to make the source code more readable and understandable. Therefore, it is easier to maintain and expand.
In this article, I will give some examples to illustrate what is "bad code" and what is "clear code"

Name should reveal the intention

  How to name is always a difficult problem in programming. Some programmers like to simplify, shorten, or encrypt names so that only they can understand them. Let’s look at some examples below:

Bad code:
int d; // number of days int ds; int dsm; int faid;
“d” can mean anything. The author uses comments to indicate his intent, but chooses not to express it in code. And "faid" can easily lead to misunderstanding as ID.

Clear code:
int elapsedTimeInDays;int daysSinceCreation;int daysSinceModification;int fileAgeInDays;
Avoid misunderstood information when naming

  Wrong information is worse than no information. Some programmers like to "hide" some important information, and sometimes they write code that is misleading.

Bad code:
Customer[] customerList;Table theTable;
The variable "customerList" is not actually a list. It's a plain array (or collection of customers). Besides, "theTable" is an object of type Table (you can easily discover its type using the IDE), and the word "the" is an unnecessary distraction.

Clear code:
Customer[] customers;Table table;
The name must be of appropriate length

  In high-level programming languages, the length of variable names is usually not limited. Variable names can be of almost any length. However, this can also make the code confusing.

Bad code:
var theCustomersListWithAllCustomersIncludedWithoutFilter;var list;
A good name should only contain the necessary words to express a concept. Any unnecessary words will make the name long and difficult to understand. The shorter the name, the better, as long as it can express the complete meaning in the context (in the context of placing an order, "customersInOrder" is better than "list").

Clear code:
var allCustomers;var customersInOrder;
Keep coding standards consistent when naming, and let the standards help understand the code

语 All programming technology (language) has its own "style", called coding specifications. Programmers should follow these conventions when writing code because other programmers know them and write in this style. Let's look at an example of bad code without obvious specifications. The following code does not follow well-known "coding conventions" (such as PascalCase, camelCase, Hungarian conventions). To make matters worse, this has a meaningless bool variable "change". This is a verb (used to describe an action), but the bool value here is to describe a state, so an adjective would be more appropriate here.

Bad code: const int maxcount = 1bool change = truepublic interface Repositoryprivate string NAMEpublic class personaddressvoid getallorders()

​ A piece of code, just look at part of it, you should directly understand what type it is, just look at its naming method.
For example: If you see "_name", you can know that it is a private variable. You should take advantage of this representation everywhere, without exception.

Clear code: const int MAXCOUNT = 1bool isChanged = truepublic interface IRepositoryprivate string _namepublic class PersonAddressvoid GetAllOrders()

The same concept is expressed with the same word when naming

It’s hard to define a concept. During the software development process, a lot of time is spent analyzing business scenarios and thinking about the correct definition of all the elements in it. These concepts are always a headache for programmers.

Bad code: //1. void LoadSingleData ()void FetchDataFiltered ()Void GetAllData ()//2. void SetDataToView ();void SetObjectValue (int value)

First of all:
The author of the code tried to express the concept of "get the data", he used multiple words "load", "getch", "get". A concept can be expressed in just one word (in the same context).
 Second:
 The word "set" is used in 2 concepts: the first is "data loading to view", the second is "setting a value of object". These are two different concepts and you should use different words.

Clear code: //1. void GetSingleData ()void GetDataFiltered ()Void GetAllData ()//2. void LoadDataToView ();void SetObjectValue (int value)


Use words related to the business field when naming

 All codes written by programmers are logically connected with business domain scenarios. To provide better understanding to all concerned with the problem, programs should use names that are meaningful in the context of the domain.

Bad code:
public class EntitiesRelation{Entity o1;Entity o2;}
When writing code that is specific to a domain, you should always consider using domain-related names. In the future, when another person (not just a programmer, maybe a tester) comes into contact with your code, he can easily understand what your code means in this business domain (no knowledge of business logic is required). Your first consideration should be the business problem, then how to solve it.

Clear code:

public class ProductWithCategory{Entity product;Entity category;}
Use words that are meaningful in a specific context when naming

 The names in the code have their own context. Context is important in understanding a name because it provides additional information. Let's look at a typical "address" context:

Bad code:

string addressCity;string addressHomeNumber;string addressPostCode;
In most cases, the "Post Code" is usually part of the address. Obviously, the postal code cannot be used alone (unless you are developing an application that specifically handles postal codes). Therefore, there is no need to add "address" in front of "PostCode". More importantly, all this information has a context, a namespace, and a class.
  In object-oriented programming, an "Address" class should be used to express this address information.

Clear code:
class Address{string city;string homeNumber;string postCode;}
Summary of naming methods

In summary, as a programmer, you should:
· Naming is to express concepts
· Pay attention to the length of the name. The name should only contain necessary words
· Coding conventions help to understand the code, you should use it
· Don’t mix names
· Names should be meaningful in the business domain and meaningful in the context


Due to restrictions on uploading attachments and text, sometimes some pictures and text may not be displayed. For details, please see: http://mp.weixin.qq.com/s?__biz=MzI5ODI3NzY2MA==&mid=100000563&idx=2&sn=528dc490ec0d0a230b8503d71d9a3e63#rd
Everyone is welcome to communicate.
Scan the QR code below to get more and more beautiful articles! (Scan the QR code to follow for unexpected surprises!!)

Follow our WeChat subscription account (uniguytech100) and service account (uniguytech) to get more and more exquisite articles!
You are also welcome to join [Everyone Technology Network Discussion QQ Group], group number: 256175955, please note your personal introduction! Let’s talk about it together!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn