When to use Single method Interfaces in Java - java

I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.
And the implementer class will implement many interfaces with single methods.
In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example ResultSet? Or is there some design standard which advocates the use of these type of interfaces?

With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.
So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.
Example:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
#Override void foo(int i){ Y.bar2(i); }
});
}

Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".
Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)
Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.

In what scenarios does it make sense to keep single method interfaces?
In such a scenarios when you need an interface with only one method.
Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.

Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:
public interface Quackable {
public void quack();
}
public class Quacks implements Quackable {
public void quack(){
//quack behavior
}
}
public class DontQuack implements Quackable {
public void quack(){
//dont quack
}
}
public class QuackableDuck{
Quackable quack; //add behavior dynamicall
}
So QuackableDuck class can add feature dynamically.
quack = new Quacks();
//or
quack = new DontQuack();
So similarly you can add multiple behavior to the class dynamically.

You create interfaces not according to the number of methods in it but to define behaviour expected by components of your systems to deliver a single responsibility to their neighbors. If you follow this simple principle/rule, you might or might not end up with single method interfaces, depending on the responsibility you are defining. I like to keep tests stupid simple and the application very flexible so I usually have many of those

Related

Any examples of bad uses of interface?

I want to avoid use interface when it's not needed. For example, there is an interface AAA, and there is a class AAAImpl implementing it, this interface AAA is only being implemented by AAAImpl, and AAAImpl is only implementing one interface, which is this AAA. The argument of doing this is the code is decoupled, it will be easier for unit testing, it leaves more options in the future for adding more features, etc.
Are these arguments valid?
One class implementing one interface is a perfectly valid strategy for designing a class library, as long as the users of your class have no direct access to the implementing class. This is information hiding at its best: the users see what they need to see, while you keep an ability to redesign your implementation in more ways than you could if you let the users access the implementing class directly.
This also gives your users the flexibility to test their code without relying on any of your code outside the interface definition.
Overall, it is a win-win situation with no downsides.
As far as bad uses of interfaces go, there is a number of possibilities:
Interfaces that attempt to do too much - Adding an interface that covers every single method of a class that performs many different tasks is a bad idea, with the exception of "infrastructure interfaces", e.g. interfaces required to define remoting.
Interfaces that attempt to do too little - Such interfaces cover a small part of functionality of the class, without enabling a meaningful task to be performed without making a reference to the implementing class.
Interfaces that provide a poor match for the functionality of the class - for example, adding IComparable<T> or IEquitable<T> to a mutable class.
One of the bad usege of interface is when iterface has more then it's needed and classes which implement the interface will have to implement all those methods which normally shouldn't.
For example, we have interface for printing and we have many different version of printing (from html document without footer, from html doc with footer, from pdf etc).
So our interface will look like:
public interface IPrinter{
public void printHtmlWithFooter();
public void printHtmlWithoutFooter();
public void printPdf();
}
and then you have implementations:
public class HtmlPrinter implements IPrinter{
public void printHtmlWithFooter(){
// some code, printing ....
}
public void printHtmlWithoutFooter(){
// some code, printing ....
}
public void printPdf(){}
}
public class PdfPrinter implements IPrinter{
public void printHtmlWithFooter(){}
public void printHtmlWithoutFooter(){}
public void printPdf(){
// some code, printing ....
}
}
as you see, you need to implement all of these methods in each class even if they are completely empty. Let's imagine that you have 10 different classes which implement IPrinter interface and you want to add one additional method into interface, so you need to do implementation in each of these classes.
That would be one of examples how you should not use interfaces.
Instead of that you should have only:
public interface IPrinter{
public void print();
}
and then client doesn't care how it will be printed and what, he only knows that method print() has to be called and that's it. Concrete classes should take care about concrete implementation.

Can interfaces evolve with time?

Interfaces are great from a flexibility standpoint. But in case, where an interface is used by a large number of clients. Adding new methods to the interface while keeping the old mehtods intact will break all clients' code as new methods won't be present in clients. As shown below:
public interface CustomInterface {
public void method1();
}
public class CustomImplementation implements CustomInterface {
#Override
public void method1() {
System.out.println("This is method1");
}
}
If at some point later in time, we add another method to this interface all clients' code will break.
public interface CustomInterface {
public void method1();
public void method2();
}
To avoid this we have to explicitly implement new methods in all clients' code.
So I think of interfaces and this scenario as following:
Interfaces once written are like carving in stone. They are rarely supposed, and expected to change. And if they do, they come with a huge cost(rewriting the whole code) which programmers should be ready for.
In continuation with the point above, Is it possible to write interfaces that can stand the test of time?
How such a scenario is handled in interfaces where you expect additional functionality in future? That is anticipating change in the contract by which all clients are binded.
EDIT: Default method is indeed a nice addition to Java Interfaces which a lot of people have mentioned in their answers. But my question was more in the context of code design. And how forcing method implementation on the client is an intrinsic character of an interface. But this contract between an interface and a client seems fragile as functionality will eventually evolve.
One solution to this problem was introduced in Java 8 in the form of default methods in interfaces. It allowed to add new methods to existing Java SE interfaces without breaking existing code, since it supplied default implementation to all the new methods.
For example, the Iterable interface, which is widely used (it's a super interface of the Collection interface) was added two new default methods - default void forEach(Consumer<? super T> action) and default Spliterator<T> spliterator().
public interface CustomInterface {
public void method1();
}
public interface CustomInterface2 extends CustomInterface {
public void meathod2();
}
Other than default method you can use inheritance property as show above by which new interface will have all previous method along with new methods and use this interface in your required situation.
Java 8 has introduced default implementation for methods. These implementations reside in the interface. If a new method with a default implementation is created in an interface that is already implemented by many classes, there is no need to modify all the classes, but only the ones that we want to have a different implementation for the newly defined method than the default one.
Now, what about older Java versions? Here we can have another interface that extends the first one. After that, classes that we want to implement the newly-declared method will be changed to implement the new interface. As shown below.
public interface IFirst {
void method1();
}
public class ClassOne implements IFirst() {
public void method1();
}
public class ClassTwo implements IFirst() {
public void method1();
}
Now, we want method2() declared, but it should only be implemented by ClassOne.
public interface ISecond extends iFirst {
void method2();
}
public class ClassOne implements ISecond() {
public void method1();
public void method2();
}
public class ClassTwo implements IFirst() {
public void method1();
}
This approach will be ok in most cases, but it does have downsides as well. For example, we want method3() (and only that one) for ClassTwo. We will need a new interface IThird. If later we will want to add method4() that should be implemented by both ClassOne and ClassTwo, we will need to modify (but not ClassThree that also implemented IFirst) we will need to change both ISecond and IThird.
There rarely is a "magic bullet" when it comes to programming. In the case of interfaces, it is best if they don't change. This isn't always the case in real-life situations. That is why it is advised that interfaces offer just "the contract" (must-have functionality) and when possible use abstract classes.
A future interface change shouldn't break anything that has been working -- if it does, it's a different interface. (It may deprecate things, though, and a full cycle after deprecation it may be acceptable to say that throwing an Unimplemented exception is acceptable.)
To add things to an interface, the cleanest answer is to derive a new interface from it. That will allow using objects implementing the new behaviors with code expecting the old ones, while letting the user declare appropriately and/or typecast to get access to the new features. It's a bit annoying since it may require instanceof tests, but it's the most robust approach, and it's the one you'll see in many industry standards.
Interfaces are contracts between the developer and clients, so you're right - they are carved in stone and should not be changed. Therefore, an interface should expose (= demand) only the basic functionality that's absolutely required from a class.
Take the List interface for example. There are many implementations of lists in Java, many of which evolve over time (better under-the-hood algorithms, improved memory storage), but the basic "concept" of a list - add an item, search for an item, remove an item - should not and will not ever change.
So, to your question: Instead of writing interfaces which classes implement, you can use abstract classes. Interfaces are basically purely-abstract classes, in the sense that they do not provide any built-in functionality. However, one can add new, non-abstract methods to an abstract class that clients will not be required to implement (override).
Take this abstract class (= interface) for example:
abstract class BaseQueue {
abstract public Object pop();
abstract public void push(Object o);
abstract public int length();
public void clearEven() {};
}
public class MyQueue extends BaseQueue {
#Override
public Object pop() { ... }
...
}
Just like in interfaces, every class that extends BaseQueue is contractually bound to implement the abstract methods. The clearEven() method, however, is not an abstract method (and already comes with an empty implementation), so the client is not forced to implement it, or even use it.
That means that you can leverage the power of abstract classes in Java in order to create non-contractually-binding methods. You can add other methods to the base class in the future as much as you like, provided that they are not abstract methods.
I think your question is more about design and techniques, so java8 answers are a bit misleading. This problem was known long before java8, so there are some other solutions for it.
First, there are no absolutely chargeless ways to solve a problem. The size of inconviniences that come from interface evolving depends on how the library is used and how deliberate your design is.
1) No techniques will help, if you designed an interface and forgot to include a mandatory method in it. Plan your design better and try to anticipate how clients will use your interfaces.
Example: Imagine Machine interface that has turnOn() method but misses turnOff() method. Introducing a new method with default empty implementation in java8 will prevent compilation errors but will not really help, because calling a method will have no effect. Providing working implementation is sometimes impossible because interface has no fields and state.
2) Different implementations usually have things in common. Don't be afraid to keep common logic in parent class. Inherit your library classes from this parent class. This will enforce library clients to inherit their own implementations from your parent class as well. Now you can make small changes to the interface without breaking everything.
Example: You decided to include isTurnedOn() method to your interface. With a basic class, you can write a default method implementation that would make sence. Classes that were not inherited from parent class still need to provide their own method implementations, but since method is not mandatory, it will be easy for them.
3) Upgrading the functionality is usually achieved by extending the interfaces. There's no reason to force library clients to implement a bunch of new methods because they may not need them.
Example: You decided to add stayIdle() method to your interface. It makes sence for classes in your library, but not for custom client classes. Since this functionality is new, it's better to create a new interface that will extend Machine and use it when it's needed.

Why does all the interface methods need to be implemented in a class implementing it in java

I know that it is the purpose of the interface and the class can be declared abstract to escape from it.
But is there any use for implementing all the methods that we declare in an interface? will that not increase the weight and complexity of the code if we keep on defining all the methods even it is not relevant for that class? why it is designed so?
The idea of an interface in Java is very much like a contract (and perhaps seen in retrospect this should have been the name of the concept)
The idea is that the class implementing the interface solemnly promises to provide all the things listed in the contract so that any use of a class implementing the interface is guaranteed to have that functionality available.
In my experience this facility is one of the things that makes it possible to build cathedrals in Java.
What you are critizing is exactly the goal interface achieve.
If you don't want to implement an interface, don't declare your class implementing it.
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
When you program against an interface, you want the concrete object behind it to implement all its methods. If your concrete object doesn't need or cannot implement all interface method you probably have a design issue to fix.
When any piece of code receives an instance of an interface without knowing what class is behind it, that piece of code should be assured of the ability to call any method in an interface. This is what makes an interface a contract between the callers and the providers of the functionality. The only way to achieve that is to require all non-abstract classes implementing the interface to provide implementations for all its functions.
There are two general ways to deal with the need to not implement some of the functionality:
Adding a tester method and an implementation that throws UnsupportedOperationException, and
Splitting your interface as needed into parts so that all method of a part could be implemented.
Here is an example of the first approach:
public interface WithOptionalMehtods {
void Optional1();
void Optional2();
boolean implementsOptional1();
boolean implementsOptional2();
}
public class Impl implements WithOptionalMehtods {
public void Optional1() {
System.out.println("Optional1");
}
public void Optional2() {
throw new UnsupportedOperationException();
}
public boolean implementsOptional1() {
return true;
}
public boolean implementsOptional2() {
return false;
}
}
Here is an example of the second approach:
public interface Part1 {
void Optional1();
}
public interface Part2 {
void Optional2();
}
public Impl implements Part1 {
public void Optional1() {
System.out.println("Optional1");
}
}
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
Yes you are right it will. That is why it is best practice in your coding to follow the Interface Segregation Principle which recommends not to force clients to implement interfaces that they don't use. So you should never have one "fat" interface with many methods but many small interfaces grouping methods, each group serving a specific behavior or sub-module.
This way clients of an interface implement only the needed methods without ever being forced into implementing methods they don't need.
It may depend on Liskov Substitution Principle
So, having A implements B means that you can use A when B is needed and, to make it work without problems, A must have at least the same methods of B.
Please keep in mind that mine is not a "proper" answer, as it's not based on official sources!
When implementing an Interface,we may not need to define all the method declared in the Interface.We can define the some methods,that we don't need,With nothing inside the body.

java interface problem

interface Block{
void printblock();
}
interface Block2{
void printblock();
}
class Impl2 implements Block,Block2{
#Override
public void printblock() {
// TODO Auto-generated method stub
System.out.println("Impl2");
}
}
public class Import
{
public static void main(String[] args) {
new Impl2().printblock();
}
}
Now please say me which printblock method is implementing by the class Import.Its implementing Block interface or Block2 interface?
Interface is just a contract and in your case there are two different interfaces vouching that that a class has a method implemented with a particular signature so it doesn't matter which interface the method belongs to.
As both interface have same method signature both method will be implemented by Impl2 class as a one method. Impl2 class is implementing a method printblock() with the same signature both interfaces has.So you can say that Imlp2 is implementing method of both the interfaces.
When you are writing
new Impl2().printblock();
It doesnt matter what Interface the method printblock is part of.
If you write something like
Block block1 = new Impl2();
block1.printlblock(); or similarly block2.printblock().
Here now both are valid statements and since both have the same method definition, same method will be executed. Interesting thing is because their definition is same its not possible to implement same method definitions in two different ways(though you want it differently for each of them)
Your question has already been answered here
Syntactically, an interface doesn't really mean anything other than the fact that some method of a certain name exists.
Semantically, however, the power of interfaces is that they form a "guarantee" of an implementation of some method to be in accordance with the behavior described by the interface itself. That is, by choosing to implement Block or Block2, you are contracting yourself to their behavioral expectations (specifically, containing their method).
In your example, the fact that your class implements both Block and Block2 is an explicit statement that you are implementing both of them--don't be confused by the fact that their method names are the same! The syntax only tells you that the method EXISTS in Impl2. What's more important is what behaviors Block and Block2 define/expect.
For example, if you had two interfaces called List and Set, and wanted one data structure to be able to represent both semantically, you may have a size() method that is the same for both, and thus it implements both List.size() and Set.size().
Of course, interfaces are also very easy to abuse if you are not careful with semantics. You would have big issues implementing both List and Set if they defined the same add() method, because by definition, the List.add() behavior allows duplicates, and Set.add() does not. So there is a trap here--you may think you can implement both interfaces based on similarities in some methods, but it turns out they define fundamentally different behaviors in other methods.
In general, it seems to me like any time you are implementing two interfaces at the same time with the same method, something is wrong with the class design. Perhaps what you really wanted to do was combine shared behavior into a superinterface, and implement that. It would be a much stronger construct since you would be explicitly defining the shared portions of the interfaces, and wouldn't run into implementation issues with the distinct portions.

why we need interface instead of class and what we are achieving from interface

As we know that we can declare only the method signature and also can not create the instance of a Interface. then why we need interface. Unnecessary its loading into JVM. This is also one performance degradation. We are creating the interface and several classes implementing that interface and defining all the methods of the interface. Actually what we achieved from this interface. Could you please give me some example.
Interface is you are forcing your client to implement some specified thing, implementation will be remain to the client.Also java doesn't support multiple inheritance by extending multiple classes you can have multiple interface implemented.
For example : List declares add(..) method all the implementation of List provides it implementations.
Simpler would be.
You define an Interface Animal and a method speak() it means all Animal must will have to speak with different different implementation. Man will speak,Dog will bark,Lion will roar.
Why should we go for create class Animal extra. We can declare the speak() in every class. What is befit we will get from Animal class and implementing speak() in all the sub classes. Still I did not get this concept
Main advantage is inheritance and polymorphism [core concepts of OOP]
You are specifying Animal's behavior here also.
You can have
Animal obj = new Man();
Animal obj = getAnimalForThisCriteria(something here);//this will return some animal at runtime so you can catch instance using Animal.
You might have Three different Class Ma,Dog,Lion with same method but there is no way to tell they all are animal unless they extends or implements common class or interface, here comes the concept of structure
Having interfaces separate from classes allows for clear separation between, well, the interface of an object and its implementation. Without them you would have no standard way to indicate that some class should not contain implementation details at all.
Second, since Java does not support multiple inheritance, interfaces are a partial workaround, by allowing inheritance on the outward features of the class.
Interfaces are for when you care only about an object's capabilities, not how it achieves them.
Suppose you are writing the high level control code for a robot. You don't care about how the robot actually works, you only want to be able to tell it to go forward, backward, turn left or right, etc. Without interfaces, you would implement a abstract class called AbstractRobot that has all methods as abstract methods. At this point you have basically created an interface,but in the form of an abstract class, but one that is 'heavier' than required.
Lastly, a class can conform to multiple interfaces, but can only inherit from one class. This allows some design patterns which rely on multiple inheritance.
I'll try to explain this in simple words.
Consider your favorite Computer Game, say Counter Strike.
In this game, the players (terrorists or counter-terrorists) use weapons.
If we teach the player how to use weapon (analogous to Interface), it can use any weapon like AK47, Maverick, Shotgun, Sniper (analogous to classes which inherit Weapon interface).
The advantage of this is consider Bazooka (which implements Weapon) is developed in future versions. Then the current player will be able to use it without any modifications - as it knows how to use Weapon interface :-)
This is just a simple example. There are many other reasons for using interfaces.
An analogy for an interface is to think of a class using an interface as being like an electric wall outlet, and think of the implementation as the plug. The outlet doesn't care what's behind the plug, as long as it fits in the outlet. In psuedocode terms it could be written like this:
public interface ElectricOutlet {
public void powerUp();
}
And a class that implements ElectricOutlet might look like this:
public class Appliance implements ElectricOutlet {
//member variables
public void powerUp() {
//Draw power from the wall
}
...
}
So how do you use that interface? Like this:
//lots of other code
ElectricOutlet out = new Appliance(); //plug the appliance into the outlet
out.powerUp; //power it up!
Of course, it doesn't have to be an appliance that you plug into an outlet. It could be a TV, or a laptop, or a lawn mower, but they all behave the same way from the outlet's point of view. So how does this apply to programming? In exactly the same way:
List<String> list = new ArrayList<String>(); // create a new List of Strings
I just created a new (empty) List of Strings. If it turns out that ArrayList doesn't provide the right performance, and LinkedList works better, I can go back and change that line to this:
List<String> = new LinkedList<String>(); //should work better now
I can do this because both ArrayList and LinkedList implement the List interface, and thus they provide the same behavior (API), even though the internal implementations may be different. From the List's point of view, however, it doesn't matter what the internal workings are, just as long as the interface is there. This allows a lot of independence between classes, and allows more reuse.
Simple. I think Interfaces and Abstract classes are for the same purpose. The difference is If you extend an Abstract Class, you could not extend no other class in Java. Reason: Java does not support Multiple Inheritance. At the same time, You can implement any number of Interface for a class.
The most important use of interfaces as i see it is passing code(anonymous inner class or lambda) to a method as parameter.
Example:
Suppose we want to make a method which can return the execution time required to run a piece of code. We want to pass our code as a parameter to this method.
interface Code{
public void run();
}
long getExectutionTime(Code code){
long startTime = System.nanoTime();
code.run();
return System.nanoTime() - startTime;
}
getExecutionTime(new Code(){
public void run(){
//the code to be executed
}
});
In java 8,
getExecutionTime(()->{
//the code to be executed
});
Interface is nothing but its a guide line for the new implementation
it provides some instructions for new implementation and categorize the functionality of the object .In details like if we create an interface then we create an instruction for the implementation .

Categories