2011-01-28

Java, @Override, and refactoring

We have been making some changes to the user interface of a project of which I'm a member. This requires me to change some automated user testing APIs and interfaces to match the new reality.

I don’t remember exactly who I was talking one day when they mentioned my use of the @Override annotation even when implementing interfaces. I told them the IDE added that, and I just left it at that. I couldn’t think of a great use case for that being there at the time, but since the IDE did it for me I figured there must be some point even in the case of interface implementation, so I left it in the code as it didn’t cause any issue and was correct logic.

Now that I have begun to refactor and remove some methods which no longer make sense, I am finding the @Override annotations very useful because the IDE points out what is implemented as an @Override when it isn’t actually overriding anything from a super class or interface. This is a compile time error, and were I not using a fancier IDE, I would still be alerted to the problem when the project was compiled. Thus, the annotation has been a nice aid in this type of refactoring.

This would also be the case of an actual method override in the case where the super method was not called from the override. In such a case, and without @Override, the logic would simply no longer be used, but would compile just fine. The call would be removed from calling code of the super class or interface for the obvious compiler reasons one would encounter, but if someone left that logic in the existing class by mistake, and someone thought it should be called because some other state depended on it without that class being rethought at the time of some major refactoring, then a serious issue has been introduced which could be hard to figure out.

I wanted to share this with everyone as I believe it can help everyone if @Override is always used. If you have a different opinion or thoughts on the topic please share.