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());//获取目标路径
    File targetDir = new File(targetFilePath);
    if (!targetDir.exists()) {
        targetDir.mkdirs();//如果不存在目录则创建
    }

    String encryptedFilePath = this.getEncryptedFilePath(stepContext.getJobContext());//获取加密文件路径
    String fileName = this.getFileName(stepContext);//获取文件名
    File[] encryptedFiles = new File(encryptedFilePath).listFiles(this.buildFilenameFilter(fileName));//过滤文件

    FileEncryptor dencryptor = this.buildFileEncryptor(stepContext);//创建FileEncryptor
    Stream.of(encryptedFiles)
            .forEach(encryptFile -> {
                File targetFile = new File(targetFilePath, encryptFile.getName());
                dencryptor.invoke(encryptFile, targetFile);//解密文件
            });

    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.

Each 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 appropriate comments:

Comments are an important means to improve 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 whitespace 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 code 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:

// 类名:RegexValidator
// 函数名:validateString
// 函数功能:正则验证字符串
// POM依赖包:无

import java.util.regex.Pattern;

public class RegexValidator {
    /**
     * 正则验证字符串
     * @param regex 正则表达式
     * @param str 待验证的字符串
     * @return 是否匹配正则表达式
     */
    public static boolean validateString(String regex, String str) {
        if (regex == null || str == null) { // 检查入参是否为空
            throw new IllegalArgumentException("Regex and string cannot be null"); // 抛出异常,正则表达式和字符串不能为空
        }

        Pattern pattern = Pattern.compile(regex); // 编译正则表达式
        return pattern.matcher(str).matches(); // 使用正则表达式匹配字符串,并返回结果
    }
}

// 函数示例
// 正则验证字符串示例
// 入参:regex,正则表达式;str,待验证的字符串
// 出参:isValid,是否匹配正则表达式
// 调用示例:
// String regex = "\\d+";
// String str = "12345";
// boolean isValid = RegexValidator.validateString(regex, str);
// System.out.println(isValid);
// 输出结果:例如,通过正则表达式"\\d+"验证字符串"12345",结果为:true
// 则输出结果为: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 of the function. 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 , allowing 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. comply with Java coding standards, which helps to 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 the full-stack fully automatic software development tool soflu software robot. 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, pay attention to the WX "SoFlu Software Robot" experience .

Alibaba Cloud suffered a serious failure and all products were affected (restored). Tumblr cooled down the Russian operating system Aurora OS 5.0. New UI unveiled Delphi 12 & C++ Builder 12, RAD Studio 12. Many Internet companies urgently recruit Hongmeng programmers. UNIX time is about to enter the 1.7 billion era (already entered). Meituan recruits troops and plans to develop the Hongmeng system App. Amazon develops a Linux-based operating system to get rid of Android's dependence on .NET 8 on Linux. The independent size is reduced by 50%. FFmpeg 6.1 "Heaviside" is released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4868096/blog/10140626