SonarQube規則翻譯001-050


1.".equals()" should not be used to test the values of "Atomic" classes

equals()方法不應該用在原子類型的數據上(如:AtomicInteger, AtomicLong, AtomicBoolean).

AtomicInteger, and AtomicLong extend Number, but they're distinct from Integer and Long and should be handled differently. AtomicInteger and AtomicLong are designed to support lock-free, thread-safe programming on single variables. As such, an AtomicInteger will only ever be "equal" to itself. Instead, you should .get() the value and make comparisons on it.

Atomiclnteger類和AtomicLong類繼承自Number類,但是它們與Integer類和Long類有不同點,因此在使用上也有不同。 Atomiclnteger類和AtomicLong類是為支持單個變量的線程安全和無需鎖定而設計的。因此,一個Atomiclnteger對象的.equal方法比較只有在跟自己比較的時候才會返回 true 。所以,對於比較它們的值是否相等,就應當使用 Atomiclnteger對象的.get()方法,進行取值比較。

This applies to all the atomic, seeming-primitive wrapper classes: AtomicInteger, AtomicLong, and AtomicBoolean.

這條規則適用於所有的 atomic類對象,具體參考封裝類: Atomiclnteger , AtomicLong 和 AtomicBoolean。

Noncompliant Code Example

錯誤的代碼示例

AtomicInteger aInt1 = new AtomicInteger(0);
AtomicInteger aInt2 = new AtomicInteger(0);

if (aInt1.equals(aInt2)) { ... }  // Noncompliant

Compliant Solution

正確的代碼示例

AtomicInteger aInt1 = new AtomicInteger(0);
AtomicInteger aInt2 = new AtomicInteger(0);

if (aInt1.get() == aInt2.get()) { ... }

2."=+" should not be used instead of "+="

"=+"不可以替代 “+=”.

The use of operators pairs (=+,=-or=!) where the reversed, single operator was meant (+=,-=or!=) will compile and run, but not produce the expected results.

使用相反的運算符對(=+=-=!),意味着運算符按照(+ =-=!=)將編譯並運行, 但不會產生預期的結果。

This rule raises an issue when=+,=-, or=!is used without any spacing between the two operators and when there is at least one whitespace character after.

= += -= !時,此規則會引起問題。 在兩個運算符之間沒有空格且之后至少有一個空格字符時使用。

Noncompliant Code Example

錯誤的代碼示例

int target = -5; 
int num = 3;

target =- num; // Noncompliant; target = -3. Is that really what's meant? 
target =+ num; // Noncompliant; target = 3

Compliant Solution

正確的代碼示例

int target = -5; 
int num = 3;

target = -num; // Compliant; intent to assign inverse value of num is clear 
target += num;

3."==" and "!=" should not be used when "equals" is overridden

It is equivalent to use the equality == operator and the equals method to compare two objects if the equals method inherited from Object has not been overridden. In this case both checks compare the object references.

But as soon as equals is overridden, two objects not having the same reference but having the same value can be equal. This rule spots suspicious uses of == and != operators on objects whose equals methods are overridden.

如果繼承自對象的 equals method沒有被重寫,則使用等號"==操作符和equals方法來比較兩個對象是等價的,否則不能用等號操作符.

Noncompliant Code Example

錯誤的代碼示例

String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();

if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value

Compliant Solution

正確的代碼示例

String firstName = getFirstName();
String lastName = getLastName();

if (firstName != null && firstName.equals(lastName)) { ... };

4."@CheckForNull" or "@Nullable" should not be used on primitive types

"@CheckForNull" 或者 "@Nullable" 注解不應該用於基本類型(byte, short, int, long, float, double, boolean, char).

By definition, primitive types are not Objects and so they can't benull. Adding@CheckForNullor@Nullableon primitive types adds confusion and is useless.

This rule raises an issue when@CheckForNullor@Nullableis set on a method returning a primitive type: byte, short, int, long, float, double, boolean, char.

根據定義,原始類型不是對象,因此它們不能為空。 在基本類型上添加@CheckForNullor @Nullable會增加混亂,並且沒有用。

當在返回基礎類型的方法上設@CheckForNullor @Nullable時,此規則這些基礎類型引起問題:字節,短整數,整型,長整數,浮點型,雙精度型,布爾型,字符型。

Noncompliant Code Example

錯誤的代碼示例

@CheckForNull
boolean isFoo() {
 ...
}

Compliant Solution

正確的代碼示例

boolean isFoo() {
 ...
}

5."@Controller" classes that use "@SessionAttributes" must call "setComplete" on their "SessionStatus" objects

使用了“@SessionAttributes”注解的“@Controller”類必須在其“SessionStatus”對象上調用“setComplete”.

A Spring@Controllerthat uses@SessionAttributesis designed to handle a stateful / multi-post form. Such@Controllers use the specified@SessionAttributesto store data on the server between requests. That data should be cleaned up when the session is over, but unlesssetComplete()is called on theSessionStatusobject from a@RequestMappingmethod, neither Spring nor the JVM will know it's time to do that. Note that theSessionStatusobject must be passed to that method as a parameter.

Noncompliant Code Example

錯誤的代碼示例

@Controller
@SessionAttributes("hello")  // Noncompliant; this doesn't get cleaned up
public class HelloWorld {

  @RequestMapping("/greet", method = GET)
  public String greet(String greetee) {

    return "Hello " + greetee;
  }
}

Compliant Solution

正確的代碼示例

@Controller
@SessionAttributes("hello")
public class HelloWorld {

  @RequestMapping("/greet", method = GET)
  public String greet(String greetee) {

    return "Hello " + greetee;
  }

  @RequestMapping("/goodbye", method = POST)
  public String goodbye(SessionStatus status) {
    //...
    status.setComplete();
  }

}

6."@Deprecated" code should not be used

被@Deprecated 注解標注的代碼不應該被使用.

Once deprecated, classes, and interfaces, and their members should be avoided, rather than used, inherited or extended. Deprecation is a warning that the class or interface has been superseded, and will eventually be removed. The deprecation period allows you to make a smooth transition away from the aging, soon-to-be-retired technology.

Noncompliant Code Example

錯誤的代碼示例

/**
 * @deprecated  As of release 1.3, replaced by {@link #Fee}
 */
@Deprecated
public class Fum { ... }

public class Foo {
  /**
   * @deprecated  As of release 1.7, replaced by {@link #doTheThingBetter()}
   */
  @Deprecated
  public void doTheThing() { ... }

  public void doTheThingBetter() { ... }
}

public class Bar extends Foo {
  public void doTheThing() { ... } // Noncompliant; don't override a deprecated method or explicitly mark it as @Deprecated
}

public class Bar extends Fum {  // Noncompliant; Fum is deprecated

  public void myMethod() {
    Foo foo = new Foo();  // okay; the class isn't deprecated
    foo.doTheThing();  // Noncompliant; doTheThing method is deprecated
  }
}

7."@EnableAutoConfiguration" should be fine-tuned

@EnableAutoConfiguration”缺點是它可能加載和配置應用程序永遠不會使用的bean,因此會消耗比實際需要更多的CPU和RAM。@EnableAutoConfiguration應該配置為排除應用程序不需要的所有bean.

"@EnableAutoConfiguration" is a convenient feature to configure the Spring Application Context by attempting to guess the beans that you are likely to need. The drawback is that it may load and configure beans the application will never use and therefore consume more CPU and RAM than really required.@EnableAutoConfigurationshould be configured to exclude all the beans not required by the application. Alternatively, use the@Importannotation instead of@EnableAutoConfiguration, to explicitly import the useful AutoConfiguration classes.

This rule applies for@SpringBootApplicationas well.

Noncompliant Code Example

錯誤的代碼示例

@SpringBootApplication
public class MyApplication {
...
}
@Configuration
@EnableAutoConfiguration
public class MyApplication {
...
}

Compliant Solution

正確的代碼示例

@SpringBootApplication(exclude = {
  MultipartAutoConfiguration.class,
  JmxAutoConfiguration.class,
})
public class MyApplication {
...
}
@Configuration
@EnableAutoConfiguration(exclude = {
  MultipartAutoConfiguration.class,
  JmxAutoConfiguration.class,
})
public class MyApplication {
...
}
@Configuration
@Import({
        DispatcherServletAutoConfiguration.class,
        EmbeddedServletContainerAutoConfiguration.class,
        ErrorMvcAutoConfiguration.class,
        HttpEncodingAutoConfiguration.class,
        HttpMessageConvertersAutoConfiguration.class,
        JacksonAutoConfiguration.class,
        ServerPropertiesAutoConfiguration.class,
        PropertyPlaceholderAutoConfiguration.class,
        ThymeleafAutoConfiguration.class,
        WebMvcAutoConfiguration.class
})
public class MyApplication {
...
}

8."@Import"s should be preferred to "@ComponentScan"s

由於@ComponentScan會減慢項目啟動的速度,應該選擇顯式引入jar包的“@Import”注解,而不是“@ComponentScan”注解.

@ComponentScanis used to find which Spring@Componentbeans (@Serviceor@RepositoryorController) are available in the classpath so they can be used in the application context. This is a convenient feature especially when you begin a new project but it comes with the drawback of slowing down the application start-up time especially when the application becomes bigger (ie: it references a large JAR file, or it references a significant number of JAR files, or the base-package refers to a large amount of .class files).

@ComponentScanshould be replaced by an explicit list of Spring beans loaded by@Import.

The interface@SpringBootApplicationis also considered by this rule because it is annotated with@ComponentScan.

Noncompliant Code Example

錯誤的代碼示例

@ComponentScan
public class MyApplication {
...
}

@SpringBootApplication
public class MyApplication {
...
}

Compliant Solution

正確的代碼示例

@Configuration
@Import({
        DispatcherServletAutoConfiguration.class,
        ErrorMvcAutoConfiguration.class,
        HttpEncodingAutoConfiguration.class,
        HttpMessageConvertersAutoConfiguration.class,
        MultipartAutoConfiguration.class,
        ServerPropertiesAutoConfiguration.class,
        PropertyPlaceholderAutoConfiguration.class,
        WebMvcAutoConfiguration.class
})
public class MyApplication {
...
}

9."@NonNull" values should not be set to null

@NonNull注解修飾的字段不能被賦為null, 標記為@NotNull、@NonNull或@NonNull的字段、參數和返回值通常在使用前不檢查空值。將這些值中的一個設置為null,或者在構造函數中沒有設置這樣的類fieldin,可能會在運行時導致nullpointerexception.

Fields, parameters and return values marked@NotNull,@NonNull, or@Nonnullare assumed to have non-null values and are not typically null-checked before use. Therefore setting one of these values tonull, or failing to set such a class field in a constructor, could causeNullPointerExceptions at runtime.

Noncompliant Code Example

錯誤的代碼示例

public class MainClass {

  @Nonnull
  private String primary;
  private String secondary;

  public MainClass(String color) {
    if (color != null) {
      secondary = null;
    }
    primary = color;  // Noncompliant; "primary" is Nonnull but could be set to null here
  }

  public MainClass() { // Noncompliant; "primary" Nonnull" but is not initialized
  }

  @Nonnull
  public String indirectMix() {
    String mix = null;
    return mix;  // Noncompliant; return value is Nonnull, but null is returned.}}
  }

10."@Override" should be used on overriding and implementing methods

在重寫和實現方法時,需要添加"@Override"注解.

Using the@Overrideannotation is useful for two reasons :

  • It elicits a warning from the compiler if the annotated method doesn't actually override anything, as in the case of a misspelling.
  • It improves the readability of the source code by making it obvious that methods are overridden.

Noncompliant Code Example

錯誤的代碼示例

class ParentClass {
  public boolean doSomething(){...}
}
class FirstChildClass extends ParentClass {
  public boolean doSomething(){...}  // Noncompliant
}

Compliant Solution

正確的代碼示例

class ParentClass {
  public boolean doSomething(){...}
}
class FirstChildClass extends ParentClass {
  @Override
  public boolean doSomething(){...}  // Compliant
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM