Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have been programming for many years but I am still not comfortable with the concept of "Interfaces". I try to use interfaces but many times I don't see a mandatory use for it. I think this is probably because the projects weren't so big, or because interfaces are more useful when teamwork is involved.

So, making another attempt to understand the importance of interfaces, here is my question:

What problems will I face if I remove the concept of interfaces from my code?

share|improve this question
4  
What is it that makes you feel uncomfortable with interfaces? What programming language are you using? –  Paulo Madeira Dec 15 '12 at 15:49
1  
what happened when you tried to remove it? –  gnat Dec 15 '12 at 16:52
    
@Paulo Madeira : I am not uncomfortable with anything. But i think, that interface has always been hard for me to understand. I am using AS3.0 –  Vishwas Gagrani Dec 15 '12 at 17:46
1  
Vishwas your question was edited by a regular user, not by a moderator (we have diamonds next to our usernames), every post on Stack Exchange can be edited by everyone. I've reviewed @Dynamic's edits, and I find nothing wrong there. The first version of your question and what you are alluding to in your comment is not a question that is on topic on Programmers, open ended questions and/or hypotheticals is not what the site is about. –  Yannis Rizos Dec 16 '12 at 13:50
1  
@RossPatterson Nice catch, I've added that back to the question. –  Yannis Rizos Dec 16 '12 at 15:28
show 3 more comments

7 Answers

up vote 0 down vote accepted

Short answer: As result, your classes will have both unhealthy high headcount and very high method count. (look at early UI libraries, they are loaded with classes with, say 100 methods - ugly)

Interfaces are nice compact (usually 0-5 methods) purely abstract classes. They are easy to inherit by any class in any place, in hierarchies of any size. The sole purpose of interfaces is multiple inheritance, but without evil parts of multiple inherictance. Interfaces naturally bring good compression to badly bloated piles of classes.

Removing interfaces will disallow multiple inheritance from purely abstract classes. The remaining classes, instead of being multirooted shallow and compact hive, will form forest of trees of inheritances. Over time, with refactorings, forest will tend to collapse to single super tree with root "Object" class. The tree will be no more pretty. It will have lengthy root with many unnecessary abstract classes close to root and wide crown of nearly identical leaf classes, where it is hard to tell one class from another. Simple functions introduced at root classes will have too much of impact on everything and make the code unmaintainable, unlearnable, overfunctional and useless. Every special treatment of common methods will require specialization tricks, like "reintroduce".

There will be unnecessary visibility for overly public methods. Lot of dead methods, which are needed to stay near root classes, but making no sense for most of leaf classes. At some point the pile will reach the size, complexity and amount of inner conflicts, when there will be no more possible to bring change, fix or improvement without breaking something somewhere.

share|improve this answer
4  
"The sole purpose of interfaces is multiple inheritance", that's so wrong. The greatest purpose is to declare an object's capability, the messages it can handle. It doesn't really matter if the interface is "inherited", it matters if it's implemented. It doesn't really matter if the object "inherits" multiple interfaces, it matters which it implements. What does an object inherit from an interface? Only its contract. So, if a language says you inherit an interface, it's simply that language's way of using interfaces. –  Paulo Madeira Dec 16 '12 at 16:26
1  
The other problems you mention, composition and delegation have been used to work around heavy inheritance. Those problems only happen when you rely solely on inheritance. Interfaces are a natural consequence, in strongly typed languages, an object can be a polymorphic proxy or decorator, no matter its class hierarchy. In C++, there's multiple inheritance, and "interfaces" are pure abstract classes, only a special case of multiple inheritance. Certainly not the only language with multiple inheritance other than for interfaces, Common Lisp's mixins, for instance, and it doesn't have interfaces. –  Paulo Madeira Dec 16 '12 at 16:29
1  
Interfaces (whether by the "interface" keyword or not) are about software which can be easily extended. New implementations can plug-in if they conform to the interface. Avoiding the "diamond" multiple inheritance problem is just an orthogonal language specific issue and not the purpose of interfaces at all. Let alone the sole purpose. –  mike30 Dec 17 '12 at 15:14
    
@Paulo Thank you for comment. You are confusing "to implement" and "to inherit". I chose the word inherit, and there may be other words in different OOP languages. But the word "implement" would be exactly wrong. –  user7071 Dec 18 '12 at 5:09
    
@RocketSurgeon, how so? What would be the use of an interface in a strongly typed language if it could be inherited but not implemented (except for abstract classes)? What value would the language offer me by allowing a dynamic cast from an object to a specific interface, if the interface is not (fully?) implemented? –  Paulo Madeira Dec 18 '12 at 23:50
show 3 more comments

An interface is very useful to hide implementation details. E.g. there might be a logging-class. It is not necessary to know how the logging is managed, the log messages may saved in a text file or in a database. All logging-implementations might implement this interace:

public interface Logging {
void log(String message, int level)
}

If you use the interface (and get the implementation via a fabric or dependency injection) you don't depend on a certain implementation, which might change over time. And you are available to change the implementation without any changes in the code.

share|improve this answer
5  
@chao - That is still an interface. That people think that the design concept of an interface needs the language keyword of interface is one of the great common failings. –  Telastyn Dec 15 '12 at 15:35
1  
@cHao, multiple interfaces can be implemented in Java and C#, but only one class, abstract or not, may be inherited. In C++, we call interface to an abtract class with only public pure virtual methods. In languages that are more function-oriented (e.g. Common Lisp), we call interface to a set of methods that must be specialized. In general, you cannot decouple actual implementation without interfaces, having just an abstract or partially implemented class already tightly couples you to that partial implementation and probably its details. –  Paulo Madeira Dec 15 '12 at 15:39
1  
@cHao, at a language level, that might be true. But if you're given documentation (technical, specs, etc.), you ought to be glad someone described what methods an object you may implement from scrach should respond to. That's an interface. –  Paulo Madeira Dec 15 '12 at 15:48
2  
@cHao, I believe this should continue on a chat, but "interface", to me, is a concept above the support of particular programming languages. If it sounds like a dirty hack in JS it's because it doesn't provide a notion of interface by itself. Is a function typedef in C a dirty hack? I think it's a step towards callback/struct-methods interface. But I digress, I'm not defending JS or any other language, just the concept of interface and what you might miss by not using it. In fact, this question doesn't have a language tag, so... –  Paulo Madeira Dec 15 '12 at 16:26
1  
@cHao, I don't consider every method (part of) an interface. In fact, I have for myself that "interface" works the other way around: from design to implementation. But let's agree to disagree, then, this is no longer about abstract classes or the answer. –  Paulo Madeira Dec 15 '12 at 21:38
show 10 more comments

I was in the same boat as you for the first couple of years of my programming career. I managed to get on fine without creating my own interfaces. You cant really remove the concept entirely however as using most libraries will involve consuming interfaces.

I would strongly recommend spending the time to research what they are and some basic use cases. You will miss out on a lot of powerful tools such as dependency injection if you don't learn how to use them. It will also make your code more decoupled and simpler to change if you rely on interfaces rather than concrete types.

share|improve this answer
add comment

If you don't understand what interfaces offer then you don't understand interfaces. So you probably won't loose much if you stop using them because it is apparent you don't use them to their fullest potential.

The three major things I would miss would be

  1. Multiple inheritance. If I inherit from a base class in a framework to get the plumbing benefits how does the class easily tell the world it can do x? Interfaces.
  2. Related to #1 is that I can define the behavior of the application in a component that has no dependency on anything. You can do this with abstract classes to a point but you can run into problems pretty quick if you work with third parties, other divisions or even legacy code.
  3. Those two things make testing new classes that rely on interfaces so much easier.

If you don't understand those three benefits (and there are others) then you either work with a language that allows true multiple inheritance and accept the problems that introduces, use scripting languages that are much more flexible or you simply do not understand what interfaces represent.

share|improve this answer
add comment

Removing interfaces from your code, whether they're done explicitly (e.g., Java's interface construct) or implicitly (e.g., a C++ abstract class), removes your ability to take advantage of some forms of inheritance. (I say "some forms" because in general terms, interfaces are equivalent to abstract classes but are treated differently by different languages.)

Take this example, written in no particular language:

class Juice { ... };  // Represents any kind of juice.

interface Fruit {
    Boolean is_edible();
    Juice   make_juice();
};

class Apple implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}

class Banana implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}


// Processes and accumulates the juices of many fruits.
class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process(Fruit f) {
      if ( ! f.is_edible() ) throw_exception;
      accumulated_juice.add(f.make_juice());
    }
}

This is pretty straightforward. The Juicer can process() any Fruit you hand it because the interface guarantees that:

  • There's an is_edible() method determine if the Fruit is edible
  • There's a make_juice() method to produce the juice

You can develop a Kumquat or a Mango or a StarFruit and you'll never have to modify the Juicer to understand them. Juice is juice.

If you remove interfaces, all of that simplicity goes away:

// Assume same class declarations as above without "implements xxx" clause.

class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process_apple(Apple a) {
        if ( ! a.is_edible() ) throw_exception;
        accumulated_juice.add(a.make_juice());
    }
    Void process_banana(Banana b) {
        if ( ! b.is_edible() ) throw_exception;
        accumulated_juice.add(b.make_juice());
    }
    // Add methods for additional fruits here.
}

All of the process_xxx() methods are identical except for what type they take as an argument. Even though Apple and Banana have methods called is_edible() and make_juice() with identical signatures, the language won't just let you call them by name because they're part of different classes. This means your Juicer has to have more code added every time you develop a new fruit.

Once this grows to more than these few classes, it becomes a maintenance nightmare if you need to make changes to how the process() method works internally. Further, any other code that handles your fruits has to have all of this additional code

HTH.

share|improve this answer
4  
"Removing interfaces from your code (...) removes your ability to take advantage of inheritance", I don't agree with this sentence. It removes your ability to decouple from actual implementation. If you don't use interfaces, you may still benefit from inheritance, e.g. Fruit may be a class every fruit must inherit from, perhaps because of inner implementation details that only fruit have (a thing that an interface doesn't state: implementation details). BTW, in the first example, Juice should probably be an interface too. Otherwise, good answer. –  Paulo Madeira Dec 15 '12 at 17:54
    
Thanks for the answer. Actually I get this answer ( About referring instances with a common Class name, here: Fruit ) in most the books. But in AS3.0 I can also use use Object class to fill in any instance of any class I want to. Alternatively, i can also make an array of different classes to call a function one by one. For example fruitArray[0].isEdible(), fruitArray[1].makeJuice() etc. –  Vishwas Gagrani Dec 15 '12 at 18:03
    
@PauloMadeira: Terminology is difficult to nail down because different languages treat interfaces differently. I'll see if I can clarify the language a bit. I left Juice as a class to keep the example simple. –  Blrfl Dec 16 '12 at 13:03
    
@VishwasGagrani: You didn't mention ActionScript initially, and I can't really speak for what kind of shenanigans it allows with its objects. What you propose won't work in a very-strongly-typed language because Object isn't going to have the methods Fruit defines, and you'd still have to figure out how to cast it into one of the individual types (Apple, Banana, etc.) to run their specific methods. –  Blrfl Dec 16 '12 at 13:08
add comment

What problems will I face if I remove the concept of interfaces from my code?

What you will get is the tight coupling of your system. As the saying goes "In pursuit of code quality: Beware the tight couple!"

What is tight coupled software system?

You probably have at least heard the term coupling used in the context of object-oriented programming. Coupling refers to the interrelationship(s) of components (or objects) in an application. A loosely coupled application is more modularized than a tightly coupled one. Its components rely on interfaces and abstract classes as opposed to concrete ones, as they would in a tightly coupled system. In a loosely coupled system, components are interrelated using abstractions instead of implementations.

A common schema of tightly coupled software system (GUI and DB without abstraction layer in between)

enter image description here

The GUI's dependence on an implementation rather than an abstraction limits the system. You cannot operate the GUI without having the database up and running. This design doesn't seem so bad from a functional standpoint -- we've been writing apps like this for years and planes aren't falling out of the sky, after all -- but testing it is another story.

OK, how to tight coupling? - will Interfaces do the trick? - Turn the coupling to be loose!

enter image description here

The GUI in above software system relies on an abstraction - a data access object or DAO. The DAO's implementation is directly dependent on the database, but the GUI itself is not entangled. Adding an abstraction in the form of a DAO decouples the database implementation from the GUI implementation. In place of the database, an interface is now coupled to the GUI code.

In conclusion - One thing developers have come to agree on is that well-written code is maintainable, and the Dependency Inversion Principle is a sure way to design for maintainability. Dependency inversion stresses reliance on abstractions over implementations, which creates a great deal of flexibility within a code base. Applying this technique with the help of a DAO, ensures that not only will you be able to modify your code base when you need to, but so will other developers.

share|improve this answer
add comment

If you're not seeing a need for interfaces, then they may not be necessary. I would say, don't create an interface until you have a good reason to do so. (This goes under the principal of every character of your code having a purpose.)

I've done a lot of work in the Java world. Interfaces are all over. There are several reasons for these interfaces including

  • Some libraries requires interfaces e.g. if you want to create a dynamic proxy, you have to use interfaces to define types
  • Implementation hiding - this is the classic reason
  • "Because we may need it later" - not necessary and maybe a waste of developer time
  • "Because somebody told me that I should create interfaces" - not a good reason
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.