Skip to main content

Is it just me or are interfaces overused?


Ok, I may resort to a tad ranting here, so let me apologize in advance, but I'm really curious if others find this pattern annoying too (and I wonder if it is a justifiable pattern)…



So, after just looking at a particular question , I noticed that almost all of the responses suggested creating an interface for injecting a mock in some test code.



I don't mind using interfaces, and sometimes they can really help in static typed languages like C# and Java… but I do mind seeing interfaces for almost every class in a system(or in general being used where they aren't really needed).



I have 2 major problems with using an interface when it isn't called for:



  • You abstract away where the implementation is coming from. This problem has a couple consequences… in an IDE, it means that when I try to browse to the source of this method being called… I get taken to an interface instead of some code that I can look at and see what is going on. This bothers me a lot, but also this is a real problem to me to hide where the implementation is coming from (sometimes it can be in non-obvious locations).

  • It adds ANOTHER file to the system. I tend to be a minimalist in my programming… if I don't really need another method, or another class, or even another file… not unless that extra thing is justified (flexibility that is going to be used, or makes the design cleaner, or provides some real benefit).



Now… if you are testing something, and you create an interface JUST TO ALLOW MOCKING… this seems to be adding a layer of minor headaches for no real benefit. What does creating the interface do that just overriding the class won't do? What is so bad about having a mock that merely overrides some methods of the single implementation class?



I guess it should be no surprise then that I much prefer Java's default virtual methods (ie requiring a final keyword to have a method that CAN'T be overriden) to C#'s default final methods… and I also tend to avoid the final keyword on methods and classes too.



So is there something to using interfaces that I am missing? Is there some hidden benefit of using an interface when you have 1 version of a class and no immediate need to create an interface?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. A big headache with interfaces in Java and C# is that they give you so few options to evolve your contract. E.g.:

    interface ILogSink {
    Log(DateTime timestamp, string message);
    }


    If you define this in a framework and have a lot of different external consumers that all implement this interface you cannot change it without breaking their implementation. If you need to change it in the next version, you end up with something like:

    interface ILogSinkVersion2 {
    Log(DateTime timestamp, string message, CultureInfo culture);
    }


    If you use a base class on the other hand, you can start out with:

    class LogSink {
    void Log(DateTime timestamp, string message);
    }


    And evolve it to:

    class LogSink {
    [Obsolete("Please Log(DateTime, string, CultureInfo)")]
    virtual void Log(DateTime timestamp, string message) {
    }

    virtual void Log(DateTime timestamp, string message, CultureInfo culture) {
    // Call old method for old implementations:
    Log(timestamp, message);
    }
    }


    This way you can evolve your code without forcing every implementation of the contract to consume your changes immediately.

    Update: This is not a big deal if you sit on your own island and own all your code. However if you maintain a framework interface like log4net's ILog interface or .NET frameworks IDisposable interface, you need a quite good reason to add or change methods, since it will affect a few thousand implementations throughout the world.

    ReplyDelete
  2. Interfaces are useful in order to add a level of abstraction early on in the design process. It will benefit the modularity of your code. If you have a big enough project (one that warrants using mocking) interfaces are useful, though for small projects this is most likely overkill. They can be used more than they need to be certainly, but if you take to heart the following guidelines you will know when to use inheritance and when to use an interface. Your code reusability and scalability will increase greatly when interfaces are used where appropriate!

    The old explanation of when to inherit works nicely:


    Is a - inheritance

    Your class is a subclass of a more generalized class, e.g. HouseCat inherits from Feline because a house cat "is a" feline.
    Has a - member field

    A LittleGirl
    has a cat, so obviously she should not
    be a subclass to HouseCat (she is not a cat). It is
    best that she "has a" HouseCat member field.

    class LittleGirl
    {
    int age;
    string name;
    HouseCat pet;
    }

    Performs - interface

    Interfaces should be used when a class or group of classes all have similar functionality, but when there is no obvious line of inheritance. Think of them as a certificate that says "this object performs this functionality."

    For example, a HouseCat might inherit from Feline, but implement the ICanHasCheeseburgers (or ICanHazChzbrgrsPlz) interface. That way you have a BurgerJoint class with a method public CheeseBurger Serve(ICanHasCheeseburgers patron) and be able to pass either Humans or HouseCats to the Serve method in order to feed them a Cheeseburger.

    This is useful because HouseCat does not inherit from Person nor vice versa. However, they both perform acts involving CheeseBurgers.


    ~ William Riley-Land

    ReplyDelete
  3. If you have one class I can understand your hesitation with interfaces. According to Robert Martin's book Agile Patterns and Practices (I believe that's the name of it). In the book he describes the Dependency Inversion Principle. I don't believe he invented it but he's who made it click for me.

    Basically the more you depend on interfaces the less fragile your software. This is an ideal though. I say break it where it makes sense. If you're not using interfaces more often than you are then there may be other problems. For example, just because you have different classes doesn't mean they should all have different interfaces. The interface segregation principle states that we should break up interfaces into the most reuseable atomic components possible.

    For example imagine having 100 different data access classes (each for a different kind of entity). They could have their own interfaces but what if they shared a common ICrud interface? Then you know each supports the basic CRUD methods. In this way you should be looking to add consistency and order through out your code... ideally. No one's perfect at it (and productive) but it's a good ideal to strive for.

    ReplyDelete
  4. Read about the open/closed principle. Depend upon abstractions, not details. If you're depending on a concrete class, you're depending on details and there's no opportunity to change just one of two or more coupled components, you must change them all.

    You say "JUST TO ALLOW MOCKING" as if it's a bad thing and then say that there's no real benefit. The benefit is in the decoupled design that allows me to use, for example,
    an Inversion of Control container that may have aspect-oriented programming features or support runtime dynamic code-composition, etc. By following these design principles, my options are always wide open. Being able to mock and perform interaction testing is one benefit I get and it happens to prove out the fact that my abstractions are aligned correctly according to the correct interaction boundaries.

    When the testing via mocks goes well, it's a canary in the mineshaft that tells me whether things are designed correctly. When the testing via mocks goes poorly, I have a problem and it's usually reflected in other areas of the application, too, not just the mocks (again with the canary analogy).

    Sure, sometimes you may not ever have an alternate implementation of ISomeFoo in which case it might have been a waste for that particular component. But if you ever DO need to have an alternate implementation, going and changing those 50 references to concrete PetrolSomeFoo to concrete HydrogenSomeFoo will hurt really bad, especially if someone of the changes involve other applications or integration scenarios.

    I totally do NOT follow you on the files-on-the-filesystem argument. That matters so little as to be a non-argument. If your design concerns number of files on the filesystem, you might have a problem :) Or, you know what, put the ISomeFoo inside the same file as your first concrete implementation. There, 1 file.

    Finally, your instinct that interfaces are smelly is not totally a bad one. But what is smelly is the statically-typed class-based languages like C#, Java, etc. that require strong interfaces (instead of, say, duck typing) in order to obtain the necessary abstraction to pull off the open/closed principle.

    If we had duck typing, you wouldn't need so many interfaces and this conversation would be moot.

    ReplyDelete
  5. I completelly AGREE WITH YOU!

    I stated this in my ansewer: http://stackoverflow.com/questions/90657/mocking-method-results#90687

    And I had to edit my answer twice to be clearer, because almost all answers suggested creating an interface to an UTILITY class. This kind of answer was even accepted. You should create an interface for testing purposes if it makes sense - which it does NOT in the context of the question.

    Creating an interface is not even the biggest problem. I think the worst is obligate a client class to inject the interface implementation when calling a simple operation. This will increase the complexity all code using that class. This is very bad. It's a hack! A BAD hack! Why is it bad?


    It's an Utility class. It's not likely to change implementation. So why even bother adding other layer of abstraction?!
    Was suggested over and over to inject the Utility class implementation in classes that uses it. Now code that looks like this: myClass.loadData() will look like this: myClass.loadData(new HelperImplementation()). NO!!
    +1 to all the points stated by Mike
    There are other - more elegant - ways.
    Must be other reasons why it's bad. :)

    ReplyDelete
  6. Ok, I just wanted to thank everyone for all the great responses (I added comments on most of them for what I felt on each individual one)! It seems there is a strong division of people who firmly believe interface overuse is a good thing, and those who are on my side of the fence of believing they are a sign of a problem (and an antipattern).

    Let me add 1 thing to all of you who seem to think creating an interface for just 1 class is a Good Thing:

    Consider a class that does nothing in the constructor, except maybe set some fields and invoke some protected methods (which could then be overridden in both a mock and an alternate version of the class that some client decides they want to create). Now, how does this differ from an interface, realistically? Both are equally flexible to the client, but the class has the added benefit of being less complex. Essentially, the class is now an interface that also happens to be a default implementation.

    If that clicks for you, you probably just realized why interfaces for 1 implementation bothers me so much.

    Note that I am not talking about multiple inheritance... there are times where it is quite useful to be multiple things... but I say don't ANTICIPATE it... it is most likely not going to be needed... instead factor out the interface later when you see you DO need it (most IDE's have an "extract interface" refactoring tool).

    There are 2 cases of interfaces being extremely useful that I can think of (off the top of my head) which I would jump on (and have) if I were going to implement such a thing:


    You have something that lends itself to a custom implementation... such as an Encoder type interface where there really is an obvious immediate need to have multiple options (most classes don't fall into this type of category in my experience).
    The class you are developing needs some kind of visitor pattern, where the code you are going to call may or may not need to be implemented by all clients... I'm talking about event callback sort of things, or higher order functions like map and reduce. (I guess this is kind of the same as option 1 now that I think on it more...)


    Anyways, I'm not trying to say NEVER use interfaces... I'm trying to say evaluate it in each individual case, and try to see if there is going to be real benefit in adding the complexity to your system (there is no point in incurring unnecessary cost, right?)... like all patterns, patterns can be overused and applied when they don't actually give you any benefit, and I really believe interfaces are an overused pattern.

    ReplyDelete
  7. Yes, I'm with you...

    ...but have always kept quiet about it.

    A few years back I took over a project that had zillions of single class implementations of a corresponding interface...in a closed system! (The API was never externally exposed.) More files, more code, more characters. WTF?

    It is one of those cases where people become obsessed with 'the rule' and lose pragmatism in their designs. (Like bureaucrats becoming obsessed with the bureaucracy rather then the purpose.)

    And then there is a class of coder who considers the most verbose code, the code using as many language features as possible, to be the most 'correct'.

    Interfaces have their place, but it's not everywhere. Very often XP's You Aren't Going to Need It principal applies.



    On a side note, I cannot stand interfaces prefixed with I (E.g.: IMyInterface). Can anyone say Hungarian Notation? (For the hair splitters, it is 'Systems Hungarian Notation', to be specific.) It is information that tooling can communicate, just like whether or not a variable has a local or member scope.

    ReplyDelete
  8. I have rarely seen interfaces "over-used" in my experiences, but it is certaintly possible.

    Knowing when to use:


    An interface
    Simple inheritence
    Abstract base class
    Interface AND an abstract base class
    Encapsulation/helper classes


    are keys to good designs. You can't learn enough about this, and we can't talk enough about it. We can talk about the "fringe" cases (all 300 classes in this library have interfaces), but I think that's a waste of time. We already know that "creating interfaces just to support unit testing" (or any other "just to support.." phrases you can think of) is not the right answer.

    Yet there are some simple rules (the "is-a" relationaship test comes to mind). There are also some obvious situations where interfaces are used (plug-in architectures, for example). I will offer this thought...

    Most piles of code in a library (think about the 300 classes mentioned above) have some public-facing interface that is significantly less large than "the entire code", and normally less large than what the library needs to support itself. Presenting this as a series of interfaces is what you want to be thinking about. Designing these interfaces requires a different train of thought than the code design - you are thinking about the consumption of your code, not the implementation of it.

    By including this thinking, and designing interfaces, you will most certaintly be rewarded in the later stages of development (assuming this is a reasonable large system with more than one developer).

    ReplyDelete
  9. I wanted to post one final response after a little more thinking. I'm preparing for the barrage of down votes I might get with this.

    I think this very issue shines a bright light on the issues that can arise with static typing. Notice I'm not saying strong typing, merely static. Really, all of this nonsense about interfaces is really just us TDD guys trying to be able to test each portion of our system in isolation. If we could duck type (signature based polymorphism) I guarantee you none of us would be rationalizing making those explicit interfaces.

    What TDD aficionados like myself are saying is in the language I am using I need to use interfaces to get the level of decoupling I am after. I'm saying I need that decoupling to have an actual unit test, to verify 99% absolutely ;) that I have done my job. I would honestly rather just be able to use duck typing and only explicitly define an interface when I expect it to be of some use. One of the reasons I enjoy JavaScript is the ease with which I can create a mock object that looks and behaves like the real thing (as far as the injected class is concerned).

    In closing allow me to summarize. I think the pain point isn't in either side's philosophy. One side is idealistic about how much decoupling they should be able to get and the other side is trying to deal with the practicality of applying such ideals in languages such as C# and Java. Both are good sides to be on. In the end, it comes down to understanding the limitations of your language and just making a judgement call on a case by case basis as to which side of the fence you'll choose to side with today.

    ReplyDelete
  10. For me an interface should only be created when there's someone, somewhere which doesn't really care about who is implementing it as long as it's being implemented.

    And that's the only place to use them, to define and agree on behaviour, any other use is probably misuse (some exception for particular cases allowed but generally speaking)

    ReplyDelete
  11. I find that in most cases interfaces are seriously underused.

    Using interfaces from the start allows you to divide behaviour and implementation.
    With complex applications this makes early programming a bit more complex but long term programming becomes a lot less complex.

    ReplyDelete
  12. The original edict to "code to interfaces" seems to come from the GOF "Design Patterns" book. The important thing to realize from this is the interface they are talking about is not the Interface keyword/concept as it is most often currently interpreted as. The interface as they are writing about is just the public interface as represented by some class be it abstract or otherwise.(Interface didn't exist yet when the book was published)

    Overriding some methods to provide your mock or stub is as a valid option as implementing an Interface to do the same. The trade-offs of inheriting from the class you're going to mock or via extracting and implementing an Interface are up to the details of the particular implementation.

    ReplyDelete
  13. "Another file to the system" objection is so 1980's. So what? I'd rather have 100 source files that are small, clean and easy to understand than 2-3 files that are huge and full of highly coupled code.

    The objections you present are superficial. What interfaces provide is a cleaner separation from a service and something that uses the service. If I want to know what time it is, I only need to look at the watch. I don't need to see all the little wheels and springs inside. And I don't really care if the watch is on my hand or it is a Big Ben: they both share a same interface.

    ReplyDelete
  14. (And to think I almost failed a Software Engineering exam because I had placed interfaces only on classes that required it, rather than everywhere...)

    ReplyDelete
  15. Bottom line, if the interface is simplifying the test and making the implementation more complex than it needs to be, I consider it bad design... I would rather add a bit of complexity to the test and keep my implementation clean.

    (ie, the interface should be simplifying the implementation, not the test).

    ReplyDelete
  16. When you are considering writing anything which is likely to be a shared resource across multiple projects, then in my opinion, you simply must use interfaces. I'll give you an example:

    Where I work (in a financial firm), we have an API which allows tradable product information to be accessed from any application:

    Product p = productService.lookup(ProductCodeType.TICKER, "MSFT");


    A decision was made that Product should be a class as opposed to an interface. Unfortunately, this has come to be a millstone around our necks. Why? Because Product is not quite as simple a class as it was first supposed to be.

    We have a number of implementations of the ProductService which offer various caching strategies, static or dynamic views of the product universe. But we cannot do some very useful things which we want to do with the Products themselves, for example, hydrating properties in a background thread, using proxies to collect statistics, eagerly fetch and hydrate their properties, etc.

    Had Product been an interface, we would have none of these restrictions. Interface is simply the mechanism the Java language designers used to "implement" the familiar design pattern.

    ReplyDelete
  17. Interfaces should be used with care - don't add too much abstraction when it is not necessary! The minimalistic approach is really good thing - it help for easier walk through the code after several months when nobody remembers the big interface hierarchy

    ReplyDelete
  18. You do not add the interface for allowing mocking. In reality, if you need to mock something, is because there is a dependency on an external component, and the interface is used to decoupling that dependence, which in return allows Mocking, but thats a consecuence of a better design, not a requirement for mocking.

    The problem with the question you link is this:


    I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?


    The user needs a deterministic result, so the only solutions are mock the helper, or just hardcode the value directly.

    On your concerns:

    If you try to brownse the code for an interface's implementation in your project you didt't code, chances are that you probably know beforehand what the implementation is (maybe because of a previouse debug trace), or that you IDE have an 'find all references' for that interface, or better utilities if you use third party plugins (an user said in this question that Resharper has a "go to inheritor' option) I don't think is a big deal.

    Adding a new file is good. Really. Separate all files and implementations in numerouses files is not a bad thing, because we have tools that take that bunch of files and organize it in a proper structured way: a project. Your real concern here is not adding a new file, but adding new simbols you need to care about ,IMHO, which add complexity to the project.

    ReplyDelete
  19. Basic rule of thumb: If you only have a single class implementing an interface, and if you can't think of another possible implementation of the interface, you don't need an interface, at least not now. You can always refactor and add an interface later, if required.
    I'd argue that you should not add interfaces because they are somehow required by your testing strategy. Unit tests are the most important tool developers have (in my opinion), but they should not force a particular design. Fix the test infrastructure if it forces interfaces on your design.

    ReplyDelete
  20. Well on a recent project, I took a plunge and used interfaces heavily. By that I mean that almost all the classes in the project implement at least one interface. Some implement 2 or more. But also the number of interfaces is far lower than the number of classes.

    The possibilities of this have shocked my socks off!

    Allow me to give an example. Two of the interfaces are Provider and Receiver.

    The first methods built were two classes. One was a SymbolManager as a Receiver of market symbols. The other was a FileProvider as a Provider which is reading financial data from a file and passes it to the SymbolManager. At first it felt cumbersome putting the methods both in the SymbolManager and the Receiver interface. Same for FileProvider.

    But the next requirement was to have multiple SymbolManagers each for a different "symbol" which is a financial instrument.

    And then the requirement was to feed data to them from a single "provider" which was a data broker. Well the data broker feeds many symbols so they need to be multiplexed to the proper SymbolManagers.

    So the ProviderService implements Provider and feeds data to multiple Receivers.

    Next users need to send this data remotely across a network so now a ReceiverStub implements a Receiver and marchals the data across TCP/IP with a ProviderProxy receiving and passing to a Receiver.

    Point is that more and more Receivers and Providers keep getting added AND it's very easy through configuration to connect them in various different ways.

    I'm shocked at how often we keep coming up with more Provider and Receiver ideas.

    The most power of all this, of course, is that when we add a new Provider or Receiver implementer, it can get connected to any other of the other existing objects just by injecting into the other object WITHOUT changing the older objects code.

    In fact, it helps me to think of Interfaces as an easy way to make software operate internally similar to a "plug-in" architecture where you can add functionality to older code without changing the older code in any way.

    It's nearly impossible to see the value of Interfaces until you get hit with a requirement later in a project or even after it's finished that you never accounted for when building it originally. If you made it loosely coupled you find it quick and easy to make the change usually. If not, it may be more painful and time consuming.

    We have even taken this to a literal plug-in architecture by allowing users to create their own implementers of interfaces that get dynamically loaded via reflection. In fact, the GUI dynamically finds all classes in their DLL that implement certain interfaces and let's them pick from the list.

    Now that I've built "loosely-coupled", pluggable architecture using interfaces, I can't imagine working the old way.

    ReplyDelete
  21. To be flexible, think "factories".

    If you define and use factory methods for object creation, it doesn't matter whether you're using a class or interface to the callers.

    Think about it for a minute...

    Suppose you start with a class:

    public class Foo {
    Foo() {...} // package-access
    }


    and define somewhere in the same package

    public Foo createFoo() { return new Foo(); }


    Users can write

    Foo foo = SomeFactory.createFoo();


    Later you decide it would be good to use an interface so you can have alternate implementations. So you change to

    public interface Foo {...}
    public class SomeFooImpl implements Foo {...}


    and change the factory method

    public Foo createFoo() { return new SomeFooImpl(); }


    This allows you to "have your cake and eat it too". The factory methods are a wee bit extra overhead, but give you flexibility later on down the pipe.

    OK, now the confession: I don't regularly do this, but I'm thinking about doing it more and more. Thought I'd throw the idea out there and see who it sticks to and starts digesting them until it grows into a big blob that only Steve McQueen can stop.

    ReplyDelete
  22. I would have added a comment....

    For Eclipse, highlight the method and hit Ctrl-T, this will bring up the hierarchy of implementations for a method which will allow you to go to the implementation with a single click. This is especially useful with a Spring/Hibernate driving application where you want to skip all the proxies and reflection classes in debug mode.

    On the broader topic of interfaces, I feel they're only needed when a factory of some sort is used, and preferably at component or application boundaries. A component that heavily uses interfaces internally and has a 1:1 interface:class ratio usually smacks of bad architecture or drinking the Spring Kool-Aid (essentially the same thing). Adding an interface for the sole purpose of Mocking is injecting test code into your production code and should be avoided at all costs.

    Lastly, you should note that you can extract interfaces out of a class with ease when needed with Eclipse (and probably most other major Java IDEs as well) although you might need to rename your file outside of Eclipse, refresh, and then do an extraction back to the original name. This process allows you to effectively rename the class without breaking all the links to it, which will now utilize the interface. You can also specify which methods you'd like to extract, which will quickly show you via compile time errors where you're referencing the implementation class directly.

    ReplyDelete
  23. I think the arguments that you provide against interfaces are not valid at all. For me programming is not about how many files you have in the application, or how easy it is to go to the source of something. Programming is about making things work the right way. Now, I've participated in the implementation of applications that expose extensive APIs and are used by many other developers. If I didn't use interfaces, I doubt I would be able to make users of these products happy. In short I think you are irritated by the IDE, as Roger said, not the interfaces themselves.


    and you create an interface JUST TO ALLOW MOCKING


    If you can mock an object, then it means that you can extend it and you have the flexibility to add additional functionality to the released product. So in fact there's no "just to allow mocking", mocking rather adds visibility to some design flaws you may have in the product. It is the same as with unit testing - only after you start doing it you realise how bad you clients felt with your product.

    And finally, I also think that interfaces allow multiple inheritance in languages that otherwise don't support it. So my advice to you is to get the right tools for your IDE and don't confuse programming experience with the final result.

    ReplyDelete
  24. Yes. There are a billion programmers out there who've been taught design patterns so now they have to make everything fit into one of those nice neat boxes. Code's no good unless it's complicated.

    ReplyDelete
  25. By programming against interfaces you're able to switch to implementation in a central place, e.g. a factory, a builder or dependency injection, which is a good thing.

    The downside is a higher complexity, so using interfaces depends on your requirements/needs. If you have a fixed implementation that yould never change, let it be.

    ReplyDelete
  26. Interfaces can be good for decoupling modules of your system that are at different levels of abstraction - for example, see the Separated Interface Pattern (http://martinfowler.com/eaaCatalog/separatedInterface.html). In this specific case, I can see there being value in splitting into interface and implementation, even if there is just one implementation.

    For example, following Domain Driven Design principles, you try to have a separate, rich, entirely "business-focused" layer. This layer may still require access to objects that come ultimately from the database. By defining a "Repository" interface with operations defined purely in domain terms within the domain layer, and then having it implemented by a class in the infrastructure layer (which knows all the data access details), you eliminate the dependency of the domain on any infrastructure code (i.e. you could happily compile your domain layer without requiring the infrastructure code to be present).

    However, I do agree that introducing interfaces just to support testing, or creating them as a matter of course for every class seems very wrong.

    ReplyDelete
  27. I used to use interfaces for mocking but at least in C# with rhino mocks you can get around that (you'll be making a lot of methods virtual though.). I agree that using interfaces just for this is a waste.

    Another reason to use interfaces is for decoupling dependencies. Instead of one class depending on another they can both depend on an interface, one by implementing it and one by consuming it. I still use interfaces a lot for this. In a model view presenter architecture I usually have the presenter depend on an interface on the view instead of on the view class directly. This can be a very useful tool for resolving circular references between assemblies in your code too.

    Interfaces are also a good tool to be more flexible in the way you order your work. If you want to implement and test high level behaviour first without getting bogged down in low-level dependencies you can just implement the low level behaviour (like persistence or writing to a file) as an interface and mock it in your tests. Later you can decide if you want to implement the interfaces you made this way or remove them completely if they're not useful anymore. Interfaces that are implemented only once and are only used within an assembly usually get removed.

    Another thing to keep in mind that it's usually better to create small interfaces and implement more of them in a single class than create big monolithic interfaces. This improves decoupling and flexibility in your object design.

    @Mike Stone: I often remove pieces of code that don't carry their own weight when refactoring. That includes interfaces that don't add anything useful. I agree that dummy implementations of classes as scaffolding can be better when you dont intend to use an interface in the final version. Interfaces require less typing beforehand but more refactoring to remove them when you're done. I don't always know beforehand what I intend to use though.

    ReplyDelete
  28. You're right, referring to an interface conveys less information than referring to a concrete class. But this is generally a good thing. It keeps code simpler, which is usually better. Code written against an interface is only concerned with what the interface provides, and so all the extra information about what implementation you're using is irrelevant. I usually find code easier to read if it doesn't contain irrelevant information.

    To respond to the two things you don't like about interfaces:


    This is a problem with modularity in general. The same thing happens when we decide to create a function somewhere instead of just writing the entire application inline within the main() method. This is a strange complaint. It seems you could use the same principle to complain about variables: e.g. you don't know what the value of a boolean variable will be at runtime, so how do you know whether to read the code in an if block?
    Don't add a separate file for the interface and its implementation if it bothers you. Do this instead:


    :

    public interface Foo {

    public void bar();

    ... other methods
    public static class BasicImpl implements Foo {
    public void bar() { ... }
    ... other methods
    }
    }

    ReplyDelete
  29. There is something else at work here that nobody has mentioned: personality.

    Developers with certain personality types love a high degree of structured craftsmanship. They like putting boxes inside of boxes. For these developers, using interfaces FEELS good, and so that makes interfaces easier to use and much more effective for them.

    Developers with other personality types love problem-solving. They want the most efficient path from A to B. To them, adding anything to the code that might never be used FEELS bad, and so that makes interfaces harder to use and less effective for them.

    If you love Interfaces, you will spend more time thinking about them, and your Interface designs will be better, and it will make you love Interfaces even more.

    If you hate Interfaces, you will spend less time thinking about them, and your Interface designs will be weak, and that will bite you later and will make you hate Interfaces even more.

    So, how you FEEL about Interfaces has a major impact on when you should use them. If you hate them, reduce your use of them, because you aren't going to do them correctly anyway. We are only human. :)

    ReplyDelete
  30. You abstract away where the implementation is coming from. This problem has a couple consequences... in an IDE, it means that when I try to browse to the source of this method being called... I get taken to an interface instead of some code that I can look at and see what is going on. This bothers me a lot, but also this is a real problem to me to hide where the implementation is coming from (sometimes it can be in non-obvious locations)



    This could be considered to be a problem with your IDE. For C# editing, I use Jetbrains ReSharper, and it has a natty "Go to Inheritor" feature that takes you from a method in the interface to the implementation. I suspect that other VS addons (Visual Assist, the DevX tools, etc.) will have a similar feature.

    If you're on Eclipse (I'm not), I suspect that someone will have cooked up something similar.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex