sheidaei
sheidaei

Reputation: 10332

How to change an interface in Java and its consequences?

What is the best practice for changing an interface in an application. If the interface has been implemented by many Java classes, what would be the best way to change it? Are you going to extend to a new class? Are you going to use any design pattern? or do you use delegation (I don't think there is any way using delegation)? Are you going to use deprecated annotation at all?

is this the best solution?

public interface interface1
{
}

public interface interface2 extends interface1
{
public void newMethod()
}

Upvotes: 3

Views: 529

Answers (4)

Kanika Maheshwari
Kanika Maheshwari

Reputation: 85

You can use design patterns. Abstract Factory or Bridge pattern can be used

Upvotes: 0

kosa
kosa

Reputation: 66637

If this method is not needed by all other classes implemented interface1, then I think by doing this you can avoid major code changes.

Then, next question, do we need this in interface2 (or) just having in the required class is enough?

If you don't want to define this new method as contract, in other words no other classes need to implement, then I wouldn't even create a interface2.

Upvotes: 0

Faelkle
Faelkle

Reputation: 485

There are two ways that immediately spring to mind.

  1. In your IDE, use a refactoring tool to change the interface. The more advanced IDE's (Eclipse can - I don't know about others) can refactor any known implementations immediately. This requires the affected projects to be open.
  2. Your solution, MyInterface2 extends MyInterface is used extensively too, because it doesn't break existing implementors.

If your solution came up in a code audit or review, I wouldn't reject it - it's fine, IMHO.

Upvotes: 3

ptyx
ptyx

Reputation: 4164

If you own the code, the best way to change an interface is to fix all references to it - rather than leave deprecated code around.

Upvotes: 0

Related Questions