@Deprecated & @Override

1. @Deprecated” code should not be used

級別:cwe, obsolete, owasp-a9, security

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
class Fum { ... }

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
  }
}

不應該在程序中使用@Deprecated標註的接口、類和方法,該註解表明此功能已被廢棄,之所以還存在是爲了向前兼容,使用廢棄的功能容易引起安全問題。

2. “@Override” annotation should be used on any method overriding (since Java 5) or implementing (since Java 6) another one

級別:bad-practice

Using the @Override annotation is useful for two reasons :
1. It elicits a warning from the compiler if the annotated method doesn’t actually override anything, as in the case of a misspelling.
2. 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
}

當重寫父類的方法或實現接口中的方法時,應該在方法上標註@Override,一方面,這能提醒編譯器如果由於拼寫錯誤,這個方法在父類或接口中不存在,編譯器能給出警告。另一方面,@Override註解能提高代碼的可讀性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章