Reputation: 51
If we have an interface which is being implemented by large number of classes in our application, and we need to add a method to the interface, What is the recommended way to do it?
Would the approach differ if we are using older version of java (let's say 1.5) vs if we are using newer version of java (let's say 1.8).
Upvotes: 1
Views: 282
Reputation: 4307
This won't be a popular answer, but it seems right to me that the operation you envisage is a difficult one.
Interfaces define a service contract between different sub-systems. Changing that contract should be more difficult that changing an implementation. Java 8 introduced "default" methods on interfaces, which converts the interface from being a strict contract, to a kind of abstract base class. I guess it might take some of the sting out of changing interfaces, but I think it's right that developers should feel that sting.
In fact, in an ideal world, all interfaces would be agreed in advance, and there should never be a need to change one. I guess that's impractical, but I see no need to make it easy.
The short answer, I think, is that if you change an interface, you should reflect on what changes are needed in all the implemented classes, grit your teeth, and get on and make them.
Upvotes: 2
Reputation: 44130
we need to add a method to the interface
Well then there's no way around it. Without any context for what you're adding and why, I'll take your word for it that you do need to. Make sure that's actually the case.
Java 5: add the method. Fix all the classes implementing it.
You can consider adding a default to a new abstract base class which implements the interface, and make all implementations extend that. Then if you're in the same situation in the future you'll have an easier time.
Java 8: add a default method
Upvotes: 0
Reputation: 5789
you should always follow the principle of "Open for extension Close for modification"
if u add a new method the repercussions will be in all the Classes implementing it , U have to implement the method to all (be it java 5 or 8 until its a default method), so better
Create a new interface and the needful classes should extend it
Upvotes: 1