Home Backend Development PHP Tutorial Write high-quality code—start with naming

Write high-quality code—start with naming

Jul 25, 2016 am 08:43 AM


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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles