


Worth a look! Necessary coding skills and thinking for senior PHP engineers
Recommended: "PHP Video Tutorial"
Good developers are usually defined by code quality. In the software industry, writing good code means saving money on testing, updating, extending or fixing bugs. In this article, I will show you some real-life examples of techniques and ideas to help you clean up your logic code, refactor it, and make it more robust and modular. These tips will not only help you refactor your old code, but also give you some good advice on how to write cleaner code from now on.
What is refactoring and why do we need it?
Refactoring refers to methods and steps that help us write concise code. This is important for other developers who may read, extend, and reuse our code without much editing.
The following content will show you some examples of refactoring logic code to make it better.
Don’t refactor production code without unit testing
My first piece of advice is to never start without fully unit testing Refactor logic code. My reasoning is this: you'll end up with broken functionality that's hard to fix because it's hard to pinpoint what's broken. So if you're going to refactor it, start with tests. Make sure the parts you plan to refactor are covered by tests. PHPUnit code coverage analysis.
Start refactoring from the bottom of your code
Look at the picture below. This is a real hotel management system project that I found from Github. This is an open source project, but closed source projects would be terrible.
Example: Refactoring from the bottom
Look at this code, there are three levels marked in red. The lowest level should be the declaration surrounded by if/else in the first if condition. Usually, the lowest level is concentrated on a single logical processing and is easier to refactor.
Make your methods shorter, decompose them into smaller methods or configuration files/DB tables
Maybe here, we can refine it as below A private method:
#Make your methods shorter
The next point of depth will be uploading parameters and loading views. Now, let's look at the add()
method after refactoring other parts. It becomes more concise, easier to read, and easier to test.
Example: Refactor the lowest level first
if statement insists on using curly braces
Most programming languages All support single-line if statements. Because it is simpler, some developers use it this way. However, it is not easy to read and can easily cause problems, because a blank line can interrupt the condition and cause a crash. Look at the difference between the following two examples:
Example: Use braces
Do not use magic numbers or magic strings:
In the next example, you notice that if the room exceeds 250, an error message will be returned. Here, 250 is considered a magic number. If you're not the developer writing this, it's hard to figure out what this number means.
Example: Magic Numbers
To refactor this method, we can indicate that 250 represents the maximum number of rooms. To replace the hardcoding, we can extract it into a variable $maxAvailableRooms
. Now it becomes more understandable to other developers.
Example: Fix magic numbers
Don’t use else statements if you don’t really need to:
In the same availablerooms() function, you notice that if statement, where we can easily get rid of the else part and the logic remains consistent.
Example: Ignore the else statement
Use naming that represents your methods, variables, and tests
In the following example, you will find that the hotel management system has two methods: "index()" and "room_m()". For me, I can't figure out what their purpose is. I think it should be easy to understand if their names describe themselves.
Example: Bad Method Naming
Take full advantage of the power of your programming language
Many developers Programmers will not take advantage of the full capabilities of the programming language they are using. Many features can save you time and make your code more robust. Take a look at the example below and notice how it's easier to achieve the same result with less code, by using type hints.
Finally, I’d like to offer some quick tips for better coding:
- Use the new array form [] to replace the old array().
- Use the === operator instead of == unless it is important not to check the data type.
- It's always a good idea to give public methods short, descriptive names. Private methods can use longer names because their scope is more limited.
- Use generic names such as add() only for methods that implement the interface, and use descriptive names such as addUser() or addDocument() for individual class methods.
- Remove unused methods from the class.
- Use the is/has prefix for functions that return values such as boolean: isAdmin($user), hasPermission($user).
- Always use access modifiers in class methods and properties.
- Be careful about interface pollution: only use methods that are publicly available to users.
- Organize class methods so that public methods are at the top.
- Always apply the concept of single responsibility within a class.
Original address: https://medium.com/@maladdinsayed/advanced-techniques-and-ideas-for-better-coding-skills-d632e9f9675
Translation Address: https://learnku.com/php/t/37900
The above is the detailed content of Worth a look! Necessary coding skills and thinking for senior PHP engineers. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
