Saturday, March 6, 2010

Relax. You can (mostly) stop using Interfaces in Java now.

Detractors of Java are correct to point out a rather unfortunate trend in the Java world- there is a common tendency for developers to turn every non-trivial class into an Interface, and then create an "Impl" that actually does the work.  As a result, your codebase becomes littered with lots of superfluous interfaces that have only a single implementation.

Why do we do this?

Part of it is simple architecture astronautics, but there is actually a very legitimate use case for creating interfaces even when there is only a single implementation- it allows you to mock out your objects so that other classes can be unit tested easily. This is really important in TDD, and so I've come to accept the fact that there will always be some extra "interface noise" in the codebase in order to support a good test infrastructure.  C'est la vie, right?

Along comes JMock 2.5, with its ClassImposterizer, backed by cglib.
"The ClassImposteriser creates mock instances without calling the constructor of the mocked class. So classes with constructors that have arguments or call overideable methods of the object can be safely mocked."
I should point out that this isn't exactly new- JMock 2.5 came out in 2008, so I'm a little late to the game here.  But I haven't seen much written about this.  It's a really huge change.  It means that you can do things like:

final java.awt.Graphics2D graphics = mockery.mock(java.awt.Graphics2D.class);
    mockery.checking(new Expectations() {{
    one(graphics).getBackground();
    will(returnValue(java.awt.Color.BLUE));
}});
Of course this is great for testing code that uses libraries that weren't designed with mocking in mind, but even better than that- you can use it against your own code, and save yourself from having to create interfaces.

This means you can go ahead and create your concrete MyComplicatedDAO, without having to create MyComplicatedDAOIFace, MyComplicatedDAOImpl, MyComplicatedDAODummy, etc.  When you need to test code that uses it, you just do:
final MyComplicatedDAO dao = mockery.mock(MyComplicatedDAO.class);
    mockery.checking(new Expectations() {{
    one(dao).getLoggedInUsername();
    will(returnValue("user1"));
}});
It's really hard to overstate the significance of this.   It's changed the way I write and test code. It's very refreshing to be able to start out with a concrete class and write code that does stuff, rather than code that merely talks about doing stuff.

Of course there are still very legitimate reasons for using interfaces. If you're designing a library, using interfaces makes life easier on your users. Interfaces are also a great way to decouple code, to remove circular dependencies, and to support callbacks.  All of these are legitimate and appropriate uses, and you shouldn't abandon them.

But use interfaces with reason, and not by reflex.

98 comments:

  1. You may want to check out mockito (http://code.google.com/p/mockito/), I've had it recommended several times, apparently the ignore key mock works better as well (I've found with JMock that i've had to specify everything if i wanted it to assert the mock calls.

    ReplyDelete
  2. Are you currently using Spring (IOC, DI, etc) in your coding? How would you suggest removing interfaces and retaining all of that spring-like functionality?

    ReplyDelete
  3. At my company we use EasyMock (http://www.easymock.org/). We find that is supports re-factoring better with its use of the "real method" approach opposed to the jMock "string literal" or non-dot notation standard method invocations.

    ReplyDelete
  4. @Anonymous- we're using Seam for DI. It has no issues with injecting concrete classes and wiring everything up properly. Does Spring still require interfaces?

    ReplyDelete
  5. Spring does not currently require interface for DI.

    And throw up another easymock bit of praise out there, it has supported mocking classes with the class extension for a few years also.

    ReplyDelete
  6. I never had anything particular against interfaces, but boy, were those Spring kiddies annoying with their insistance that abstract classes are evil and everything needs to be an interface.

    ReplyDelete
  7. I believe I would have to kill myself before I used this programming language feature.

    P.S.: Mock mock mock mock mock.

    ReplyDelete
  8. // Mockito is awesome
    ComplicatedDAO dao = mock(ComplicatedDAO.class);
    when(dao.getLoggedInUsername())
    .thenReturn("user1");
    //do something
    verify(dao).getLoggedInUsername();

    There is also powermock which builds on mockito to mock static methods!

    ReplyDelete
  9. If you have to mock static methods in order to test your code, you doing it wrong.

    ReplyDelete
  10. As a .NET developer, I feel like I need to defend interface programming a little bit here. Yes, that feature is neat; I have to say, though, if the primary use case you're creating interfaces is to better facilitate unit testing, something's being overlooked.

    Many of the reasons I use interfaces stem from adaptability (I have no idea if we'll still be on this provider in 3 months), assembly management (use IoC to resolve an assembly in the global assembly cache, avoid referencing assemblies directly), and parallel development (I don't have to wait on you to get started.) Yes, all this can be done without interfaces, but it sure does lend itself to a few advantages outside of just better unit testing.

    ReplyDelete
  11. @Kenly: +1
    Especially - "I don't have to wait on you to get started"

    ReplyDelete
  12. Well this makes sense, but this would only work if you do not use static methodsw in the class isnt it?

    ReplyDelete
  13. @Fazal- the idea is that when testing code that depends on a class under your control, you don't have to write an interface for it, and can instead just create a concrete implementation and jmock it as necessary. Since the code is under your control (you wrote it) presumably you are also not boxing yourself into a corner by creating static methods.

    If you're talking about mocking static methods in some library code, well that's another issue. If you google it, I believe there are jmock-based solutions for this as well. Thanks.

    ReplyDelete
  14. @Kenly- I would tend to think YAGNI. But I don't know .NET, so I'm not really qualified to say for sure. But it's very common in the Java world to create interfaces explicitly for DI/IoC and unit testing. In fact I'd estimate that (outside of library design) that's the *primary* reason for creating an interface. Thanks for your comment.

    ReplyDelete
  15. Just a matter of taste i prefer JMockit, which basically help me to integrate my new code with current legacy code that was not design as TDD in mind and the abuse of statics method is overwhelming.

    ReplyDelete
  16. Interfaces also play a key role in building the separate layers in most non-trivial apps. Any layer wants to only advertise its public interfaces, thereby limiting dependencies.
    Having to use mocks is a red flag to me; certainly they are unavoidable. But if you need to use a mock to test your design is probably poor.

    ReplyDelete
  17. @Christian. JMock2 fixed the issue of string literals...

    ReplyDelete
  18. Absolutely. Interfaces are overused in Java.
    Scala it has something generally more usable called "Traits".

    Abstract classes (which is kind of what Traits are like) have huge advantages over interfaces in terms of code maintenance and api change.

    If someone extends my api abstract class I don't have to worry about adding additional concrete public methods to that abstract class and having break all existing implementations.

    This is nice because I don't have to add lots static utility methods or transfer objects when I want some behavior added to that type of object.

    The only issue is multiple inheritance.

    Now of course interfaces are nice for API but you should not have lots of them or else that means you will have to maintain a large API.

    You want only has much API exposed that is needed. Not hundreds of interfaces.

    ReplyDelete
  19. I have been looking for some info about You can(mostly) stop using Interfaces in Java now, and wow I have no idea that in the web were so many blogs related to generic viagra, but anyways, thanks for sharing your inputs and have a nice day.

    ReplyDelete
  20. Hello I want to congratulate to them by its site of the Web of the excellent looks like entertained and very good very to me it elaborated. I invite them to that they explore a little on my Web site. Lots in Costa Rica Costa Rica Cheap Land for Sale

    ReplyDelete
  21. When I bought my computer and I didn´t know how to use java graphics, so I decided looking for information in a webside and I found an useful information that helped me a lot.. Now I am interested in to do the best investment and I found a webside very useful and interesting called costa rica investment opportunities , I think it´s a very wonderful site.

    ReplyDelete
  22. Well this makes sense, but this would only work if you do not use static methodsw in the class isnt it?

    ReplyDelete
  23. http://www.bestpenisproducts.com is an all-natural Penis Enlargement, safe, and guaranteed alternative to painful and dangerous Penis enlargement methods such as surgery, straps, or rings.
    penis enlargement pills or male enhancement pills will immediately boost your performance, improve your orgasms, and increase the size of your penis within just a few weeks!
    VISIT OUR BEST PENIS ENLARGEMENT PILLS PRODUCTS:

    VIGRX PLUS PILLS
    VIMAX PILLS
    MALE EXTRA PILLS
    MALE ENHANCEMENT PILLS

    ReplyDelete
  24. We just wanted to share information about best penis enlargement that are busy talking about people who want a bigger penis size, stronger and able to increase stamina.
    http://www.sizepenisenlargement.com
    Penis Enlargement Pills
    Top Penis Enlargement Pills
    Method Penis Enlargement Pills

    ReplyDelete
  25. In the new Louis Vuitton Cabas Rivington core values campaign ,the ads features astronauts photoshop software Buzz Aldrin who is the first woman astronaut into space, Jim Lovell the director of Apollo 13 and Sally Ride the first louis vuitton moda astronaut who left his footprint in the moon. The three astronauts pose buy replica handbags with a battered pickup truck and a travel bag while gazing up into the sky in the California desert nrgbh100901.

    ReplyDelete
  26. Greetings,

    Hi blog owner, I was very impressed with your blog. Because I think you have an interesting post, therefore I will revisit your blog to see any updates you are doing.

    Now I want to share a little information about the best product for becoming a real men.

    Vimax is the brand name of a most popular male enhancement on the market today. These products include a Vimax Pills, a Vimax Patch, Vimax Extender and also a sperm enhancer Vimax Volume.

    It is my understanding that this product has a good reputation in the marketplace, having been sold online for more than ten years now. It also comes with money back guarantee which should give men more confidence in their buying decision.

    Cheers.

    ReplyDelete
  27. For men who want bigger, harder, longer-lasting erections, there's now VigRX Plus™, a fresh twist on the already popular VigRX™, but designed to further enhance men's sexual functioning with the addition of three exciting new ingredients: Damiana, Tribulus, and Bioperin. Doctor endorsed and rated #1 for results by clients of penis enlargement consumers. rated two penis pills is vimax. if you find about male enhancement this products is the best and proven to work, there products have money-back guarantee in effectiveness and result.

    ReplyDelete
  28. about jerking off hot twink cock gay bondage with a masturbation session in front of our cameras.
    trying desperately to swallow the huge cock
    bends bound male over to take it up the ass
    rough day for Ricky Sinz, Drew Cutler tries to make him feel better and rubs his wounded, muscle bod
    there's no limit to male bdsm what you can swallow at an all-you-can eat white cock. Luke takes a 12-inch dildo gay extreme and begs three times before Sebastian takes gay spanking the boys throbbing dick and takes him over the edge to climax. one of the gay punishment hottest video shoots we've had in a while, male fetish Dallas Knight and Thugzilla show off their mighty fine bods on the high seas in this encounter. perfect ass for this piss-filled video They trade blowjobs slurping on each other before

    ReplyDelete
  29. brand name handbags and cheap designer bags Brand fashion replica handbags, cheap luxury, wholesale designer shoes, women fashion clothes.

    replica shoes and handbags replica

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. That is really very good article.kızlarla chat,I am glad to know.mersin chat,Thanks for sharing !avrupa chat

    ReplyDelete
  32. It also comes with money back guarantee , I agree with you .

    ReplyDelete
  33. Dear friends,Cheap Sale Louboutin online.All shoes elegant shoes is one of masterpiece from Christian Louboutin Platforms. When you buy yourself a pair of Christian Louboutin Thong Sandals
    shoes you allow yourself to benefit from the vast experience and expertise that this brand has collected over the years.Christian Louboutin Platform Sandals
    shoes is the personification of women,is their direct orgin of racial pride.Christian Louboutin Shoes
    shoes is the personification of women,is their direct orgin of racial pride.andChristian Louboutin Mensis a very distinctive design, its design reflects its style. You put on it, that means you have its style.Welcome to our Louboutin 2011 .

    ReplyDelete
  34. Want to be the fashionable person?Sexy and beautiful women are always men's favor. Now come to Louboutin UK store! We will change you into a gorgeous girl! Here provides Christian Louboutin Fashion,Louboutin 2011,Christian Louboutin Wedding,louboutin platforms,Louboutin Wedges and so on.The unique and well-Designed shoes favored by the world, signed with the Christian Louboutin red soles of the mark, giving high heels and covetable accessories, system pumps and elegant luxury Christian Louboutin clutch has to be available almost all fashion only. We now provide Christian Louboutin shoes with free shipping and save 60% off! Hurry up! Christian Louboutin UK store is your first choice!

    ReplyDelete
  35. Great post thank sfor the nice share!!!

    ReplyDelete
  36. For men who want bigger, harder, longer-lasting erections, there's now VigRX Plus™, a fresh twist on the already popular VigRX™, but designed to further enhance men's sexual functioning with the addition of three exciting new ingredients: Damian, Tribulations, and Couperin. Doctor endorsed and rated #1 for results by clients of penis enlargement consumers. rated two penis pills is vi max. if you find about male enhancement this products is the best and proven to work, there products have money-back guarantee in effectiveness and result.
    Dripping Springs Remodeling Contractor

    ReplyDelete
  37. Well you would say that wouldn't you? I've always thought the opposite but just couldn't prove it.

    ReplyDelete
  38. Exceptional publish you’ve caused proper here! The internet is stuffed of poor penning and I used to be grabbed by your readability. Your choices are accurate and i will instantly subscribe to your rss nourish to remain as much date with your up rising postings. Yes! I acknowledge it, your authorship style is astounding and that i will work harder on enhancing mine.

    penis pills

    ReplyDelete
  39. Christian louboutin shoes disconut are so captivating using the distinctive style and design and stylish appearance.Louboutin Heels is on sale now, why not purchase a pair of Louboutin heels for yourself? They will assist you be additional attractive and comfortable. Louboutin mall are worthy of treasuring.

    ReplyDelete
  40. Oh man, this is great. I remember Spin doing an article on Pen & Pixel back in the mid to late nineties, part of it involved cover mock-ups for artists like Nine Inch Nails and Tori Amos. I've been looking for that picture of Trent Reznor sitting on a throne, a castle silhouetted by lightning holding a jewelled chalice (if memory serves) ever since.
    Abilene Roofing Contractor

    ReplyDelete
  41. Nice post. Great blog. Thanks for sharing. It was very interesting and informative.
    Money Talks| Money Talks News|

    ReplyDelete
  42. this very incredible blog and very interesting to read ..
    continue to add his writings ..
    thanks

    ReplyDelete
  43. Thanks for the program. I used it. Its working

    ReplyDelete
  44. Amazing!I also wish him good luck to defend his gold medal. I like to share it with all my friends and hope they will also encourage him.

    ReplyDelete
  45. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.

    ReplyDelete
  46. Thank you, I have recently been searching for information about this topic for ages and yours is the best I have discovered so far.


    the best seo company

    ReplyDelete
  47. Thanks for your post, I like this post very much.

    ReplyDelete
  48. Thanks for your post, I like this post very much.

    http://www.angelslimoservice.com

    ReplyDelete
  49. This is one of the highly informatics and attractive blogs that has not only educated also informed me in a very effective manner. There are very few blog like this one I have read.

    ReplyDelete
  50. This is one of the best post I've ever seen, you can include some more ideas in the same theme. I'm still waiting for some interesting thoughts from your side in the next post. One thing I just want to say is that your blog is so perfect!
    @ Vimax, Vimax pills, VigRX Plus, Penis Enlargement, Penis Enlargement Pills

    ReplyDelete
  51. I was wondering when can I stop using Interfaces in Java.

    ReplyDelete
  52. Wow, thats amazing.I love the way you write. Do you provide an RSS feed?

    buy percocet online

    ReplyDelete
  53. This site is excellent and so is how the subject matter was explained. I also like some of the comments too.Waiting for next post.
    organic seo service|

    ReplyDelete
  54. All these ideas are quite easy to understand and I wonder why I've never thought thus. It's excellent that your blog is full of worthy information for your readers.

    ReplyDelete
  55. Awesome pictures and interesting information and attractive.This blog is really rocking...

    ReplyDelete
  56. Wonderful post. I am searching awesome news and idea. What I have found
    from your site, it is actually highly content. You have spent long time
    for this post. It's a very useful and interesting site. Thanks!

    ReplyDelete
  57. ClassImposterizer really help me do it! Thanks a lot for this post like manual! =)

    ReplyDelete
  58. You will be missed.The one place where as a venue and fan I could search by
    what ever perimeters I chose .Good Luck with your future endeavors.

    ReplyDelete
  59. A true love is what doesn’t strive for busyness, for extravagance, for luxury, and moreover for hokum

    ReplyDelete
  60. nice to share my love is wonderful to tell you that a healthy green gives you the best Organic vitamins, herbal remedies and organic supplements.
    They use all natural ingredients to create organic products.

    ReplyDelete
  61. Casi la gente le gusta escribir lo que dijo, pero me gusta escuchar lo que dijo, su mensaje es muy bueno. Gracias!

    ReplyDelete
  62. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!

    find doctor list

    ReplyDelete
  63. Simply perfect blog post - I save it on delicious - need more posts like this!

    toronto limo rentals

    ReplyDelete
  64. I think the original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995 link

    ReplyDelete
  65. Thank you for for sharing so great thing to us. I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post nice post, thanks for sharing.

    ReplyDelete
  66. Your blog is very useful. Thank you so much for providing plenty of useful content. I have bookmark your blog site and will be without doubt coming back. Once again, I appreciate all your work and also providing a lot vital tricks for your readers.
    rent apartment in Dubai

    ReplyDelete
  67. I can not stop reading this. And 'so fresh, so full of information,
    I do not know. I'm glad that people actually write the smart way to
    show the different sides of him.
    testimonial voiceovers

    ReplyDelete
  68. I agree with you. This post is truly inspiring. I like your post and everything
    you share with us is current and very informative, I want to bookmark the page
    so I can return here from you that you have done a fantastic job ...

    Natural supplements

    ReplyDelete
  69. I think a number of criticisms have been leveled at Java for various design choices in the language and platform. Such criticisms include the implementation of generics, the speed of Java, the handling of unsigned numbers, the implementation of floating-point arithmetic, and a history of security vulnerabilities in the primary Java VM implementation HotSpot
    buy term papers, essays

    ReplyDelete
  70. This is good site to spent time on .I just stumbled upon your informative blog and wanted to say that I have really enjoyed reading your very well written blog posts. I will be your frequent visitor, that's for sure.

    ReplyDelete
  71. I am visiting this site first time & it has awesome information. I have come to know a lot of information after visiting this site. Keep this sort of posting in future as well.....
    buy watson

    ReplyDelete
  72. It will benefit all the people. appreciate the idea. and Yours truly

    ReplyDelete
  73. Thank you for sharing this kind of important information. and especially for sharing your own experience with these.

    ReplyDelete
  74. Your thoughts are real help to any developer, who uses Java interfaces

    ReplyDelete
  75. Nice to be visiting your blog again, it has been months for me.
    Well this article that I've been waited for so long.


    3d ultrasounds
    4d ultrasounds
    4d3d ultrasounds

    ReplyDelete
  76. Thank you for for sharing so great thing to us. I definitely enjoying every
    little bit of it I have you bookmarked to check out new stuff you post nice post,
    thanks for sharing.

    tubal ligation reversal

    ReplyDelete
  77. There are Usually Extremely couple of Individuals Who Can not Write Articles That Creatively so easy. Keep Up the good writing!

    ReplyDelete
  78. The blog is written in such a way that it is so easy to read and understand.
    web hosting Pakistan

    ReplyDelete
  79. Researchers observed that curcumin seems to help fight and prevent damage caused by liver fibrosis, a chronic liver disease that typically leads to.

    ReplyDelete
  80. Some people really make difference. Blog carries great informative material. One should read this one and appreciate. Thanks.

    ReplyDelete
  81. dieta online
    Hi! This is my first visit to your blog! We are a team of volunteers and new
    initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job!

    dietas online

    ReplyDelete
  82. Very interesting article, I was looking about this subject.

    custom essays paper

    ReplyDelete
  83. I agree with you. This post is truly inspiring. I like your post and everything
    you share with us is current and very informative, I want to bookmark the page
    so I can return here from you that you have done a fantastic job ...

    ReplyDelete
  84. Good information, please write another one.

    ReplyDelete
  85. these are so great! This is a content I like, I think you must have spent a lot of effort to prepare, very grateful. Thank you so much for your post.

    ReplyDelete
  86. Many human trials are needed before we can know with any certainty how we can best use curcumin in medicine.
    herbal vitamins
    |curcumin

    ReplyDelete
  87. Every dog has his day, the Doves are made of Pellucida TM, a durable resin compound, and may be cleaned by washing with soap & water. They are unconditionally guaranteed against any defects in materials or workmanship.

    ReplyDelete
  88. One of those informative posts i get interested reading with. This is very helpful.

    ReplyDelete
  89. It's great to see a blog of this quality. I would learned a lot of new things. Thank you.
    Hospital Reviews and Ratings

    ReplyDelete
  90. Wow its totally a unique dress designs really very impressive..

    Salon and Spa Logo

    ReplyDelete
  91. Great improvement to the organization is strengthening.

    ReplyDelete