Tuesday, March 4, 2014

Break the bloated library cycle with Java 8

Most of us have, at some point in time, wondered why all successful java libraries tend to "bloat" by adding new stuff all the time. Spring is a great example. Why on earth is there spring-jdbc, spring-transaction or even spring-web ?

Apart from the obvious market-wise need for a companies to appear as a continuous sources of innovation (investors like that), there are some technical issues involved too. This post looks at how java8 can change some of the dependency issues; it may even change how you do java7 right now.

Java7


The dilemma: A class/library wishes to reuse external services, which introduces dependencies.

public class MyClass {
    private ExternalDependency1 ed1;
    private ExternalDependency1 ed2;
   public int doSomething(String input){
       return ed1.calculate( ed2.transform( input));
   }
}

Now this is the classical reason why need to make *our* module depend on something external, ExternalDependency1 and ExternalDependency2 are defined in another project. This is basically the technical reason why we have 280 different "spring" projects; they all tie in with their different dependencies.

Java8 to the rescue

In java8, we can easily move the declaration of the required type *into* MyClass, which makes it self-contained with respect to dependencies:

public class MyClass {

public interface InternalDependency1 {

int calculate(String source);
}
public interface InternalDependency2 {
String transform(String source);
}
private InternalDependency1 id1;
private InternalDependency2 id2;
public MyClass(InternalDependency1 id1, InternalDependency2 id2) {
this.id1 = id1;
this.id2 = id2;
}
public void doSomething(String input){
id1.calculate( id2.transform( input));
}
}

At first glance, this seems like just additionally bloating the code. We need to look at the use before it all becomes clear:

ExternalDependency1 ed1 = new SomeObject1();
ExternalDependency2 ed2 = new SomeObject1();
MyClass mc = new MyClass( ed1::calculate,         ed2::transform);

Now this is where the subtle magic happens; any method that matches the *shape* of the calculate or transform method will be autoboxed into something that can be *used* as InternalDependency1/2.

With this one magic little change, MyClass suddenly lost all its external dependencies.

What about java.util.function.Function ?


Some of you will notice that I am using 1 method interfaces instead of the generic java.util.function.Function class. There are several reasons for this:

A) It is an explicit type that will some day provide IDE support. Current IDE support is somewhat sketchy, but this will improve.
B) "MyClass" is a library component that is expected to have clients; the "cost" of these interfaces making the external contract of "MyClass" 100% clear is probably worth it in the long run.
C) This is java5/6/7 compatible, although the java7 client will have a slightly less cool client api (anonymous inner class galore)
D) If you use Function, the only thing expressing the intention of the function will be the local variable name; in this case id1 and id2. This makes our java code all javascripty; much as I love javascript I am a little sceptical about too this in java; at least for "library" style code.




121 comments:

  1. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    ReplyDelete
  2. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.Block Chain Training in Bangalore

    Block Chain Training in Bangalore

    block chain Training in btm

    Block Chain Training in tambaram

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

    ReplyDelete
  4. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.


    rpa training in chennai | best rpa training in chennai | rpa training in chennai | rpa training in bangalore
    rpa training in pune | rpa online training

    ReplyDelete
  5. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs Training in online

    ReplyDelete
  6. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Best Devops Training in pune

    ReplyDelete
  7. Awesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..
    python training in velachery | python training institute in chennai



    ReplyDelete
  8. This looks absolutely perfect. All these tiny details are made with lot of background knowledge. I like it a lot. 
    python interview questions and answers | python tutorials

    ReplyDelete
  9. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me

    Java training in Marathahalli | Java training in Btm layout

    Java training in Jaya nagar | Java training in Electronic city

    ReplyDelete
  10. nice site you have here!We provide world-class Oracle certification and placement training course as i wondered Keep up the excellent work experience!Please visit Greens Technologies located at Chennai Adyar Oracle Training in chennai
    Devops Training in Chennai | Devops Training Institute in Chennai

    ReplyDelete
  11. Amazing! I like to share it with all my friends and hope they will like this information.
    Regards,
    Python Training in Chennai | Python Programming Classes | Python Classes in Chennai

    ReplyDelete
  12. I likable the posts and offbeat format you've got here! I’d wish many thanks for sharing your expertise and also the time it took to post!!

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  13. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  14. If you have Natural Curls or Curly Hair, you are just blessed. You can experiment with many Hairstyles which will Look Stylish here we tell about top best and easy Curly Hairstyles

    ReplyDelete
  15. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live.
    javascript training in chennai | javascript training institute in chennai | javascript course in chennai | javascript certification in chennai | best javascript training in chennai

    ReplyDelete
  16. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    IT Institute in KK Nagar| Data Science Training in chennai | data science course in chennai | data science Training Institute in Chennai

    ReplyDelete
  17. Thanks for the Valuable information.Really useful information. Thank you so much for sharing.It will help everyone.Keep Post. Find Some Indian Memes. Interesting News Tamilrockers Movie Download Trending News Some Life hacks tips Life hacks Entertainment News Find Some Viral News Here.Viral News
    saurabh jindal

    ReplyDelete
  18. Nice article
    Thanks for sharing the information
    Please visit leadmirror to know your seo position on the google

    ReplyDelete
  19. For Blockchain training in Bangalore, Visit:
    Blockchain training in Bangalore

    ReplyDelete
  20. Thank you so much for this useful article. Visit OGEN Infosystem for Web Designing and SEO Services in Delhi, India.
    SEO Service in Delhi

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

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

    ReplyDelete
  23. 이러한 최고의 노치 팁으로 비즈니스의 SEO 개선에 도움을주십시오!

    웹 사이트의 각 카테고리별로 높은 게재 위치를 달성하는 방법을 이해하는 것은 문자 그대로 성공적인 비즈니스와 실패한 벤처의 차이입니다. 비즈니스 거래에 성공하려면 아래에 제공된 검색 엔진 최적화 팁을 읽으십시오.

    URL에서 관련 키워드를 사용하여 최대 검색 엔진 순위에 맞게 웹 사이트를 설정하십시오. 키워드가 페이지의 다른 곳에 나타나는 한 검색 엔진은 URL에 사용 된 용어에 상당한 가중치를 부여합니다. 사이트에 사용 된 도메인 이름을 제어 할 수없는 경우에도 페이지 이름은 귀하에게 달려 있습니다.

    사이트 SEO를 설정할 때 사이트의 URL을 잊지 마십시오. 도메인을 설정하면 하위 도메인보다 도메인이 더 좋습니다. 또한 약 10 단어를 초과하는 URL은 스팸으로 분류 될 위험이 있습니다. 도메인에서 약 3-4 개의 단어를 원하고 페이지 이름에서 6 또는 7을 넘지 않아야합니다.

    웹 사이트에 권한이 있는지 확인하십시오. 검색 엔진 최적화는 고객 및 / 또는 고객이 브랜드를 신뢰하는 경우에만 성공할 수 있습니다. 기억하기 쉬운 전용 도메인 이름은 사람들이 웹 사이트 체크 아웃을 마치고 오랫동안 기억할 수있는 브랜드를 구축하는 첫 번째 단계입니다.

    검색 엔진 결과 페이지 상단에 도달하는 확실한 방법 중 하나는 훌륭한 콘텐츠를 보유하는 것입니다. 흥미 롭거나 재미있는 정보를 지속적으로 제공하면 사람들이 자연스럽게 귀하의 사이트로 돌아 가기를 원할 것입니다. 훌륭한 콘텐츠를 만들기 위해 노력하는 경우 전문 작가를 고용하는 것이 좋습니다.

    이러한 아이디어 중 일부를 바로 사용할 수 있지만 다른 아이디어는 장기적으로 효과적 일 수 있습니다. 귀하의 사이트를 더 잘 인식하려면 다음 정보를 현명하게 사용하십시오 구글상위업체.

    ReplyDelete
  24. Great Post!
    Thanks for providing valuable information. 파워볼사이트

    ReplyDelete
  25. Hey, would you mind if I share your blog on my social media channels? There are a lot of folks that I think would enjoy reading your content. Please let me know. Thank you.
    ios developer
    app development
    app developers india

    ReplyDelete
  26. Effective blog with a lot of information. I just Shared you the link below for ACTE .They really provide good level of training and Placement,I just Had Blockchain Classes in ACTE , Just Check This Link You can get it more information about the Blockchain course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  27. Selenium testers have great opportunities. Many new things and compatibility features are added every day. So, start to learn selenium course and get a bright career. good luck
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  28. If you are a proficient online player you are playing at two or more tables at a time. Some players I know play at 16 tables on two different sites simultaneously. 안전놀이터

    ReplyDelete
  29. https://www.pforprograms.com/2020/09/cc-basic-programs-with-example-and.html

    ReplyDelete
  30. I am really loving the theme/design of your web site. Do you ever run into any browser compatibility problems? A few of my blog readers have complained about my website not working correctly in Explorer but looks great in Chrome. Do you have any tips to help fix this issue?

    ReplyDelete
  31. 좋은 블로그 !!! 당신의 블로그를 전달하는 방식이 더 인상적입니다. 귀중한 정보에 감사드립니다. 정말 유용한 정보입니다. 좋은 공유.
    내 지식에 추가해 주셔서 감사합니다.안전놀이터

    ReplyDelete
  32. Oh my goodness! Awesome article dude! Thanks, Numerous tips!

    my website - 부산오피


    (jk)


    ReplyDelete
  33. I am impressed with this website, really I am a big fan.
    휴게텔

    Hi there mates, how is all, and what you would like to say concerning this
    article, in my view its truly awesome in favor of me.

    ReplyDelete
  34. I got a web site from where I be capable of really obtain valuable information regarding my study and knowledge.
    Great Article… Good Job… Thanks For Sharing…

    Website:바카라

    ReplyDelete
  35. Shop for the latest Redmi mobiles from Helmet Don at the best prices in India. Xiaomi smartphones include Mi Series, Mi Note Series, Redmi Series, Pocophone, Mi Max Series, Mi Mix Series, and the Blackshark.
    HelmetDon
    MI
    redmi-phones


    ReplyDelete
  36. Shop Repair & Buy Mobiles Online At best prices in India only at https://rshop.in/location/puthur-kollam/

    ReplyDelete
  37. Best Air Fryers In 2022

    Mealthy Crisplid

    For Download Subway Surfers Mod Apk
    -------------------------------------015------------------------------------------
    Sous Vide Anova Nano

    For Download Subway Surfers Mod Apk

    ReplyDelete
  38. Are You Thinking About Joining AVATRADE REVIEW ? If You Are Then Read The Review On AVATRADE Fx In This Article. We, Will, Tell You About The Company, The Brokers, The Platform, And All The Information You Need To Know. Read More Here.

    ReplyDelete
  39. 메이저놀이터추천November 20, 2021 at 4:02 AM

    I've been troubled for several days with this topic. 메이저놀이터추천, But by chance looking at your post solved my problem! I will leave my blog, so when would you like to visit it?


    ReplyDelete
  40. It's too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site 꽁머니 and leave a message!!


    ReplyDelete
  41. Write more, that all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what your talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something informative to read?대딸방

    ReplyDelete
  42. It is perfect time to make some plans for the long run and it is time to be happy. I’ve learn this post and if I may I wish to counsel you some interesting issues or tips. Maybe you could write subsequent articles regarding this article. I desire to learn even more things approximately it!마사지블루

    ReplyDelete
  43. What a nice post! I'm so happy to read this. baccarat What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.


    ReplyDelete
  44. "Excellent blog you have here.. It’s difficult to find quality writing like yours nowadays. I really appreciate individuals like you! Take care!!
    I could not refrain from commenting. Exceptionally well written."

    야설

    ReplyDelete
  45. "Howdy! Would you mind if I share your blog with my zynga group?
    There’s a lot of people that I think would really enjoy your content.

    Please let me know. Thank you 오피헌터"

    ReplyDelete
  46. Quality articles or reviews is the important to interest the people to pay a quick visit the website, that’s what this site is providing. 카지노사이트탑

    ReplyDelete
  47. I'm so happy to finally find a post with what I want. 오공슬롯 You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.


    ReplyDelete
  48. What a post I've been looking for! I'm very happy to finally read this post. evolution Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


    ReplyDelete
  49. It's so nice to know you. I hope you also welcome me.메가슬롯If you welcome me, please visit my blog and write. My blog is on It's hard because of Covid - 19, but let's do our best!!


    ReplyDelete
  50. It’s really a great and helpful piece of info. I’m glad that you shared this helpful info with us. Please keep us up to date like this. 토토사이트

    ReplyDelete
  51. At Ranks In Forex . our SEO process will make sure your business or website is easily found by new potential customers. Let us help you harness the power of search engine optimization.

    ReplyDelete
  52. I used to ask to get this information for a long time, I was not getting it, after reading your post, I have got complete information about it.

    ReplyDelete
  53. Get the latest Siml Stock real-time quote, historical performance, charts, and other financial information to help you make more informed investment decisions. You'll get an overview of a stock's key fundamentals including revenue and earnings as well as valuation measures such as price/earnings ratio. Beyond fundamentals, you'll find technical analysis from experts, news, historical trends, and predictors - all available in Our Servlogin Webpage.

    ReplyDelete
  54. No One Knows How Many Links Are Required To Rank On The First Page Of Google, But It's Safe To Say That There Are A Lot. We Will Do All The Work For You, Including The Tedious Forex Broker Keyword Analysis Process, For A Reasonable Price. We'll Make Sure That You Have A Complete List Of Links, Both Old And New, To Keep Your Site's Rankings High.

    ReplyDelete
  55. If you trade forex having a broker is an essential part of the process. There are many alternatives in the open market to choose from, but finding one that suits your investing style and plus your requirements can be hard. Iforexs have put together a guide to help you choose the best broker available and match it with your needs.

    ReplyDelete
  56. Iforexs Is Here To Bring You A Solution For All Your Brokerage Research Needs. We've Compiled And Reviewed The Top Over 60+ Forex Brokers That Are Independently Rated And Reviewed By Trusted Forex Traders From All Over The World. Without Having To Spend An Eternity Online Researching, You Can Focus On Other Important Aspects Of Trading Instead!

    ReplyDelete
  57. Iforexs is an online forex broker review and comparison site. We select and compare the best online forex brokers to help you choose the forex platform that's right for you. Whether you're looking for the cheapest forex trading platform or the one with the best educational resources, we can help you find it with ease.

    ReplyDelete
  58. Forex Search Engine Optimization Company You Can Use Link Building Services To Increase The Visibility Of Your Website. The Service Is An Affordable And Long-term Solution To Help Your Site Rank Higher In Search Engine Results. Link Building Services Use A Variety Of Strategies To Help Your Site Rank Higher. One Such Strategy Is To Create Backlinks To Your Site. The Link Building Service Will Create And Place Links On Websites That Are Relevant To Your Business And Industry. This Helps Your Site Rank Higher In Search Engine Results And Increases The Likelihood Of Potential Customers Finding Your Site.

    ReplyDelete
  59. Tradingzy Is The Best And Most Reliable Seo Company And Offers A Wide Variety Of Crypto Seo Services , Including An Affordable Monthly Subscription Service, One-time Links, And Blog Comments. With Any Of These Services, You Can Be Assured That Your Site Will Rank Higher In The Search Engine Results Page And Receive An Influx Of Targeted Traffic.

    ReplyDelete
  60. As a new forex trader you need to know what the best brokers offers and their Forex Marketing before you begin trading and investing, Use this guide to learn about trading costs, leverage and leverage limits, spreads and execution times, custodial services and market maker spreads .

    ReplyDelete
  61. As a new forex trader you need to know what the best brokers offers and their White Label Forex Broker Cost before you begin trading and investing, Use this guide to learn about trading costs, leverage and leverage limits, spreads and execution times, custodial services and market maker spreads .

    ReplyDelete
  62. webgirls In relation to preventing infections, sufferers often times have their work reduce for these people. It is because yeast infections can easily come to be chronic and ongoing. With that in mind, on this page, we will present a variety of some of the best proven yeast infection remedy and reduction ideas around.

    ReplyDelete
  63. webgirls With regards to preventing yeast infections, affected individuals often times have their function remove for them. The reason being yeast infections can certainly grow to be persistent and continuous. Bearing that in mind, in this post, we are going to provide a wide range of some of the best proven candida remedy and prevention ideas about.

    ReplyDelete
  64. https://gamebegin.xyz You may exercise by itself. A pitching device permits you to established the rate of your ball. By packing several baseballs in the unit, you can practice hitting without needing a pitcher. This electrical equipment is perfect for individuals who want to process baseball on your own. Pitching models could be acquired at the community wearing goods retail store.

    ReplyDelete
  65. https://gamezoom.xyz Acquiring a workout lover can considerably improve your muscle-creating outcomes. Your lover can be quite a important way to obtain inspiration for sticking with your exercise routine program, and pushing you to definitely increase your efforts while you work out. Possessing a reliable spouse to determine with can also help help you stay safe since you will always use a spotter.

    ReplyDelete
  66. https://gameboot.xyz The truth is them on periodicals and on Television, men and women who appear to be their hands and thighs will explode as his or her muscle groups are so massive! There is no need that you should get your body to that degree when you don't wish to, since the simple strategies on this page will help you develop muscle tissue inside a healthy manner.

    ReplyDelete
  67. Best MT5 Forex Broker Philippines Get Information On The Best Forex Brokers In Philippines. Read Reviews, Compare The Best Trading Platforms, & Find The Right Broker ForYou.

    ReplyDelete
  68. Harrah's Resort Atlantic City - MapYRO
    Find Harrah's Resort Atlantic City, New Jersey, United States, 광양 출장마사지 United States, ratings, photos, prices, expert advice, traveler 통영 출장안마 reviews and tips, and more information Hotel condition: 진주 출장샵 3.5Room comfort: 3.5 Rating: 3.5 · ‎3 계룡 출장마사지 reviews 대전광역 출장마사지

    ReplyDelete
  69. Would You Like To Access Your IG Review > Account And Manage Your Trades? This Is The Place For You. Here You Can Easily Manage Your Investments, Deposit Or Withdraw Funds. Read More Here.

    ReplyDelete
  70. thank you for taking the duration to proclamation this find the maintain for an opinion totally beneficial! Bandicam Key Generator

    ReplyDelete
  71. remarkable call i might sooner or later to thank you for the efforts you've got made in scripting this tempting and knowledgeable article. ! Girlfriend Birthday Wishes

    ReplyDelete
  72. Great post! I really enjoyed reading about your experience and perspective on this topic. It's refreshing to see someone share their personal insights in such a relatable way.
    Also, check Java Course in Nagpur

    ReplyDelete
  73. This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting.our sclinbio.com

    ReplyDelete
  74. DevOps is the most emerging field in today’s market. DevOps Classes in Pune in simple language is a set of processes that unitedly bring software development through a collaboration of development and operations.

    6
    https://www.sevenmentor.com/devops-training-in-pune.php

    ReplyDelete