Java – How to Properly Deprecate Methods

continuous integrationdeprecationjavaversion control

Today I lost a method that I was using since my co-worker redefined it to take its superclass instead. So after synchronizing with the repository I had trouble. Would it had been better in this case to use some annotation like @Deprecated instead of removing the method so that I would get an error message telling my that the method was deprecated? Can a version control system or an IDE work around situations like this by deprecating methods instead of deleting them?

Best Answer

@Deprecated annotation is the correct thing to do. Removing code creates breaking changes in the API that is being used - this can be bad.

The thing is that often people ignore the 'bad' thing and still use deprecated methods because it doesn't fail the build. Thus, the next correct thing to do is to make using deprecated methods fail the build.

It is possible to make the build scripts often used by Java developers to fail the build on compiler warnings (not only errors). There are various approaches to doing this depending on the build system being used (gradle, maven, ant, ...).

At the point that you now fail the build when (unconsciously) using the deprecated method (you upgraded the library, something is now deprecated, the build fails - this is a good thing).

At that point, you can specifically disable deprecated warning for that method call with @SuppressWarnings( "deprecation" ) and then it will build again. But now you know that you need to fix that code, because your build failed and that alerted you to the changing API.