Using interfaces as class members [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.

To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.

An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.

Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?

Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.

Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.

"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...

I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html

It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Related

What is use of assaigning subclass object to superclass reference variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Java Code Style -- Interfaces vs. Abstract Classes

A new collaborator of mine who was reviewing some code I'd written told me that she wasn't used to seeing interfaces used directly in Java code, e.g.:
public interface GeneralFoo { ... }
public class SpecificFoo implements GeneralFoo { ... }
public class UsesFoo {
GeneralFoo foo = new SpecificFoo();
}
instead, expecting to see
public interface GeneralFoo { ... }
public abstract class AbstractFoo implements GeneralFoo { ... }
public class SpecificFoo extends AbstractFoo { ... }
public class UsesFoo {
AbstractFoo foo = new SpecificFoo();
}
I can see when this pattern makes sense, if all SpecificFoos share functionality through AbstractFoo, but if the various Foos have entirely different internal implementations (or we don't care how a specific Foo does Bar, as long as it does it), is there any harm in using an interface directly in code? I realize this is probably a tomato/tomato thing to some extent, but I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing.
If you have no need for an abstract class with certain details common to all implementations, then there's no real need for an abstract class. Complexity often gets added to applications because there is some perceived need to support future features that haven't yet been defined. Stick with what works, and refactor later.
No, she's inexperienced, not right. Using interfaces is preferred, and writing redundant abstract super classes for the sake of redundancy is redundant.
UsesFoo should care about the behaviour specified by the interface, not about the super class of its dependencies.
For me "she wasn't used to" is not good enough reason. Ask her to elaborate on that.
Personally I'd use your solution, because:
AbstractFoo is redundant and ads no value in current situation.
Even if AbstractFoo was needed (for some additional functionality), I'd always use lowest needed type: if GeneralFoo was sufficient, then I'd use that, not some class derived from it.
It depends only on your problem.
If you use interfaces only, then if all your classes have a same method, it would have to be implemented redundantly (or moved away to a Util class).
On the other hand, if you do write an intermediary abstract class, you solved that problem, but now your subclass may not be a subclass of another class, because of absence of multiple inheritance in Java. If it was already necessary to extend some class, this is not possible.
So, shortly - it's a trade off. Use whichever is better in your particular case.
There is not harm in directly using an interface in code. If there were, Java would not have interfaces.
The disadvantages of using an interface directly include not being able to reach and class-specific methods which are not implemented in the interface. For poorly written interfaces, or classes which add a lot of "other" functionality, this is undesirable as you lose the ability to get to needed methods. However, in some cases this might be a reflection of a poor design choice in creating the interface. Without details it is too hard to know.
The disadvantages of using the base class directly include eventually ignoring the interface as it is not frequently used. In extreme cases, the interface becomes the code equivalent of a human appendix; "present but providing little to no functionality". Unused interfaces are not likely to be updated, as everyone will just use the base abstract class directly anyway. This allows your design to silently rot from the viewpoint of anyone who actually tries to use the interface. In extreme cases, it is not possible to handle an extending class through the interface to perform some critical functionality.
Personally, I favor returning classes via their interface and internally storing in members them via their lowest sub-class. This provides intimate knowledge of the class within the class's encapsulation, forces people to use the interface (keeping it up-to-date) externally, and the class's encapsulation allows possible future replacement without too much fuss.
I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing
That reasons for the first interfaces style:
Often, the design is such that the interface is the public interface of the concept while the abstract class is an implementation detail of the concept.
For example, consider List and AbstractList in the collection framework. List is really what clients are usually after; fewer people know about about AbstractList because its an implementation detail to aid suppliers (implementers) of the interface), not clients (users) of the class.
The interface is looser coupling, therefore more flexible to support future changes.
Use the one that more clearer represents the requirement of the class, which is often the interface.
For example, List is often used rather than AbsrtactList or ArrayList. Using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an AbstractList or an ArrayList. If this class relied on some AbstractList-specific property, i.e. it needs to use an AbstractList method, then using AbstractList list = ... instead of List list = ... may be a hint that this code relies on something specific to an AbstractList .
It may simplify testing/mocking to use the smaller, more abstract interface rather than to use the abstract class.
It is considered a bad practice by some to declare variables by their AbstractFoo signatures, as the UsesFoo class is coupled to some of the implementation details of foo.
This leads to less flexibility - you can not swap the runtime type of foo with any class that implements the GeneralFoo interface; you can only inject instances that implement the AbstractFoo descendant - leaving you with a smaller subset.
Ideally it should be possible for classes like UsesFoo to only know the interfaces of the collaborators they use, and not any implementation details.
And of course, if there is no need to declare anything abstract in a abstract class AbstractFoo implements GeneralFoo - i.e. no common implementation that all subclasses will re-use - then this is simply a waste of an extra file and levels in your hierarchy.
Firstly I use abstract and interface classes plentifully.
I think you need to see value in using an interface before using it. I think the design approach is, oh we have a class therefore we should have an abstract class and therefore we should have interfaces.
Firstly why do you need an interface, secondly why do you have an abstract class. It seems she may be adding things, for adding things sake. There needs to be clear value in the solution otherwise you are talking about code that has no value.
Emperically there you should see the value in her solution. If there is no value the solution is wrong, if it cant be explained to you she does not understand why she is doing it.
Simple code is the better solution and refactor when you need the complexity, flexibility or whatever perceived value she is getting from the solution.
Show the value or delete the code!
Oh one more thing have a look at the Java library code. Does that use the abstract / interface pattern that she is applying .. NO!

Is there any true point to the Java interface? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How are Java interfaces actually used?
I'm not talking from an accademic buzzword point of view but from a pratical developer point of view.
So taking the example:-
Class1 implements Interface
public String methodOne() {
return "This is Class1.methodOne()";
}
public String methodTwo() {
return "This is Class1.methodTwo()";
}
}
Class2:
Class2 implements Interface
public String methodOne() {
return "This is Class2.methodOne()";
}
public String methodTwo() {
return "This is Class2.methodTwo()";
}
}
Using the Interface:-
Client {
Interface intface = new Class1();
intface.methodOne();
intface.methodTwo();
Interface intface = new Class2();
intface.methodOne();
intface.methodTwo();
}
But what are the benefits over just writting:-
Client {
Class1 clas1 = new Class1();
clas1.methodOne();
clas1.methodTwo();
Class2 clas2 = new Class2();
clas2.methodOne();
clas2.methodTwo();
}
And bypass the Interface altogether.
Interfaces just seem to be an additional layer of code for the sake of an additional layer of code,
or is there more to them than just "Here are the methods that the class you are accessing has"?
When using standalone classes, you don't need interfaces. However, when you have a type hierarchy, interfaces are indeed indispensable.
Your simple example does not really do justice, but let's rename your interface to something more useful and concrete, e.g. a Sorter algorithm which can take a list of items and sort them. You can have several different sorting algorithms implemented, and you may want to change the algorithm used, based on the context (i.e. QuickSort is faster for large data sets, but BubbleSort is better for small data sets, etc.) So you don't want to tie the client code to one specific algorithm. By using the polymorphic Sorter type (implemented as an interface), you can pass different concrete sorter objects to the client, without it knowing (and caring) what algorithm it is actually using. And you can any time introduce a better sorting algorithm, or remove one which proved inefficient, without the clients noticing anything.
Such a feat would be impossible without interfaces. The alternative would be calling the sort method of choice directly from (possibly duplicated) if-else or switch blocks all over the place, with the inevitable possibility of introducing bugs when forgetting to update all places properly when a sorting algorithm is added/removed... not to mention that you would need to recompile all client code after each such change :-(
Suppose you want a collection of objects with both methods "Method1" and "Method2".
And you don't want to programatically check each instance in the collection for its type.
A collection of objects the implement that interface saves you from doing this.
It calls Polymorphism and it is very useful.
The other folks have pretty much covered your question but, in a word: Yes!
The Java language was actually conceived as a fairly minimal object-oriented language, and interfaces were there from the very beginning. There are concepts of describing the relationships between classes that are hard or impossible to do without either interfaces or some performance-costly runtime type identification. All or almost all the patterns quoted in the famous Design Patterns book (here's the book itself) rely on interfaces.
(Not sure how I respond without it being seen as an answer but...)
Wow, so many answers so quickly, pretty impressive forum - cheers! :-D
So would it be reasonable to say that an Interface essentially sets the 'rules' for which the concrete classes must meet?
For example if I had classes Class1 & Class2, both of which have method 'getList()'.
Without implementing an Interface Class1.getList() could return say a list of Strings and Class2.getList() could return Integers.
Essentially the Interface sets the rules that my Class has to have a method of getList() and that method must return List,
so if both implement the Interface Lister with method 'public String getList();' I know that both Class1 & Class2 getList() returns a
List of types String.
But concrete Class1 could be returning a list of departments whereas Class2 is a list of employees, but I know they both return a list of Strings.
This would probably become more useful if I had maybe half dozen or so classes each with half dozen methods all of which I want to
ensure meet the .getList returns a list of type String 'rule'.
I use interfaces mostly for
simulating multiple inheritance
defining a service contract and a service implementation
single method callback contracts
and because
some dependency injection frameworks require interfaces to work
mocking interfaces easier than mocking classes
many AOP frameworks work better with interfaces than classes
And it is not really a layer of code between a service and its client, but more a formal contract.
Interfaces are useful if there is a chance that you'll need more than one implementation, maybe for another technology (different database) or for testing.
Interfaces define the contract of the type, without anu implementation details. This lets you program against the interface without knowing the actual implementation class.
An example of the advantage of interfaces using your code could be:
public void useInterface(Interface obj) {
obj.methodOne();
obj.methodTwo();
}
and calling it as in:
useInterface(new Class1());
useInterface(new Class2());
The Java collections classes make heavy use of interfaces, it allows you to switch implementations for lists and maps later without having to change the code using those instances.
Consider the following method which receives a list of 'intfaces', you don't have to know if you handle clas1 or clas2, you just want to handle something that 'is a' intface. You may add clas3 implement intface later on and it will stil work...
public void callMethods(List<intface> intfaces){
for(Interface intface : intfaces) {
intface.methodOne();
intface.methodTwo();
}
}

Coding to interfaces? [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Based on the above:
Are there any fallacies in my understanding of "coding to interfaces"?
Are there any benefits of coding to interfaces that I missed?
Thanks.
Just one possible correction:
To use the interface one can simply call the methods on an instance of the concrete class.
One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:
List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");
If you decided to switch to another List implementation, the client code works without change:
List<String> l = new LinkedList<String>();
This is especially useful for hiding implementation details, auto generating proxies, etc.
You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.
Your understanding seems to be right on. Your co-worker just swung by your desk and has all the latest pics of the christmas party starring your drunk boss loaded onto his thumbdrive. Your co-worker and you do not think twice about how this thumbdrive works, to you its a black box but you know it works because of the USB interface.
It doesn't matter whether it's a SanDisk or a Titanium (not even sure that is a brand), size / color don't matter either. In fact, the only thing that matters is that it is not broken (readable) and that it plugs into USB.
Your USB thumbdrive abides by a contract, it is essentially an interface. One can assume it fulfills some very basic duties:
Plugs into USB
Abides by the contract method CopyDataTo:
public Interface IUSB {
void CopyDataTo(string somePath); //used to copy data from the thumbnail drive to...
}
Abides by the contract method CopyDataFrom:
public Interface IUSB {
void CopyDataFrom(); //used to copy data from your PC to the thumbnail drive
}
Ok maybe not those methods but the IUSB interface is just a contract that the thumbnail drive vendors have to abide by to ensure functionality across various platforms / vendors. So SanDisk makes their thumbdrive by the interface:
public class SanDiskUSB : IUSB
{
//todo: define methods of the interface here
}
Ari, I think you already have a solid understanding (from what it sounds like) about how interfaces work.
The main advantage is that the use of an interface loosely couples a class with it's dependencies. You can then change a class, or implement a new concrete interface implementation without ever having to change the classes which depend on it.
To use the interface one can simply call the methods on an instance of the concrete class.
Typically you would have a variable typed to the interface type, thus allowing only access to the methods defined in the interface.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Sort of. Most importantly, it allows you to write APIs that take parameters with interface types. Users of the API can then pass in their own classes (which implement those interfaces) and you code will work on those classes even though they didn't exist yet when it was written (such as java.util.Arrays.sort() being able to sort anything that implements Comparable or comes with a suitable Comparator).
From a design perspective, interfaces allow/enforce a clear separation between API contracts and implementation details.
The aim of coding against interfaces is to decouple your code from the concrete implementation in use. That is, your code will not make assumptions about the concrete type, only the interface. Consequently, the concrete implementation can be exchanged without needing to adjust your code.
You didn't list the part about how you get an implementation of the interface, which is important. If you explicitly instantiate the implementing class with a constructor then your code is tied to that implementation. You can use a factory to get an instance for you but then you're as tied to the factory as you were before to the implementing class. Your third alternative is to use dependency injection, which is having a factory plug the implementing object into the object that uses it, in which case you escape having the class that uses the object being tied to the implementing class or to a factory.
I think you may have hinted at this, but I believe one of the biggest benefits of coding to an interface is that you are breaking dependency on concrete implementation. You can achieve loose coupling and make it easier to switch out specific implementations without changing much code. If you are just learning, I would take a look at various design patterns and how they solve problems by coding to interfaces. Reading the book Head First: Design Patterns really helped things click for me.
As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes.
The only sort of mutation i see in your thinking is this - You're going to call out expected contracts, not expected functionality. The functionality is implemented in the concrete classes. The interface only states that you will be able to call something that implements the interface with the expected method signatures. Functionality is hidden from the calling object.
This will allow you to stretch your thinking into polymorphism as follows.
SoundMaker sm = new Duck();<br/>
SoundMaker sm1 = new ThunderousCloud();
sm.makeSound(); // quack, calls all sorts of stuff like larynx, etc.<br/>
sm1.makeSound(); // BOOM!, completely different operations here...

"Program to an interface". What does it mean? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Categories