Java – When to deprecate and when to delete in Java

javaprogramming practicesrefactoring

As part of a refactoring effort or just ongoing development, a particular method or maybe an entire class may become obsolete in some sense. Java supports the @Deprecated annotation to indicate that there's probably a better way to handle the functionality in question. I imagine this is particularly useful in public API's where the effects of removing parts of an API might not be known. For a non-public API and a project that uses revision control systems (so deleting can be undone in some sense), when is it appropriate to deprecate rather than deleting the obsolete element(s)?

Best Answer

Is your API a public facing API? That dictates whether or not you should deprecate or remove. If the API is strictly for your benefit (i.e. only used within your company), then it is best to simply remove the offending code. It's much cleaner and will cause fewer maintenance headaches in the long run.

However, if the API is public facing simply removing a method can cause code that used to work with older versions of your library to stop working. That's where things get messy. The following are some guidelines:

  • Internal API: remove rather than deprecate. If any client is using an internal class or method, it is their fault if the tool breaks.
  • External API: deprecate first, remove later. Deprecation is a flag that something will be removed later. Later depends on what you believe is reasonable. At the very least give 2-3 versions before actually removing the deprecated code.