How to properly declare a field as deprecated in Java
Deprecated?
Deprecated means that a class or method is no longer important, and will be suspended from the API. A class or method can evolve during its lifetime, methods signature change, new ones are being added and fields change. Such changes introduce a problem. Developers who are using the old API must be warned in some way that they are using a method that will no longer be in the API for a long time. Here is where the @Deprecated
annotation and the @deprecated
JavaDoc comes into play. When you specify this on a class or a method the compiler will issue a warning, but the code will still work.
When to Deprecate
When building software or API’s every now and then you might refactor your code and some classes or methods become obsolete, or even has some typo’s. Then you could deprecate these methods to preserve backward compatibility. Indicating that you could still use these classes or methods but that it is recommend that you’ll switch to the new indicated classes or methods. Some valid reasons would be:
- There are some typo’s in the contract
- It will be removed in a future release
- It contains bad practices
- It is insecure
- There is a better way to achieve the same goal
How to Deprecate
We strongly recommend to deprecate a method using both the @Deprecated
annotation available since Java J2SE 5.0 and the @deprecated
JavaDoc available since Java 1.1. When you deprecate something be sure to explain the reason why it is being deprecated and provide an valid alternative. Using the annotation causes the Java compiler to generate warnings. Here is an example how to deprecate a Java method.
/**
* @deprecated reason this method is deprecated </br>
* {will be removed in next version} </br>
* use {@link #new()} instead like this:
*
* <blockquote>
* <pre>
* new()
* </pre></blockquote>
*
*/
@Deprecated
public void old() {
}
remember to explain:- Why this class or method is no longer used, remember to separate line for readability </br>
- Inform your users when you are removing this class or method from your API.
- Provide your users with an alternative class or method that they can use
{@link #new()}