Java Top

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll have a look at deprecated APIs in Java and how to use the @Deprecated annotation.

2. The @Deprecated Annotation

As a project evolves its API changes. Over time, there are certain constructors, fields, types or methods that we don’t want people to use anymore.

Instead of breaking the backward compatibility of the project’s API, we can tag these elements with the @Deprecated annotation.

@Deprecated tells other developers that the marked element should no longer be used. It’s common to have a Javadoc accompany the @Deprecated annotation to explain what would be a better alternative that serves the right behavior:

public class Worker {
    /**
     * Calculate period between versions
     * @deprecated
     * This method is no longer acceptable to compute time between versions.
     * <p> Use {@link Utils#calculatePeriod(Machine)} instead.
     *
     * @param machine instance
     * @return computed time
     */
    @Deprecated
    public int calculate(Machine machine) {
        return machine.exportVersions().size() * 10;
    }
}

Remember that a compiler only displays the deprecated API warning if the given Java element is used somewhere in the code. So, in this case, it’d only show if there was code that called the calculate method.

Also, we can communicate deprecated status in documentation as well by using the Javadoc @deprecated tag in the method description.

3. Conclusion

In this quick article, we saw how to use the @Deprecated annotation to mark code that should no longer be used.

The full source code for the examples can be found over on GitHub.

Java bottom

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of