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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

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

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),