Start with the details: Improve the readability of your code

In the world of programming, we are always pursuing higher performance, more elegant design, and more complex features. However, we should not ignore a basic and important principle – code readability. So what exactly is code readability? As the name suggests, code readability refers to the degree to which the code is understandable. It is the code author’s ability to output the information that needs to be expressed into the reader’s mind through the medium of code. Therefore, some people say that good code must have clear and complete comments, while others say that code is comments, which is the highest state of code simplicity. I have reservations about the latter view. After all, code is comments. How many people are there?

Let’s look at an example first:

public StepExitEnum doExecute(StepContext stepContext) throws Exception {
    String targetFilePath = this.getOriginFilePath(stepContext.getJobContext());//Get the target path
    File targetDir = new File(targetFilePath);
    if (!targetDir.exists()) {
        targetDir.mkdirs();//If the directory does not exist, create it
    }

    String encryptedFilePath = this.getEncryptedFilePath(stepContext.getJobContext());//Get the encrypted file path
    String fileName = this.getFileName(stepContext);//Get the file name
    File[] encryptedFiles = new File(encryptedFilePath).listFiles(this.buildFilenameFilter(fileName));//Filter files

    FileEncryptor dencryptor = this.buildFileEncryptor(stepContext);//Create FileEncryptor
    Stream.of(encryptedFiles)
            .forEach(encryptFile -> {
                File targetFile = new File(targetFilePath, encryptFile.getName());
                dencryptor.invoke(encryptFile, targetFile);//Decrypt file
            });

    return StepExitEnum.CONTINUING;
}

This kind of code is very common, and it is actually easy to understand if you have the patience: create directory -> read encrypted file -> decrypt file. For now, it actually meets the business needs, but it is not elegant enough; in the long run , this will produce a bad smell. First of all, what is the meaning of comments such as “Create the directory if it does not exist” and “Get the file name”? It’s possible that this was the coder’s plan at the time, but is it really needed? It does affect the attention of programmers who see this code, but it often does not allow programmers to obtain any valuable information; secondly, if you want to understand the purpose of the doExecute method, you must read the code thoroughly. The developer may just want to know what it does; finally, if something goes wrong in one line of this method, the scope of the impact is the entire business process. If changes are needed later, most people may add conditional judgments or continue to add code implementation later, which will eventually make it increasingly difficult to read. This is actually the root of the saying “if it can run, don’t touch it”. Because no one can understand what it does, but it has to be changed.

So how can you improve the readability of your code? After all, code readability is a prerequisite for team collaboration development, software maintainability, code review, and one of the core concerns in code review.

Abstraction, reasonable business logic abstraction

“A method should only do one thing” relies on the coder’s in-depth understanding and reasonable abstraction of business logic and function implementation, so that the boundaries of each function can be clearly distinguished, or how to define this “thing”.

Reasonable abstraction is very clear in terms of functional roles and division of responsibilities. Only with this foundation can we write business logic code clearly, instead of piling up various conditional judgments and loops with two slashes and comments. This is The basis of readability.

Everyone performs his or her own duties and has a single responsibility

A method only does one thing, and the same applies when extended to a class. It has a single responsibility. In the final analysis, it must be based on reasonable abstraction. Therefore, it is actually a concrete manifestation of abstraction, and the two always complement each other.

Use clear, concise naming:

Naming variables and functions is key to code readability. Names should be concise and descriptive, clearly expressing their purpose. Avoid using vague or oversimplified names.

Keep comments appropriate:

Comments are an important means of improving code readability. For complex logic and algorithms, appropriate comments can help readers understand the purpose and working principle of the code. At the same time, comments should also be kept concise and clear, avoiding excessive explanations.

Follow coding conventions:

Various programming languages have a set of recommended coding standards, such as Python’s PEP8, Java’s Google Java Style Guide, etc. These specifications not only help maintain code consistency, but also help improve code readability.

Use meaningful spacing and formatting:

Using appropriate spacing and formatting in code can help readers better understand the structure and logic of the code. For example, use spaces to separate variable and function names, use blank lines to separate different code blocks, etc.

Limit line length:

Lines of code that are too long are often difficult to read and understand. In general, limiting the length of lines of code can help improve code readability. Most IDEs and editors provide code line limits.

Based on the above suggestions, let’s take a look at the following code:

//Class name: RegexValidator
// Function name: validateString
// Function: Regular verification string
// POM dependency package: none

import java.util.regex.Pattern;

public class RegexValidator {
    /**
     * Regular verification string
     * @param regex regular expression
     * @param str String to be verified
     * @return whether it matches the regular expression
     */
    public static boolean validateString(String regex, String str) {
        if (regex == null || str == null) { // Check whether the input parameter is empty
            throw new IllegalArgumentException("Regex and string cannot be null"); // throw exception, regular expression and string cannot be null
        }

        Pattern pattern = Pattern.compile(regex); // Compile regular expression
        return pattern.matcher(str).matches(); // Use regular expressions to match strings and return the results
    }
}

// Function example
// Regular verification string example
// Input parameters: regex, regular expression; str, string to be verified
// Output parameter: isValid, whether it matches the regular expression
// Call example:
// String regex = "\d + ";
// String str = "12345";
// boolean isValid = RegexValidator.validateString(regex, str);
// System.out.println(isValid);
//Output result: For example, through the regular expression "\d + "verification string "12345", the result is: true
//The output result is: true

Through analysis, it is not difficult to find:

1. Naming: The class name RegexValidator and the function name validateString are clear and clear, allowing people to see their uses at a glance.

2. Comment: Above the validateString function, there is a detailed comment explaining the function, parameters and return value. This helps readers understand what the code does.

3. Exception handling: Inside the function, the input parameters are checked for null values and an IllegalArgumentException is thrown, which allows readers to clearly know what will happen if the input is null.

4. Sample call and output: In the last part of the code, a sample call and comments on the output results are provided, which makes it easier for readers to understand how to use this function and what its expected output is.

5. Code standardization: The format of the code is very standardized, and indentations, spaces, etc. all comply with Java coding standards, which helps improve the readability of the code.

In summary, this is a very readable code that is easy to understand and use. This code is generated by FuncGPT (intelligent function) launched by soflu software robot, a full-stack and fully automatic software development tool. As an important part of Feisuan SoFlu software robot, FuncGPT (Hui Function) supports the creation of all types of functions. Use natural language to describe Java function requirements and generate high-quality, highly readable Java function code in real time. The generated code can be directly copied to IDEA, or imported into the Java fully automatic development tool function library with one click. If you want to experience generating highly readable code in seconds, download and use FuncGPT for free now https://a.d4t.cn/QKKmTr.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139,168 people are learning the system