码迷,mamicode.com
首页 > 其他好文 > 详细

SonarQube规则翻译001-050

时间:2020-04-17 20:16:13      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:也有   浮点   引入   out   atomic   boot   dir   false   operator   

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
}

SonarQube规则翻译001-050

标签:也有   浮点   引入   out   atomic   boot   dir   false   operator   

原文地址:https://www.cnblogs.com/ioufev/p/12722128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!