静态变量设为non-public或者加final关键字

Class variable fields should not have public accessibility

  • Vulnerability
  • Minor
  • Main sources
  • cwe
  • Available SinceNov 16, 2021
  • SonarAnalyzer (Java)
  • Constant/issue: 10min

Public class variable fields do not respect the encapsulation principle and has three main disadvantages:

  • Additional behavior such as validation cannot be added.
  • The internal representation is exposed, and cannot be changed afterwards.
  • Member values are subject to change from anywhere in the code and may not meet the programmer's assumptions.

By using private attributes and accessor methods (set and get), unauthorized modifications are prevented.

Noncompliant Code Example

public class MyClass {

  public static final int SOME_CONSTANT = 0;     // Compliant - constants are not checked

  public String firstName;                       // Noncompliant

}

Compliant Solution

public class MyClass {

  public static final int SOME_CONSTANT = 0;     // Compliant - constants are not checked

  private String firstName;                      // Compliant

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

}

原代码
    public static AsyncHttpClient asyncHttpClient;
 /** * 设置异步请求参数 */
    static {
        AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
        builder.setMaxConnections(MAX_TOTAL_CONNECTION);
        builder.setMaxConnectionsPerHost(2000);
        builder.setRequestTimeout(SO_TIMEOUT);
        asyncHttpClient = new AsyncHttpClient(builder.build());
    }

按照以上原则,因为是在代码块中初始化,所以无法加final关键字,于是去掉public就好

static AsyncHttpClient asyncHttpClient;

如果这会导致其他文件引用这个变量时访问不到,可将这两个类放在同一个包里面


 

posted on 2022-02-18 10:55  rachelgarden  阅读(228)  评论(0编辑  收藏  举报

导航