Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Question What's the point in interfaces?

    I've always been told and read that interfaces are good because they separate the implementation from the implementation of a class. Also I've been told the it means the client does not have to know about the implementation class when they use the service, and that if a new implementation of a interface is required then creating a new class which implements the interface is relatively straight forward. I've also been told that using interfaces makes more productive. Personally, I think this dosn't stand up to closer investigation.

    Not knowing about the implementation
    When you use any class you don't have to know about the implementation. In fact you can use any class just like it is an interface. The only difference is how you construct it. Which implies that you do you have to know about the implementation.

    List mylist = new ArrayList(); // Oh dear – I know I'm using an ArrayList implementation

    Simplifies Maintenance and Development
    Using interfaces complicates development and maintenance. Firstly there is another file that needs maintaining and that the developer has to write. How many of you have defined a service interface to a persistence layer (for example), and then spent ages adding a method to the interface and then adding a method to the implementation class. Just use the implementation class and forget the interface and save yourself a bunch of time.

    Easy to provide different implementations of the same interface.
    This if often touted as being a good reason for using interfaces, but what is so difficult about overriding methods in a parent class in a new child class? You can still declare a variable to the parent class but instantiate the new child class. This seems for effective than using interfaces, particularly as 9 times out of 10 you probably need some functionality provided by the alternative implementation of the interface.

    This is what happens in the java.utils.* classes where there are a bunch of abstract classes to provide base functionality to concrete classes. Why have AbstractList implementing List? Simplify it – drop the List interface and replace it with a abstract class called List.

    New Problems Introduced by Interfaces:
    Where do you document? If you just documents the interface than that leaves the implementation class undocumented which may be a good thing. If you find you have to document the implementation class because, or example, it's implementation offers some benefit over other implementations (for example the various pros and cons of different sort algorithms), then the client has to know about the implementation class which undermines the whole “you don't have to know about this” argument.

    If you document both the interface and the implementation then you have twice the maintiance, and you are suggesting that the API user has to know about both. Again, undermining the whole “you don't have to know about this” view.

    Benefit Of Interfaces
    The only benefit I can see of using interfaces is to get around the (quite right) restriction on multiple inheritance.
    Cloneable c = new ArrayList();
    List l = new ArrayList();
    Cloneable c = new ArrayList();
    But it's difficult to find why this justifies using interface rather than child classes with default implementations or implementations that throw an UnsupportedOperationException.

    After all that's all the Cloneable interface does – it provides no methods. The clone() method on Object throws a CloneNotSupportedException and if you provide an implementation in a child class then you implement the Cloneable exception to show that you wont throw the CloneNotSupportedException exception. Great! Why not have a canClone() method with a default return of false:

    AClass aObject = new AClass();
    if(aObject instanceof Cloneable)
    AClass clone = aObject.clone();

    vs

    if(aObject.canClone())
    AClass cone = aObject.clone();

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Suppose you have a bunch of classes that make use of a bunch of my classes (I am supposed to be a service provider). The moment I change something in my classes you have to recompile your classes too.

    Now suppose I give you a bunch of interfaces, telling what my classes (implementation of the interfaces) do. When I change my classes (but still obey to the 'contract' of the interfaces) there's nothing you have to do, i.e. you don't have to recompile anything.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Still no point in interfaces

    If I have a bunch of classes that use your classes and you change your classes then I only have to recompile if you change the method signature of your classes (assuming I'm importing your jar), and that is the same even if you give me a bunch of interfaces to code to – if you change in implementation then OK, if you change the signature that I depend on then not OK.

    So what's the point in interfaces?

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,001
    Rep Power
    10

    Default

    ...what's your point? I'm calling troll.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Jeeni101 View Post
    If I have a bunch of classes that use your classes and you change your classes then I only have to recompile if you change the method signature of your classes (assuming I'm importing your jar), and that is the same even if you give me a bunch of interfaces to code to – if you change in implementation then OK, if you change the signature that I depend on then not OK.

    So what's the point in interfaces?
    Sure, if you change the interfaces (almost) all bets are off. But we all have tro rely on something, don't we? Give us a better mechanism and we are all ears, or do you just want to stirr up some things?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Jeeni101 View Post
    So what's the point in interfaces?
    If you want to play devil's advocate you can say that almost everything is syntactic sugar including interfaces when you get down to brass tacks -- they are completely unnecessary as one can create amazing complex and full-featured programs using Turing tarpits such as BrainFuck if they wanted to, but it would be extremely difficult to do so. Interfaces allow for a reduction of complexity which I think is best exemplified by their use in design patterns. To the OP, read a book on design patterns such as Head First Design Patterns or the GOF book to see the true beauty of interfaces.

  7. #7
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,001
    Rep Power
    10

    Default

    Real programmers use only abacuses to get the job done. Anything else is just cheating.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Whats the point in what's the point of interfaces

    If I have a bunch of classes that use your classes and you change your classes then I only have to recompile if you change the method signature of your classes (assuming I'm importing your jar), and that is the same even if you give me a bunch of interfaces to code to – if you change in implementation then OK, if you change the signature that I depend on then not OK.

    So what's the point in interfaces?

    So why did I start this thread? I've been developing in Java for about 15 years, and there's a lot of stuff written about how programs should be structured and how code should be designed, and there's frameworks for this frameworks for that, even frameworks for frameworks. And recently I've been wondering why?

    What's so terrible about JSPs that you need JavaServerFaces? What's so bad about response.sendRedirect(request.getContextPath() + "/somepage.jsp"); that you need Struts or Spring?

    Any front-end developer will understand HTML, Javascript and css, so why is there any need for GWT. Why is using a scriptlet <%= “Hello World” %> so bad that you need tablibs?

    I don't think it is. I've worked on loads of projects where the dogma is about using interfaces, frameworks, service locator classes, etc, and all it does is make the code hard to maintain because its so full of framework and infrastructure code that its a major job to change anything. And this is true for almost all the places I have worked including Oracle, IBM, Hewlett Packard, and a bunch of other big tech houses.

    So anywayz I've started a company myself and started cutting my own code, which included using all the frameworks etc, but then after a few iterations I decided to cut it all out. After which productivity increased by about 600%. I've just completed a massive change that effected all areas of the code stack and it took about 3 days rather than 3 months.

    So that's why I wanted to write this post. I wanted to know if I'd gone mad, or are there other people out there who also feel that frameworks etc get in the way of writing normal simple compact maintainable code.

    I chose interfaces because they go to the core of the issue.

    So anyway, I'm coming to the conclusion that if you want to be productive, write code that is easy to maintain and adaptable, don't use frameworks, don't use teirs - just use common sense!!

    thanks
    Jeeni101

  9. #9
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Just a quick note

    I've read GOF design patterns and Core J2EE design patterns and all that they say makes sense. When you come away from reading the book then its a case of 'doing it correctly' for your next project.

    The problem is that if you do you code will be unmaintainable. For example, just to doing something simple like writing customer name and address to a DB, you have a Chain of responsibility to pick up all the validation that might be required, a Command pattern for business processing, possibly a Facade for getting between layers, a proxy for accessing external services (zip code lookup), a Front Controller, possibly a Dispatcher, a Service Locator possibly a Composite Entity, a Data Access Object, and then a buch of stuff for navigation and error handeling.

    Alternatively you could have (pardon ignoring error checking):

    // Servlet Class
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    Customer cust = new Customer();
    cust.setAddress(request.getParameter("address"));
    cust.setId(request.getParameter("dbid"));
    cust.setEmail(request.getParameter("email"));
    cust.setHomePhone(request.getParameter("home"));
    cust.setMobile(request.getParameter("mobile"));
    cust.setName(request.getParameter("name"));
    cust.setWorkPhone(request.getParameter("work"));

    Validator.validate(cust);

    EntityManager em = OracleUtil.getEntityManager();
    em.getTransaction().begin();
    if(cust.getId() == null){
    cust.setId(IDCreator.createId());
    em.persist(cust);
    } else {
    em.merge(cust);
    }
    em.getTransaction().commit();
    em.close();
    response.sendRedirect(request.getContextPath() + "/nextPage.jsp");
    }


    Job done. No messing about. No frameworks. Just easy to understand clean code. And straight from servlet to database.

    ....Sorry to go on. This is developing into quite a passion.

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by KevinWorkman View Post
    Real programmers use only abacuses to get the job done. Anything else is just cheating.
    An abacus? Pure luxury! What's wrong with our own toes? Hm?

    kindest regards

    Jos ;-)
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    I've noticed that there is a tendency to "OO things to death". I don't know why this happens. There is definitely a place for interfaces. Consider, plugins. This is a situation where only the interface is known a priori, yet a class must load and run without recompile and without even a restart. You could envision a world where 'pure abstract' classes are used for this purpose, but then you've just envisioned a world of interfaces with a different name.

    Consider also interfaces such as 'ActionListener'. Sure, you could have a base class ActionListener that has an empty 'actionPerformed' method that subclasses would have to override to get interesting behavior, but since the base class does nothing interesting in that example, and since failure to override 'actionPerformed' is almost always an error, doesn't it make sense to enforce that override at compile time?

    Consider also situations where the base class doesn't do what you want. If you have an API geared around that base class rather than a base interface, users of your API are in a take it or leave it position for the entire API. I've run into this with JFileChooser. Because it's geared around classes (either a File or a FileSystemView), it's difficult to use it for anything but a mountable file system. So if you want to use it in a client/server arrangement to viw and select files on a remote file system, it's painful. If you wanted to use it as a hierarchical record selector for something that isn't a file system at all, it'd be easier to start from scratch. But all they needed to do was base JFileChooser on something more abstract - let's call it a JChooser - and implementing a file version of that would not be much more effort than designing it the way it was done - all around concrete classes.

    But I'll say this. If you don't like interfaces and can find no good use for them, then don't use them. You'll either discover you were right, or you'll find yourself cutting and pasting code (which then all has to be maintained) because you couldn't have the inheritance tree you really needed.

  12. #12
    snotmare is offline Member
    Join Date
    Apr 2011
    Posts
    34
    Rep Power
    0

    Default

    Jeeni101, can you imagine if Collections.sort() only accepted ArrayList<T> instead of List<T>?

  13. #13
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Thanks all for the replys

    So I think I'm most convinced by the ActionListener argument. However, I cant help feeling that that's a special case. Most services and interface usage is of the sort where an interface is provided to be used as-is such as List. In this case I think it just leads to bloat.

    The ActionListener situation is where someone has said “I'm going to provide a service and I'll do that by calling methodXYZ(ABC abc) on instances of class Class123. So if you want to make use of that service you better implement that method”. Then it makes sense to provide that method as an interface (or abstract class).

    So in the ActionListener case the person who implements the interface is the service user, while in the first case the person who implements the interface is the service provider.

    And I think that's the crux of it. If you're providing an implementation of a service then just use a class. If you want a 3rd party to implement the service then provide the interface.

    Thanks again everyone for helping me through this.
    :)

  14. #14
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Funny old world... after 10 years C/C++ and 10 years Java programming, I'm convinced application design should deal solely with interfaces - classes are just an implementation detail ;)

    It's the total polymorphic freedom it gives you, with MI, mixins, shallower inheritance trees, etc. Just before I left work, we spent 6 months totally reworking our system to use interfaces throughout, with massive gains in flexibility, maintainability, simplicity, and reliability, and a considerable reduction in code duplication due to greater code reuse.
    Last edited by dlorde; 04-28-2011 at 05:14 PM.

  15. #15
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Still Not Convinced

    How can you gain flexibility, maintainability, simplicity by having an extra file to deal with?

    Polymorphism comes from inheritance not from interfaces. Why not use abstract classes instead. Much more flexible - allows you to extend functionality as well as multiple implemtations of the same contract.

    If you implement an interface for accessing a oracle db, then you want to access a mysql db, you have to write the getEntityManager() in both classes, or bring it out into a seperate service class etc. If using abstract classes then you only need to override the setPersistentUnit(String name) method.

    Also with and inheritance and interfaces you get parallel implementation classes. Just look at the java.util.List interface (Collection > List) mirrors (AbstractCollection > AbstractList)

    Why not get rid of the List interface and rename AbstractList 'List'. Look at the inheritance of AttributeList and you'll see a parallel implmentation tree mapping to those interfaces.

    Also where are you putting your documentation? On the interface or the implementation class?

    I'm convinced interfaces have a place (call-back methods, and to have multiple inheritance), but both these only stand up to reason in few cases – not in Lists, but maybe for Serializable and Cloneable, but these just tagging interfaces rather than specification of service.

    :)

  16. #16
    snotmare is offline Member
    Join Date
    Apr 2011
    Posts
    34
    Rep Power
    0

    Default

    There are several good reasons, but they can be best understood in light of a large framework rather than simple one-off classes. You might check out a book from Joshua Bloch's, "Effective Java - Second Edition". I'd highly recommend it for any serious java programmer. Chapter 4 (item 18) provides some very strong reasons for using interfaces.

  17. #17
    Jeeni101 is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default That argument still does not stack up and here's why...

    You have an interface for Singer, then you write an implementation SingerImpl. Now you do an interface for SongWriter and a implementation SongWriterImpl. Great! So now you want an SingerSongWriter so you create a third class (or maybe interface – in the book they suggest a class). So now you have a third class called SingerSongwriter that has to implement both the methods of the Singer interface and the Songwriter interface. Which is rubbish because you've already implemented them in the other implementation classes!

    So now you have two implementations of the two interfaces, and a total of 5 files to maintain.

    So how about this: A Singer class, a Songwriter class and a SingerSongWriter class which is a wrapper for the Singer and Songwriter instances when you want to use them. Admittedly you have to use the concrete class type but you do only have 3 files to maintain, which is an increase of 40% in productivity. Which, in real terms, translates to a 3 day week!

  18. #18
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    If singer songwriters are going to elements of collections declared as collections of singers (or used as arguments to methods that work on singers generally) then shouldn't they share a supertype with singers? Ditto when considered as songwriters.

    Implementations are a nice way of expressing that supertype.

    (And giving it a visibility and actual availability as byte code, separate from that of one or another specific implementation.)

    No-one can pretend that this is the only way of doing things. Eg, there's no reason why methods couldn't just invoke methods on their arguments with confidence that the programmer knows what he's doing. But having such supertypes is Java's way of implementing computation. Like any implementation you choose it if it's suitable. And choose another if it's not.

    How can you gain flexibility, maintainability, simplicity by having an extra file to deal with?

    This line of thinking has been repeated in the last couple of the OP's posts. "Flexibility" ought to be self evident. Things with many parts are simply more flexible: they have the functionality of each part separately as well as whatever functionality can be encoded into their arrangement.

    Flexibility seen this way is a trade off with simplicity. Or at least a certain sort of simplicity. Has anybody trotted out the Einstein quote? "Make everything as simple as possible, but not simpler."

    The qualification "as simple as possible" suggests that simplicity be considered in the context of some broader aim. That is, it should be spelled out as "as simple as will still enable us to..." followed by some broader aim necessitating a degree of flexibility.

    I think that broader aim is maintainability: correcting the program's bugs and extending its functionality to meet unforseen needs.

    ----------------

    When I referred to "a certain sort of simplicity" I was thinking that massively multipart objects come in two flavours: you have your Rube Goldberg machines ("Heath Robinson" in my locale), and you have those stylish pieces of beautiful Italian engineering. (A large?) Part of the difference lies in hiding the complexity of the multiple parts. (or, for the cartoonist, exposing them).

    There may be massive complexity but if your aim is to fix bugs and extend functionality you might be only interested in looking at the machine at a certain level. A well engineered machine includes elements that hide underlying implementation and thereby allow you to access the machine's implementation at the level you want. The "effective" complexity of the machine is reduced by adding those extra parts!

    Such are interfaces.

  19. #19
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by Jeeni101 View Post
    How can you gain flexibility, maintainability, simplicity by having an extra file to deal with?
    Greater modularity, separation of contract and implementation. There's no doubt that modern software development techniques and idioms benefit hugely from a sophisticated IDE - our own project refactoring wouldn't have been possible without IDE refactoring tools - handling extra files simply isn't an issue with modern IDEs.

    Polymorphism comes from inheritance not from interfaces. Why not use abstract classes instead. Much more flexible - allows you to extend functionality as well as multiple implemtations of the same contract.
    Well, interfaces provide the contract, abstract classes the implementation of that contract. I'm not saying don't use abstract classes, but the contract is what code relies on. One major reason we switched to interfaces was for ease of testing - using interfaces throughout allows you to fully test any part of your application in isolation, down to the unit level, using mock objects and dependency injection. Unit testing during development is so much easier. IOC and dependency injection can be extremely useful in configuring the live application too. I don't see how one can easily do these things with abstract classes - it was a major reason for our system refactoring.

    If you implement an interface for accessing a oracle db, then you want to access a mysql db, you have to write the getEntityManager() in both classes, or bring it out into a seperate service class etc. If using abstract classes then you only need to override the setPersistentUnit(String name) method.
    With interfaces the service consumer code writes to the service provider contract, the interface. How the service will be provided is not a concern - abstract classes, dependency injection, whatever - there's an extra level of abstraction/flexibility over restricting yourself to abstract classes. Naturally some code has to be written to implement the service, whichever way you go.

    Also with and inheritance and interfaces you get parallel implementation classes. Just look at the java.util.List interface (Collection > List) mirrors (AbstractCollection > AbstractList)

    Why not get rid of the List interface and rename AbstractList 'List'. Look at the inheritance of AttributeList and you'll see a parallel implmentation tree mapping to those interfaces.
    I wouldn't necessarily take the SDK as an exemplar of good design, and they have been constrained to backwards compatibility and consequently have ended up with huge, clunky, monolithic APIs, but, in principle, when I write code to use a List, I prefer to have the choice to use an alternative implementation (e.g. a trivial mock object) to those in AbstractCollection and AbstractList. Those abstract classes are Sun's (Oracle's) suggested implementations, I'd like the option to go elsewhere (in the case of those particular APIs, their top-heavy design makes that unlikely, but the principle remains). If I code to a generic List interface, I can handle anything that implements it.

    Also where are you putting your documentation? On the interface or the implementation class?
    The contract documentation goes in the interface. Implementation-specific documentation goes in the implementation. Ideally, service consumer code only needs the contract documentation.

    I'm convinced interfaces have a place (call-back methods, and to have multiple inheritance), but both these only stand up to reason in few cases – not in Lists, but maybe for Serializable and Cloneable, but these just tagging interfaces rather than specification of service.
    Likewise, I'm convinced abstract classes have a place, but in the implementation of a service, not its specification.

    Incidentally, I think Java's Cloneable is a horrible mess ;)

  20. #20
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by Jeeni101 View Post
    You have an interface for Singer, then you write an implementation SingerImpl. Now you do an interface for SongWriter and a implementation SongWriterImpl. Great! So now you want an SingerSongWriter so you create a third class (or maybe interface – in the book they suggest a class). So now you have a third class called SingerSongwriter that has to implement both the methods of the Singer interface and the Songwriter interface. Which is rubbish because you've already implemented them in the other implementation classes!
    If you have SingerImpl and SongWriterImpl, you just instantiate them in your SingerSongwriter and forward the Singer and SongWriter methods to those internal instances. Modern IDEs can do all that for you if the APIs are large and you're pushed for time.

    So now you have two implementations of the two interfaces, and a total of 5 files to maintain.
    You can re-use the existing implementations, and the interfaces should be the least volatile code (ideally never changing).

Page 1 of 2 12 LastLast

Similar Threads

  1. Interfaces
    By blug in forum New To Java
    Replies: 3
    Last Post: 03-08-2011, 05:01 AM
  2. What is the point of Interfaces?
    By minime12358 in forum New To Java
    Replies: 9
    Last Post: 09-02-2010, 03:24 PM
  3. Interfaces
    By jon80 in forum New To Java
    Replies: 2
    Last Post: 05-03-2008, 10:57 PM
  4. Interfaces
    By imran_khan in forum New To Java
    Replies: 5
    Last Post: 07-30-2007, 09:11 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •