In OOP what are the different meanings of interface in the different contexts they apply to [closed] - oop

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm a bit new to object oriented programming. On my journey I have come across something that has had me confused for a few days now. It is the term "interface" and how it has different meanings in different contexts and even different programming languages. I want to understand "interface" but when I do my research I seem to get different definitions as if it has multiple meanings.
Would someone kindly give me a concise definition of interface in each context (just the main ones)?
I purchased a book called the object oriented thought process by Matt Weisfeld where some of them have been identified which are below:
Graphical user interface
The interface to a class is basically the signatures of its methods
Objective-C code can be broken up into physically separate modules called interface and impelentation
A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class
(Are there any more uses/definitions of the term interface in OOP than those identified above?)
If someone would kindly explain the different contexts of the term interface in OOP it would be highly appreciated.

Short answer:
Your 4th bullet point probably comes closest to the generally accepted notion of what OOP interfaces are: contracts between parties that need to interact with one another. Such contracts define the means (a) provided by one party, and (b) required by the other, in order to do so.
Long answer:
Very generally speaking, an interface is a thing that allows two (possibly very different) entities to interact with each other; it enables them to work together while at the same time allowing them to stay apart. The interface is the "common ground" that both parties agree on.
(Can be as simple as a door lock: Both the lock and any key able to work it must "fit together" in one place; you could call that place the interface.)
How does this general definition apply to your list?
Graphical user interface
A GUI allows humans and computer programs to interact. It does not require the computer to become fully human (and listen with ears, talk with the mouth, smile, etc.), neither does it require of the human to become a computer program itself. (UIs from past decades excluded. :)
"The interface to a class is basically the signatures of its methods"
The (publicly visible) methods and their exact signatures are the only means by which other types are going to be able to interact with that class, so in that sense, they together form that class' interface.
Also, a general description of each constructor and method is typically a part of the interface as well as a short general description of the purpose of the class and each of its methods. And of course, the name of the class itself -- pretty important.
"Objective-C code can be broken up into physically separate modules called interface and [implementation]"
I don't know Objective-C well enough to comment on that, but many languages have a module system that allows you to partition your codebase into separate, functionally independent modules. These usually don't have to expose all their types and functions to outsiders; each module may carefully declare what can be seen by other modules. As above, all that is chosen to be exposed is the "interface", because it will be the only way to interact with whatever is in the module. That "whatever is in the module" stays hidden; it's called the "implementation", and outsiders should not have to know about it.
"A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class"
This is perhaps what comes closest to the generally accepted notion of interfaces in OOP: That they are contracts between parties that want to interact. See short answer at the beginning of this question.
Basically, a Java interface allows us to describe a group of methods and their exact signatures, but it won't allow us to provide the implementation. Therefore it's a pure interface; it cannot be called directly. It only describes how one could interact with a class that actually implemented it. (The two parties do not necessarily have to be "parent" and "child".)
Ideally, an interface should not just state what one class has to offer; it should also describe what a typical consumer will need, thereby keeping the interface focused in a well-encapsulated system. (I am referring to the Single-Responsibility Principle here.)

Interface is a concept of abstraction and encapsulation. It is basically a contract you should comply to or given to ie, Interface is just a contract between two parties so that they know how they will interact with each other. An interface generally defines how you can interact with a class, the methods that it supports.
An interface contains only the signatures of the methods. The methods dont have anything neither interface can do anything. It is just a pattern.
Now in this anAbstarctMethod() is the Interface which is defined and it only has signatures but it doesnot have the implementation. Now when the class ASubClass implements the ineterface then the actual implementation is provided to the interface.
As far as Graphical user Interface is concerned I dont think that may necessarily be Object Oriented Programming. The wiki says that a graphical user interface is just a user interface through which you can interact with the electronic devices through icons and other indicators.
The Java doc has given a good example for this:-
Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on the other side of
its plastic casing. You press the "power" button to turn the
television on and off.
A good example from here:-
An interface is a description of the actions that an object can do...
for example when you flip a light switch, the light goes on, you don't
care how, just that it does. In Object Oriented Programming, an
Interface is a description of all functions that an object must have
in order to be an "X". Again, as an example, anything that "ACTS LIKE"
a light, should have a turn_on() method and a turn_off() method. The
purpose of interfaces is to allow the computer to enforce these
properties and to know that an object of TYPE T (whatever the
interface is ) must have functions called X,Y,Z, etc.
You may also check Why Use Interfaces?
Another powerful design technique is to have a single class implement
multiple interfaces. If you do this, you will have objects that
support multiple interfaces and, therefore, multiple behaviors. When
used together with run-time type inspection, this becomes very
powerful.

In OOP, the term "interface" means basically all the method signatures for all the messages that can be sent to objects of a class. So in Objective-C, it would be all the method declarations in the header file.
The term "Graphical User Interface" is not using the word "interface" in an OO context.
Item #2 on your list is an OO interface.
Item #3 is referring to the .h and .m files.
Item #4 refers to the keyword 'interface' in the Java language and equating it to the keyword 'protocol' in the objective-C language.

General meaning:
An Interface is essentially something that interacts with something else
For example: An interface can be with a python application and the Skype-API (thought off the top of my head xD)

An interface is a form of multiple inheritance (without the 'alleged' complications that brings) (it's a controversial subject)
OO is founded on the "is a" relationship, MI (multiple inheritance) allows an object to be several things. Interfaces define a way for them to be these things, without an implementation.
They are "what you must to _to be a _ whatever".

Related

Is encapsulation just a capsula creation?

Recently I was talking to a very experienced programmer (8+ years of experience) and he told me that "combining data with functions that work with them in a capsula" is a wrong term for encapsulation. He told me that that was what encapsulation allowed me to do, but not what encapsulation itself was. He told me that as soon as inheritance is not possible without encapsulation, encapsulation must be just a capsula creation (class or anything like that). But today I got interviewed by a less experienced programmer and he was so sure all those classic definitions on wikipedia were right he told me not to even think of passing the interview. So I tried to google all that stuff about encapsulation, and about inheritence not being possible without encapsulation, but didn't find anything. But I can't believe that experienced programmer was wrong, he convienced not only me, but other experienced programmers too. Maybe that correct definition is just something that is lost in the chunks of useless and unimportant info?
So please, give me answers on these two questions:
1) can inheritence be possible without encapsulation? (A class's Inheritence from a class)
2) If not, then can we consider declaring a class encapsulation? Because only after declaring a class we can inherit.
Well, I'm Sorry, but I fail to see the connection between encapsulation and inheritance.
Encapsulation is hiding your internal implementation behind a publicly visible API.
Basically, it's a separation between a type's actual implementation and what it exposes.
In a broad sense, one can look at even the human body and see encapsulation:
For example: You are breathing air in and out, that's your public API, but the internals of what your body is doing with this air are hidden away inside your respiratory system - your lunges passes oxygen to your blood and collects from it carbon dioxide in return - thus changing the mixture ratio of the gasses in the air you breath, but none of this is visible to the outside world.
Inheritance, in the OOP world, is the ability to take a specific object, and derive an even more specific object from it, while adding capabilities (and sometimes mutating existing capabilities via overriding).
For example: A Dog is a kind of Mammal which is a kind of Animal.
An Animal might contain methods such as Eat() and properties such as Weight and Age.
A Mammal might override the Eat() method to implement suckling (from it's mother's breast) as an infant, but depending on it's age eating solid foods.
A Dog might introduce another capability such as Bark.
All of this have nothing to do with encapsulation as desribed in the previous paragraph.
Inheritance is tightly related to another core principle of object oriented programming called Polymorphism - basically, the ability to reference a derived class using it's base class type - perhaps you (or the interviewer) are confusing the two?
However, today is the first time I've seen another definition of encapsulation (and I've been working with oop languages for about two decades now):
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
Under that
definition, encapsulation is the process of creating capsules - stand-alone code snippets that holds data and ways to interact with it - a.k.a types, classes, etc', and is somewhat related to inheritance - in order to inherit a type, that type first needs to be defined.
However, the way I see it, this definition is not enough to define encapsulation. It can be a part of the definition, but not a stand-alone definition of encapsulation.

Is it good practice for every public method to be covered by an interface?

It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.

"Client" concept in OOP Design Patterns?

I read many topics about OOP Design Patterns of GoF, but i am not sure about "Client" concept. So what is it? How can we realize it in our application. Thank!
In the gof book, the client is the code or class that is using the classes in the pattern.
for example, from the abstract factory pattern under motivation:
Consider a user interface toolkit that supports multiple look-and-feel standards, such as Motif and Presentation Manager. Different look-and-feels define different appearances and behaviors for user interface "widgets" like scroll bars, windows, and buttons. To be portable across look-and-feel standards, an application should not hard-code its widgets for a particular look and feel. Instantiating look-and-feel-specific classes of widgets throughout the application makes it hard to change the look and feel later.
We can solve this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget. There's also an abstract class for each kind of widget, and concrete subclasses implement widgets for specific look-and-feel standards. WidgetFactory's interface has an operation that returns a new widget object for each abstract widget class. Clients call these operations to obtain widget instances, but clients aren't aware of the concrete classes they're using. Thus clients stay independent of the prevailing look and feel.
There is a concrete subclass of WidgetFactory for each look-and-feel standard. Each subclass implements the operations to create the appropriate widget for the look and feel. For example, the CreateScrollBar operation on the MotifWidgetFactory instantiates and returns a Motif scroll bar, while the corresponding operation on the PMWidgetFactory returns a scroll bar for Presentation Manager. Clients create widgets solely through the WidgetFactory interface and have no knowledge of the classes that implement widgets for a particular look and feel. In other words, clients only have to commit to an interface defined by an abstract class, not a particular concrete class.
A WidgetFactory also enforces dependencies between the concrete widget classes. A Motif scroll bar should be used with a Motif button and a Motif text editor, and that constraint is enforced automatically as a consequence of using a MotifWidgetFactory.
As a pattern, a client is an actor that initiates an interaction with a server, which is a functional, but typically passive, actor. Acting on the client's behalf as described by a request, the server performs some action and makes a report back in the form of a response.
As such, the point of a client interface is to make it convenient or possible for arbitrary code to formulate a request and attract the attention of a server. Since the request message might be conveyed over a wide variety of media (a different memory space, for example), some kind of transparent transport is usually involved, hidden behind this request interface.
That's pretty much the long and short of it as a concept. One of the drawbacks of a very flexible pattern (which certainly applies to client/server) is one needs to descend into a specific example, framework or library to speak concretely.
The client is just another module, or class, form the system use the concrete Pattern (all or part of the components construct the pattern)
A client is a caller/consumer. A client is not a subclass/implementer. In terms of a method, a client is the caller of that method. In terms of a class, a client is the caller of methods in that class.
You could say that every method has a client, because without a caller a method is dead code; however, the term client is typically reserved for the caller of a public method, since private methods are just implementation details, not relevant to design.
In a design diagram, such as a UML class diagram, a client indicates where the public access points are and how the design is used after it is implemented.

Unused Interface Parameters

I have an interface that is implemented by thirty concrete classes. The concrete implementers are subdivided into two groups, with each group inheriting from a common abstract class. The abstract classes define the constructors for the concrete implementers, including passing in a database connection object for each "side" of the two sides (they have different databases, among other differences).
All the current interface methods each have several parameters needed for the concrete classes to "get the job done", but not all are used in every implementer.
When I went to add a new method to the interface this morning, I realized that the database connection is going to be needed for only one of the concrete implementers, but the rest will not need it. So, that gets me wondering, should I pass it in as a parameter? It is needed to "get the job done", but for only one of the concrete classes, and that class has the database connection already. If I passed the database connection in as an interface parameter, then the other 29 classes will not use it.
What is a good line to draw for what is an acceptable interface parameter? Any reading/content on the subject I will thankfully devour as well.
All the current interface methods each have several parameters needed
for the concrete classes to "get the job done", but not all are used
in every implementer.
That sounds to me a lot like the interface is slowly turning into a bit of a "god interface". Check whether this is the case by asking yourself a couple of questions:
Does the interface represent a single behavioural concept in your model, or has it become a bit of a convenient dumping ground for method signatures from several concepts? Could it be called something like e.g. Serializable, or would it more accurately be called SerializableAndSomethingElse.
Could you carve the interface up into several more cohesive interfaces, and have the 30 different objects implement just the ones they need?
When I went to add a new method to the interface this morning, I
realized that the database connection is going to be needed for only
one of the concrete implementers, but the rest will not need it. So,
that gets me wondering, should I pass it in as a parameter?
No. In fact, if the database connection is only needed by one of the implementers then it doesn't sound like it belongs in the interface at all. The interface should represent the abstract API, where as it sounds as though the database connection is a part of the implementation of that API.
If it's not part of the abstraction -- then it shouldn't be in the interface. And if it's only used by 1 of 30 implementing classes, then it's definitely not part of the abstraction.
I did a quick google search for 'api design' and the first hit was:
slides of a presentation by Joshua Bloch.
His points that are relevant to your question:
"When in doubt leave it out"
'Don't let implementation details “leak” into API'
"API design is tough", but also, "API design is a noble and rewarding craft"
"Expect to make mistakes"
It sounds like you have a tough problem to solve -- but good luck!
It sounds like you are following implementation driven design as opposed to use case driven one. You'll be able to answer some of these questions yourself by considering the perspective of the caller. I've got more details in this blog post:
http://theamiableapi.com/2011/08/29/considering-the-perspective-of-the-caller/
Cheers,
Ferenc
The constructor arguments to your various classes should be collaborators (or configuration values) used in processing. This is the how. These can vary for the 30 different implementations. If the database connection is required for some and not others, then only supply it as a constructor argument to one.
The interface then forms a basis for the processing should be done. This is the what.
You should strive for an interface where the API name, arguments and methods are at the same conceptual level. Constructor arguments are likely to be at a lower conceptual level.

Why would I want to use Interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.
One specific example: interfaces are a good way of specifying a contract that other people's code must meet.
If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.
Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)
Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.
The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details.
The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.
The easiest way of understanding interfaces is that they allow different objects to expose COMMON functionality. This allows the programmer to write much simplier, shorter code that programs to an interface, then as long as the objects implement that interface it will work.
Example 1:
There are many different database providers, MySQL, MSSQL, Oracle, etc. However all database objects can DO the same things so you will find many interfaces for database objects. If an object implements IDBConnection then it exposes the methods Open() and Close(). So if I want my program to be database provider agnostic, I program to the interface and not to the specific providers.
IDbConnection connection = GetDatabaseConnectionFromConfig()
connection.Open()
// do stuff
connection.Close()
See by programming to an interface (IDbconnection) I can now SWAP out any data provider in my config but my code stays the exact same. This flexibility can be extremely useful and easy to maintain. The downside to this is that I can only perform 'generic' database operations and may not fully utilize the strength that each particular provider offers so as with everything in programming you have a trade off and you must determine which scenario will benefit you the most.
Example 2:
If you notice almost all collections implement this interface called IEnumerable. IEnumerable returns an IEnumerator which has MoveNext(), Current, and Reset(). This allows C# to easily move through your collection. The reason it can do this is since it exposes the IEnumerable interface it KNOWS that the object exposes the methods it needs to go through it. This does two things. 1) foreach loops will now know how to enumerate the collection and 2) you can now apply powerful LINQ exprssions to your collection. Again the reason why interfaces are so useful here is because all collections have something in COMMON, they can be moved through. Each collection may be moved through a different way (linked list vs array) but that is the beauty of interfaces is that the implementation is hidden and irrelevant to the consumer of the interface. MoveNext() gives you the next item in the collection, it doesn't matter HOW it does it. Pretty nice, huh?
Example 3:
When you are designing your own interfaces you just have to ask yourself one question. What do these things have in common? Once you find all the things that the objects share, you abstract those properties/methods into an interface so that each object can inherit from it. Then you can program against several objects using one interface.
And of course I have to give my favorite C++ polymorphic example, the animals example. All animals share certain characteristics. Lets say they can Move, Speak, and they all have a Name. Since I just identified what all my animals have in common and I can abstract those qualities into the IAnimal interface. Then I create a Bear object, an Owl object, and a Snake object all implementing this interface. The reason why you can store different objects together that implement the same interface is because interfaces represent an IS-A replationship. A bear IS-A animal, an owl IS-A animal, so it makes since that I can collect them all as Animals.
var animals = new IAnimal[] = {new Bear(), new Owl(), new Snake()} // here I can collect different objects in a single collection because they inherit from the same interface
foreach (IAnimal animal in animals)
{
Console.WriteLine(animal.Name)
animal.Speak() // a bear growls, a owl hoots, and a snake hisses
animal.Move() // bear runs, owl flys, snake slithers
}
You can see that even though these animals perform each action in a different way, I can program against them all in one unified model and this is just one of the many benefits of Interfaces.
So again the most important thing with interfaces is what do objects have in common so that you can program against DIFFERENT objects in the SAME way. Saves time, creates more flexible applications, hides complexity/implementation, models real-world objects / situations, among many other benefits.
Hope this helps.
One typical example is a plugin architecture. Developer A writes the main app, and wants to make certain that all plugins written by developer B, C and D conform to what his app expects of them.
Interfaces define contracts, and that's the key word.
You use an interface when you need to define a contract in your program but you don't really care about the rest of the properties of the class that fulfills that contract as long as it does.
So, let's see an example. Suppose you have a method which provides the functionality to sort a list. First thing .. what's a list? Do you really care what elements does it holds in order to sort the list? Your answer should be no... In .NET (for example) you have an interface called IList which defines the operations that a list MUST support so you don't care the actual details underneath the surface.
Back to the example, you don't really know the class of the objects in the list... neither you care. If you can just compare the object you might as well sort them. So you declare a contract:
interface IComparable
{
// Return -1 if this is less than CompareWith
// Return 0 if object are equal
// Return 1 if CompareWith is less than this
int Compare(object CompareWith);
}
that contract specify that a method which accepts an object and returns an int must be implemented in order to be comparable. Now you have defined an contract and for now on you don't care about the object itself but about the contract so you can just do:
IComparable comp1 = list.GetItem(i) as IComparable;
if (comp1.Compare(list.GetItem(i+1)) < 0)
swapItem(list,i, i+1)
PS: I know the examples are a bit naive but they are examples ...
When you need different classes to share same methods you use Interfaces.
Interfaces are absolutely necessary in an object-oriented system that expects to make good use of polymorphism.
A classic example might be IVehicle, which has a Move() method. You could have classes Car, Bike and Tank, which implement IVehicle. They can all Move(), and you could write code that didn't care what kind of vehicle it was dealing with, just so it can Move().
void MoveAVehicle(IVehicle vehicle)
{
vehicle.Move();
}
The pedals on a car implement an interface. I'm from the US where we drive on the right side of the road. Our steering wheels are on the left side of the car. The pedals for a manual transmission from left to right are clutch -> brake -> accelerator. When I went to Ireland, the driving is reversed. Cars' steering wheels are on the right and they drive on the left side of the road... but the pedals, ah the pedals... they implemented the same interface... all three pedals were in the same order... so even if the class was different and the network that class operated on was different, i was still comfortable with the pedal interface. My brain was able to call my muscles on this car just like every other car.
Think of the numerous non-programming interfaces we can't live without. Then answer your own question.
Imagine the following basic interface which defines a basic CRUD mechanism:
interface Storable {
function create($data);
function read($id);
function update($data, $id);
function delete($id);
}
From this interface, you can tell that any object that implements it, must have functionality to create, read, update and delete data. This could by a database connection, a CSV file reader, and XML file reader, or any other kind of mechanism that might want to use CRUD operations.
Thus, you could now have something like the following:
class Logger {
Storable storage;
function Logger(Storable storage) {
this.storage = storage;
}
function writeLogEntry() {
this.storage.create("I am a log entry");
}
}
This logger doesn't care if you pass in a database connection, or something that manipulates files on disk. All it needs to know is that it can call create() on it, and it'll work as expected.
The next question to arise from this then is, if databases and CSV files, etc, can all store data, shouldn't they be inherited from a generic Storable object and thus do away with the need for interfaces? The answer to this is no... not every database connection might implement CRUD operations, and the same applies to every file reader.
Interfaces define what the object is capable of doing and how you need to use it... not what it is!
Interfaces are a form of polymorphism. An example:
Suppose you want to write some logging code. The logging is going to go somewhere (maybe to a file, or a serial port on the device the main code runs on, or to a socket, or thrown away like /dev/null). You don't know where: the user of your logging code needs to be free to determine that. In fact, your logging code doesn't care. It just wants something it can write bytes to.
So, you invent an interface called "something you can write bytes to". The logging code is given an instance of this interface (perhaps at runtime, perhaps it's configured at compile time. It's still polymorphism, just different kinds). You write one or more classes implementing the interface, and you can easily change where logging goes just by changing which one the logging code will use. Someone else can change where logging goes by writing their own implementations of the interface, without changing your code. That's basically what polymorphism amounts to - knowing just enough about an object to use it in a particular way, while allowing it to vary in all the respects you don't need to know about. An interface describes things you need to know.
C's file descriptors are basically an interface "something I can read and/or write bytes from and/or to", and almost every typed language has such interfaces lurking in its standard libraries: streams or whatever. Untyped languages usually have informal types (perhaps called contracts) that represent streams. So in practice you almost never have to actually invent this particular interface yourself: you use what the language gives you.
Logging and streams are just one example - interfaces happen whenever you can describe in abstract terms what an object is supposed to do, but don't want to tie it down to a particular implementation/class/whatever.
There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code. You can also provide an sort of standardized API for simple operations.
For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects. If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.
If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.
Interfaces encourage looser coupling of your code so that you can have greater flexibility.
In an article in my blog I briefly describe three purposes interfaces have.
Interfaces may have different
purposes:
Provide different implementations for the same goal. The typical example
is a list, which may have different
implementations for different
performance use cases (LinkedList,
ArrayList, etc.).
Allow criteria modification. For example, a sort function may accept a
Comparable interface in order to
provide any kind of sort criteria,
based on the same algorithm.
Hide implementation details. This also makes it easier for a user to
read the comments, since in the body
of the interface there are only
methods, fields and comments, no long
chunks of code to skip.
Here's the article's full text: http://weblogs.manas.com.ar/ary/2007/11/
The best Java code I have ever seen defined almost all object references as instances of interfaces instead of instances of classes. It is a strong sign of quality code designed for flexibility and change.
As you noted, interfaces are good for when you want to force someone to make it in a certain format.
Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.
For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I know they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.
Interfaces are rarely used because of this, since usually you can make assumptions or don't really require the data to do what you need to do.
An interface, defines merely the interface. Later, you can define method (on other classes), which accepted interfaces as parameters (or more accurately, object which implement that interface). This way your method can operate on a large variety of objects, whose only commonality is that they implement that interface.
First, they give you an additional layer of abstraction. You can say "For this function, this parameter must be an object that has these methods with these parameters". And you probably want to also set the meaning of these methods, in somehow abstracted terms, yet allowing you to reason about the code. In duck-typed languages you get that for free. No need for explicit, syntax "interfaces". Yet you probably still create a set of conceptual interfaces, something like contracts (like in Design by Contract).
Furthermore, interfaces are sometimes used for less "pure" purposes. In Java, they can be used to emulate multiple inheritance. In C++, you can use them to reduce compile times.
In general, they reduce coupling in your code. That's a good thing.
Your code may also be easier to test this way.
Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.
You could then specify an interface ICollection with the methods add(), remove() and contains().
Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.
In .Net, I create base classes and inherit from them when the classes are somehow related. For example, base class Person could be inherited by Employee and Customer. Person might have common properties like address fields, name, telephone, and so forth. Employee might have its own department property. Customer has other exclusive properties.
Since a class can only inherit from one other class in .Net, I use interfaces for additional shared functionality. Sometimes interfaces are shared by classes that are otherwise unrelated. Using an interface creates a contract that developers will know is shared by all of the other classes implementing it. I also forces those classes to implement all of its members.
In C# interfaces are also extremely useful for allowing polymorphism for classes that do not share the same base classes. Meaning, since we cannot have multiple inheritance you can use interfaces to allow different types to be used. It's also a way to allow you to expose private members for use without reflection (explicit implementation), so it can be a good way to implement functionality while keeping your object model clean.
For example:
public interface IExample
{
void Foo();
}
public class Example : IExample
{
// explicit implementation syntax
void IExample.Foo() { ... }
}
/* Usage */
Example e = new Example();
e.Foo(); // error, Foo does not exist
((IExample)e).Foo(); // success
I think you need to get a good understand of design patterns so see there power.
Check out
Head First Design Patterns