Writing high-quality code starts with naming

Writing high-quality code starts with naming

[[146621]]

I have been engaged in development for many years and have a feeling that it is a pleasant experience to view the source code of some open source projects, such as Spring, Apache Common, etc. The reasons are as follows: 1) the code quality is very high; 2) the naming is particularly standardized (this may be related to the English level of foreigners).

Writing high-quality code is not an easy task. It requires years of practice and is a process of quantitative change to qualitative change. However, good naming only requires a good foundation in English grammar and self-awareness. This blog post will summarize several naming rules based on my development experience. These naming rules are purely personal usage habits and do not represent an ideal rule. They are listed here for everyone to discuss.

1. Avoid using meaningless English letters in naming

  1. for ( int i= 0 ; i< 10 ; i++) {
  2. ...
  3. }

This is a common code snippet in many books that teach basic Java syntax. As teaching material, there is nothing wrong with writing it this way, but as real code writing, programmers must develop good habits and not use this meaningless naming method. "index" can be used here.

2. Avoid using pinyin, or even the first letter combination of pinyin

  1. cishu = 5 ; //Number of loops  
  2. zzje = 1000.00   // Transfer amount  

When I was doing code review, I encountered such naming countless times, which made people laugh and cry.

3. Use English, and use accurate English, both in spelling and grammar

  • Singular nouns must use singular English, such as Account and Customer.
  • For the naming of object collections such as arrays and lists, plural forms must be used, and it is best to use the correct plural form according to the basic knowledge of English grammar, such as List<Account> accounts, Set<Strategy> strategies.
  • For properties with boolean values, many developers are accustomed to using isXXX, such as isClose (whether it is closed). However, here are two suggestions: 1) Do not include "is" at the beginning, because the JavaBean specification uses "get/set/is" when generating get/set methods for properties. In the example above, the generated get/set method will become "getIsClose/isIsClose/getIsClose", which is very awkward. 2) Since boolean values ​​usually reflect "whether", the correct usage should be to use "adjective". The example above should eventually be changed to closed, and the get/set method will be "getClosed/isColsed/setClosed", which is very consistent with English reading habits.

4. The naming of the method needs to use "verb-object structure phrase" or "verb + predicative structure phrase"

I have seen all kinds of strange method names, some using nouns, some even "noun + verb", and if the object is a collection of objects, it is best to use plural:

  1. createOrder(Order order) //good  
  2. orderCreate(Order order) //bad  
  3. removeOrders(List<Order> orders) //good  
  4. removeOrder(List<Order> order) //bad  

5. For common "add, delete, modify and check" methods, be careful when naming them:

  • Add: create and add are the most common, but it is helpful to distinguish them according to the semantics of English. Create means to create, and add means to add. For example, to create a Student, it is better to use createStudent than addStudent. Why? Imagine if there is a class called Clazz (class, avoiding Java keywords), and now you want to add a Student to a Clazz, Clazz can easily define an addStudent (Student student) method, which is easy to confuse.
  • Modification: Common ones are alter, update, and modify. Personally, I think modify is the most accurate.
  • Query: For obtaining a single object, you can use get or load, but I personally recommend using get. Please see the explanation in point 7. For unconditional enumeration, use list. For conditional queries, use search (***do not use find. Find in English emphasizes the result. You provide a "query" method, but it does not guarantee that the input conditions can always "find" the result).
  • Delete: Common ones are delete and remove, but delete is recommended because remove means "remove". You can understand it by referring to Clazz's example. To remove a student from a class, removeStudent would be used.

6. Prefer lengthy method names to confusing abbreviations

I once encountered a method to determine whether the payment account is the same as the receiving account. As a result, I saw a name like this:

  1. checkIsOrderingAccCollAccSame(...) // This is hard to understand, I'll change it immediately to:  
  2. isOrderingAccountSameAsCollectionAccount(...) // Although a bit long, it is very easy to read, and this situation always occurs less frequently.  

7. If you are designing a business system, never use technical terms to name it.

The company I used to work for once formulated a naming rule that interfaces must start with "I", data transfer objects must be suffixed with "DTO", data access objects must be suffixed with "DAO", and domain objects must be suffixed with "DO". The reason why I do not recommend this approach is that I hope that designers can guide developers from the beginning to consider issues from the perspective of "business" rather than "technology".

Therefore, the interface does not have to start with "I", as long as its implementation class ends with "Impl" (Note: I think the interface is irrelevant to details and technology, but the implementation class is implementation-related, so there is nothing wrong with using technical terms). The data transfer object is nothing more than storing the information of an object, so you can use "**Info", such as CustomerInfo. The domain object itself is the core of the business, so it still appears with its real name, such as Account, Customer. As for "DAO", this word comes from the design pattern of J2ee. The author used "***Repository" in the previous project, which means "*** warehouse", such as AccountRepository.

The word "Repository" comes from the concept of warehouse in Eric Evans' book "Domain-Driven Design". Eric Evans defines the concept of Repository as: a conceptual collection of domain objects. I think this name is very appropriate. It allows programmers to completely break away from technical thinking and think about problems from a business perspective. At this point, some people may refute: Don't excellent frameworks like Spring and Hibernate use "I" as the beginning of the interface and "DAO" to name data access objects? That's right! But don't ignore the semantic context. Spring and Hibernate frameworks are pure technical frameworks. The scenario I am talking about here is designing business systems.

8. Do not repeat the class name in member variables

For example, many people like to use names such as accountId and accountNumber in the member variables of the Account object. In fact, this is not necessary. Think about it, member variables do not exist in isolation. If you reference accountId, it must be account.accountId. Using account.id is clear enough.

"Don't do good things for small reasons, and don't do bad things for small reasons", "Details determine success or failure", there are too many famous sayings telling us to pay attention to details. A good programmer must have a solid foundation, and for the naming rules that are easy to master, why don't we do it now?

<<:  14 top development communities frequented by foreign programmers

>>:  Summary of new technologies in Android 6.0

Recommend

A piece of ginkgo leaf you picked up may come from billions of years ago

As the temperature gradually drops, the ginkgo be...

How to build an online operation system from scratch?

The operation system is divided into the operatio...

5 predictions for IoT and mobile app integration

It makes sense to integrate IoT and mobile device...

Decline or turnaround, how can the points wall occupy the high ground?

The game of mobile marketing does have many cleve...

Do you believe that Android users can use Apple Maps?

Since its launch, Apple Maps has been criticized ...

Henan Server Rental Fee Table

Henan server rental cost table, the cost of renti...

Segment "user activity status" to help you achieve KPI indicators

“Why has the conversion rate decreased? I can’t f...