Day931. Six commonly used security refactoring methods for legacy systems - system refactoring in practice

Hi, I am 阿昌, what I learned to record today is about 六种遗留系统常用的安全重构手法content.

For bad code smells, there are also some basic ones 安全重构手法. The security reconstruction methods commonly used in legacy systems are:

  • extract variables
  • Extract parameters
  • Extraction Method
  • Extract interface
  • move method or class
  • Modularize moves across modules

The safe refactoring method is to IDE 自动辅助complete , making the refactoring more efficient, and at the same time avoiding the risks of manually moving the code.


1. Extract variables

Extracting variables is to extract code expressions into method internal variables or class member variables.

Let's take a look at a code example. There is an if statement in the code, which has three conditional judgments.

void improveReadability() {
    
    
    if (platform.toUpperCase().indexOf("Android") > -1 &&
            browser.toUpperCase().indexOf("Chrome") > -1 &&
            pm.equals("com.tencent.mm")) {
    
    
    }
}

The conditional judgment logic in this sample code is relatively complicated, and it takes a certain amount of time to read and understand the meaning of the entire paragraph.

Code readability can be improved by extracting appropriate explanatory variables to illustrate the meaning of expressions.

Specifically, the safe refactoring method for extracting variables is as follows.

insert image description here

The following is the code after extracting variables and refactoring.

void improveReadability() {
    
    
    boolean isAndroid = platform.toUpperCase().indexOf("Android") > -1;
    boolean isChrome = browser.toUpperCase().indexOf("Chrome") > -1;
    boolean isInstallWeiXin = pm.equals("com.tencent.mm");
    if (isAndroid && isChrome && isInstallWeiXin) {
    
    
    }
}

It can be seen that the refactored code extracts 3 explanatory variables, which improves the readability of the code. It can be seen immediately that the conditional judgment statement is judging:

Does the string identify whether it belongs to the Android platform and the Chrome browser and has WeChat installed?

In practice, you need to pay attention to choosing a name that is "worthy of the name" 命名非常重要and avoid using abbreviations or naming methods that "do not express the meaning".


2. Extract parameters

Extract parameter is to extract the expression result inside the method into the parameter of the method.

You can decouple the dependence of variables by extracting parameters to improve the testability of the code.

Combined with a code example to study. This sample method relies on a userId variable, which needs to be obtained from the database, which will reduce the testability of the code.

void improveTestability() {
    
    
    String userId = UserDao.getId();
    if (valid(userId)) {
    
    
        Log.d("id", "improveTestability: " + userId);
    }
}

In this regard, reconstruction is carried out by extracting parameters.

insert image description here

The refactored code is as follows.

void improveTestability(String userId) {
    
    
    if (valid(userId)) {
    
    
        Log.d("id", "improveTestability: " + userId);
    }
}

It can be seen that after refactoring, the method does not depend on the specific database implementation, and the internal logic of the method can be tested by passing parameters. But in the process of practice need to pay attention to, 参数应该是越少越好,如果参数过多就要考虑封装成对象.

In addition, the order of the parameters should be arranged according to the order used inside the method, so that it is easier to read the code.


3. Extraction method

Extract method is to extract the expression of code into independent method.

Can be done via the extract method 减少重复代码, at the same time 提高代码的可维护性.

Let's look at a code example:


public class ExtractMethod {
    
    
    String name;
    String password;
    public void login(){
    
    
        if(name == null){
    
    
            return;
        }
        if(password == null){
    
    
            return;
        }
        accountLogin();
    }
    public void Register(){
    
    
        if(name == null){
    
    
            return;
        }
        if(password == null){
    
    
            return;
        }
        accountRegister();
    }
    private void accountLogin() {
    
    
    }
    private void accountRegister() {
    
    
    }
}

This is a piece of repetitive code, and the logic of judging the name and password is repeated.

At this time, you can use the extraction method to refactor.

insert image description here

This is the code after refactoring using the extract method.

public void login(){
    
    
    if (isInValid()) return;
    accountLogin();
}
public void Register(){
    
    
    if (isInValid()) return;
    accountRegister();
}
private boolean isInValid() {
    
    
    if (name == null) {
    
    
        return true;
    }
    if (password == null) {
    
    
        return true;
    }
    return false;
}

After extracting the method, it not only reduces the repeated code, but also takes a suitable name "isInValid" to express the meaning of the method for judging the validity of the user name and password, which is also possible 提高代码的可读性.

Here we must first pay attention to the problem of naming, and secondly, we need to control the size of the method. If the number of lines of a method exceeds 50 行(more than the size of one screen), further splitting is recommended.

Of course, it would be even better if the method can be controlled to about 10 lines.


4. Extract the interface

Extracting the interface is to extract the method in the class as an interface method, so that the class that originally depends on this class becomes an interface that depends on the extraction.

Usually when refactoring, some expressions are first extracted as methods, and then extracted into interfaces.

Extracting interfaces can 依赖行为更稳定change from relying on specific implementations to relying on specific abstract interfaces, and the refactored code is easier to expand.


When displaying pictures, it is necessary to download network pictures through a network-loaded library, and display them on the interface after the download is complete.

public void show() {
    
    
    String url = "http://XXX";
    Bitmap bitmap = new Picasso().load(url);
    showImage(bitmap);
}

Since the loading library of the network may be replaced in the iterative process, it is hoped that the code can be expanded more flexibly, and the logic of displaying pictures is not coupled with the specific picture loading framework. In this case, the safe reconstruction method of extracting parameters can be used to decouple.

insert image description here

This is the code after refactoring using the extract interface method.

private IImageLoader imageLoader;
public void show() {
    
    
    String url = "http://XXX";
    Bitmap bitmap = imageLoader.getBitmap(url);
    showImage(bitmap);
}

Here, the implementation that originally relied on the specific download image is refactored to rely on the specific abstract interface. When the implementation of the download image needs to be replaced, it only needs to inject the corresponding implementation.

In practice, it should be noted that extracting an interface also has costs, not only to define a new interface class, but also to inject the interface implementation into the class that calls the interface.

Generally speaking, you can consider extracting easily changing or unstable dependencies into interfaces, which can make the program easier to expand on the one hand, and improve the testability of the code on the other hand.


5. Mobile method or class

This method is relatively simple. In the use of automated tools to diagnose and analyze the Sharing project , it is organized with a new code structure. The refactoring method of moving classes has been fully used in the code. You only need to use the MOVE refactoring function of the IDE to safely move classes and automatically modify them. Refer to the import of this class. For the mobile method, it is relatively more complicated.

Divided into two cases to discuss separately:

  • One is the relatively simple mobile static method
  • The other is a relatively complex mobile non-static method.

移动静态方法It is relatively simple, you only need to select the method and use it MOVE 重构功能, and then select the class to move to.

insert image description here


For 移动非静态方法, the IDE only supports moving the method to the class of the member variable, and cannot move it arbitrarily.

You can also use the refactoring functionality of MOVE.

insert image description here

It should be noted here that if the code is used Kotlin 编写, the latest Android Studio Chipmunk does not yet support the function of the mobile method, and the system will prompt "Unable to perform refactoring".


6. Modularize cross-module movement

Modularize cross-module movement This function is an important function in component refactoring.

In the process of componentization, it is often necessary to move a page into an independent module, but this page may depend on other classes and resource files. If one by one is manually analyzed and moved, then this project will undoubtedly be very difficult . The Modularize cross-module movement can identify and move a class and its dependent classes and resources to the target module.


This feature can greatly reduce the efficiency of manually moving code and resources. The following demonstrates how to use this feature.

Here you need to move a class Modularize to another independent module. This class depends on an associated class ModularizeReationClass and a string resource, and needs to be moved together. The specific operation is as follows.

insert image description here

In the process of practice, you should pay attention to that when the dependent class of the moved class is used by other files, there will be an underline prompt when previewing the file with the preview function of Modularize. At this time, we need to decipher the underline prompt file first. Couple until there is no underline prompt in the preview function, and then confirm to move.


7. Summary

Six commonly used security refactoring methods for legacy systems are extracting variables, extracting parameters, extracting methods, extracting interfaces, moving methods or classes, and Modularize cross-module movement.

Use these refactoring techniques in the daily coding process to optimize the code structure more efficiently and improve the quality of the code.

Summarize the definitions, functions, and usage steps of these safe reconstruction methods into a mind map for reference.

insert image description here


Guess you like

Origin blog.csdn.net/qq_43284469/article/details/129869146