search
HomeBackend DevelopmentPHP TutorialWrite high-quality code—start with naming


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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!