Writing high-quality code -- starting with naming

Source: Internet
Author: User
Writing high-quality code -- starting with naming

Programming beginners always spend a lot of time learning programming languages, syntaxes, skills, and 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 being proficient in these technologies and tools. it is about creating solutions for specific problems in specific fields. programmers can work with each other to implement these solutions. So, it is very important that you need to be able to accurately express your thoughts with code, so that others can understand your intentions through code.

Let's take a look at one sentence in the masterpiece "Clean Code" of Robert C. Martin, a programming guru:

The purpose of annotation is to make up for the insufficient expression of the code itself.

This sentence can be simply understood as if your code needs to be annotated, it is most likely that your code is poorly written. Similarly, if you cannot fully express your ideas about a problem or an algorithm without comments, it is a failure signal. In the end, this means that you need to use comments to clarify some ideas, which cannot be seen in the code. Good code allows anyone to understand without any comments. A good coding style can include all the information that helps you understand this problem in the code.

In programming theory, there is a concept called "self-describing Source Code ". For a piece of code, a common self-description mechanism is to follow some non-strictly defined variables, methods, and object naming rules. The main function of this operation is to make the source code easier to read and understand. 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 be uncovered

Naming is always a tough issue in programming. Some programmers prefer to simplify, Shorten, or encrypt names so that they can understand them only. Here are some examples:

Bad Code:

Int d; // Number of days int ds; int dsm; int faid;

"D" can represent anything. The author uses annotations to indicate his intention, but does not use code to represent it. "Faid" can easily be misunderstood as ID.

Clear code:

Int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification; int fileAgeInDays;

Avoid misunderstanding when naming

The error message is worse than no information. Some programmers like to "hide" some important information, and sometimes write some misleading code.

Bad Code:

Customer [] customerList; Table theTable;

The variable "mermerlist" is not actually a list. It is a common array (or a customer set ). In addition, "theTable" is a Table-type object (you can easily find its type with IDE). the word "the" is unnecessary interference.

Clear code:

Customer [] MERS; Table table;

Proper length is required for naming.

In advanced programming languages, variable names are generally not limited in length. Variable names can contain almost any length. Even so, this may also make the code quite messy.

Bad Code:

Var thecustomerslistwithallmermersincludedwithoutfilter; var list;

A good name should contain only the necessary words to express a concept. Any unnecessary words make the name longer and hard to understand. The shorter the name, the better, provided that the complete meaning can be expressed in the context (in the case of placing an order, "mermersinorder" is better than "list ).

Clear code:

Var allCustomers; var customersInOrder;

The encoding specifications are consistent during naming, helping you understand the code.

All programming technologies (languages) have their own "styles" called coding specifications. Programmers should follow these habits when writing code, because other programmers know this and write it in this style. The following shows an example of a code without obvious specifications. The following code does not follow well-known "Encoding Specifications" (such as PascalCase, camelCase, Hungarian ). Worse, there is a meaningless bool variable "change ". This is a verb (used to describe an action), but the bool value here is used to describe a state. Therefore, it is better to use an adjective here.

Bad Code:

Const int maxcount = 1 bool change = truepublic interface Repositoryprivate string NAMEpublic class personaddressvoid getallorders ()

For a piece of code, just look at a 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 use this representation anywhere, without exceptions.

Clear code:

Const int MAXCOUNT = 1 bool isChanged = truepublic interface IRepositoryprivate string _ namepublic class PersonAddressvoid GetAllOrders ()

The same concepts are expressed with the same words during naming.

It is difficult to define concepts. During software development, a lot of time is spent analyzing business scenarios and thinking about all the elements in correct definitions. These concepts will always be a headache for programmers.

Bad Code:

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


The author of the code tries to express the concept of "get the data". he uses multiple words "load", "getch", and "get ". A concept can be expressed with only one word (in the same scenario ).


The word "set" is used in two concepts: "data loading to view" and "setting a value of object ". There are two different concepts. you should use different words.

Clear code:

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

Use the words related to the business field for naming.

All the code written by the programmer is logically linked to the business scenario. In order to give everyone who is concerned with this issue a better understanding, the program should use meaningful names in the field environment.

Bad Code:

Public class EntitiesRelation {Entity o1; Entity o2 ;}

When writing code for a specific 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 field (without business logic knowledge ). The first thing you should consider is how to solve business problems.

Clear code:

Public class ProductWithCategory {Entity product; Entity category ;}

Use meaningful words in a specific environment for naming.

The name in the code has its own context. Context is very important for understanding a name because it provides additional information. Let's take a 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 zip Code cannot be used independently (unless you are developing an application dedicated to processing the zip Code ). Therefore, there is no need to add "address" before "PostCode ". More importantly, all the information has a context, namespace, and 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 ;}

Naming method summary

As a programmer, you should:

·Naming is used to express concepts.

·Note that the name length must contain only necessary words.

·The code specification helps you understand the code. you should use it.

·Do not mix names

·The name must be meaningful in the business field and in the context.

Due to the attachment Upload and text restrictions, sometimes some pictures, text may not be displayed, see: http://mp.weixin.qq.com/s? _ Biz = MzI5ODI3NzY2MA ==& mid = 100000563 & idx = 2 & sn = 528dc490ec0d0a230b8503d71d9a3e63 # rd
You are welcome to join us.
Scan the following QR code to get more exquisite articles! (Scan the QR code to check for any surprises you may not be interested in !!)

Follow our subscription number (uniguytech100) and Service number (uniguytech) for more exquisite articles!
You are also welcome to join the [discussion QQ group on the technical network], group number: 256175955. please note your personal introduction! Let's talk about it together!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.