<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sankalp Bhatia on Medium]]></title>
        <description><![CDATA[Stories by Sankalp Bhatia on Medium]]></description>
        <link>https://medium.com/@sankalpbhatia?source=rss-58630b928d85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vQCGZz5v6U7Bzkgo6-gctQ.jpeg</url>
            <title>Stories by Sankalp Bhatia on Medium</title>
            <link>https://medium.com/@sankalpbhatia?source=rss-58630b928d85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:26:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sankalpbhatia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A hands-on session with Google Guice]]></title>
            <link>https://medium.com/free-code-camp/a-hands-on-session-with-google-guice-5f25ce588774?source=rss-58630b928d85------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f25ce588774</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sankalp Bhatia]]></dc:creator>
            <pubDate>Tue, 30 Oct 2018 16:50:05 GMT</pubDate>
            <atom:updated>2018-10-30T16:50:05.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TUa3fApD5vZpVB7-d7mTaw.jpeg" /></figure><p>A few months ago, I wrote <a href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536">an article</a> explaining dependency injection. I had mentioned of a follow-up article with a hands-on session of Google Guice. While I am disappointed in being so late in writing this, part of me is happy that I was able to write a second article.</p><p>This article assumes that you are familiar with what dependency injection is. I would recommend you to glance through <a href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536">my previous article</a> as we will be building upon the examples we used there. If you are hearing the term for the first time, it will be worth it. If you are familiar with it, reading it won’t take much time :)</p><p>If you haven’t worked much with Guice, please check it out on GitHub <a href="https://github.com/google/guice">here</a>.</p><p>We will need to set up a few things before we start</p><ol><li><strong>JDK</strong>: We will be using Java for this task. So you will need to have a working JDK to be able to run Java code in your computer. To check if it’s already installed, run ‘java -version’ on the command line. If the version is 1.6 or greater, we are good. Just a note: I don’t think it would make much sense to attempt this if you don’t have experience with Java<em>.</em></li><li><strong>Maven</strong>: We will be using maven as a build tool. To install maven, follow the instructions here <a href="https://maven.apache.org/install.html">https://maven.apache.org/install.html</a> (Quite easy). To check if you already have maven, run ‘mvn -v’ on the command line.</li><li><strong>git</strong> (optional): <a href="https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/">https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/</a></li><li><strong>clone the hands on repository (FreshGuice)</strong>: Run commands mentioned below</li></ol><pre>cd folder/to/clone-into/ <br>git clone <a href="https://github.com/sankalpbhatia/FreshGuice.git">https://github.com/sankalpbhatia/FreshGuice.git</a></pre><h3>Bindings and Binding Annotations</h3><p>We are ready now. Let me start by introducing two crucial terms in the Guice framework: <strong>Bindings and Binding Annotations.</strong></p><p><strong>Bindings:</strong> being the core concept of Guice, in literal terms, means an agreement or promise involving an obligation that cannot be broken. Now let’s map it in the context of Dependency Injection. When we make Guice <em>bind</em> an instance with a class, we make an agreement with Guice that “When I ask for an instance of X.java, give me this instance”. And this agreement can’t be broken.</p><p><strong>Binding Annotations: </strong>Occasionally you’ll want multiple bindings for the same type. The annotation and (class) type together uniquely identify a binding. For example, in some cases, you might need two separate instances of the same class/ implementation of the same interface. To identify those, we use binding annotations. We will see some examples when we explain bindings.</p><h4><strong>How to create bindings</strong></h4><p>The user guide section of Guice explains it perfectly. So I will just be copying it here:</p><blockquote>To create bindings, extend AbstractModule and override its configure method. In the method body, call bind() to specify each binding. These methods are type checked so the compiler can report errors if you use the wrong types. Once you&#39;ve created your modules, pass them as arguments to Guice.createInjector() to build an injector.</blockquote><p>There are a number of types of bindings: Linked, Instance, @Provides annotation, Provider bindings, Constructor bindings, and Un-targeted bindings.</p><p>For this article, I will only be covering Linked Bindings, Instance Bindings, @Provides annotation, and a special annotation @Inject. I very rarely use any other means to bind, but more information can be found at <a href="https://github.com/google/guice/wiki/Bindings">https://github.com/google/guice/wiki/Bindings</a>.</p><ol><li><strong>Linked Binding:</strong> a Linked binding maps a type/interface to its implementation. This example maps the interface MessageService to its implementation EmailService.</li></ol><p>In plain terms: When I ask Guice to give me an instance of MessageService, it will give me an instance of EmailService.</p><p><em>But, how will it know to create an instance of EmailService</em>? We’ll see that later.</p><pre>public class MessagingModule extends AbstractModule {<br>  @Override <br>  protected void configure() {<br>    bind(MessageService.class).to(EmailService.class);<br>  }<br>}</pre><p>Maybe we want more than one instance of MessageService in our project. At some places, we would want a SMSService to be associated with a MessageService, rather than an EmailService. In such cases, we use a binding annotation. To create a binding annotation, you will have to create two annotations like so:</p><pre>@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)<br>public @interface Email {}</pre><pre>@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)<br>public @interface SMS {}</pre><p>You need not know about the metadata annotations (@Target, @ Retention). If interested, please read this: <a href="https://github.com/google/guice/wiki/BindingAnnotations">https://github.com/google/guice/wiki/BindingAnnotations</a></p><p>Once we have the annotations with us, we can create two separate bindings which instruct Guice to create different instances of MessageService based on the BindingAnnotation (I think of it as a qualifier).</p><pre>public class MessagingModule extends AbstractModule {<br>  @Override <br>  protected void configure() {<br>   bind(MessageService.class).annotatedWith(Email.class)<br>                             .to(EmailService.class);</pre><pre>   bind(MessageService.class).annotatedWith(SMS.class)<br>                             .to(SMSService.class);  }<br>}</pre><p>2. <strong>Instance Binding:</strong> Binds a type to a specific instance</p><pre> bind(Integer.class)<br> .annotatedWith(Names.named(“login timeout seconds”))<br> .toInstance(10);</pre><p>One should avoid using .toInstance with objects that are complicated to create, since it can slow down application startup. You can use an @Provides method instead. In fact, you can even forget that we mentioned anything about Instance binding right now.</p><p>3. <strong>@ Provides annotation</strong>:</p><p>This is straight from Guice’s wiki, as it is fairly simple:</p><blockquote>When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method&#39;s return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.</blockquote><pre>bind(MessageService.class)</pre><pre>.annotatedWith(Email.class)</pre><pre>.to(EmailService.class);</pre><p>is same as</p><pre>@Provides<br>@Email<br>public MessageService provideMessageService() {<br>  return new EmailService();<br>}</pre><p>where Email.java is a Binding annotation.</p><p>Dependencies can be passed to a method with this annotation which makes it extremely useful in real life projects. For example, for the code mentioned below, the injector will exercise the binding for the string parameter <strong><em>apiKey </em></strong>before invoking the method.</p><pre>@Provides <br>@PayPal<br>CreditCardProcessor providePayPalCreditCardProcessor(<br>      @Named(&quot;PayPal API key&quot;) String apiKey) {<br>  PayPalCCProcessor processor = new PaypalCCProcessor();<br>  processor.setApiKey(apiKey);<br>  return processor;<br>  }</pre><p>4. <strong>@ Inject annotation</strong> (Just in Time binding): Whatever we covered up until now are called <em>explicit bindings. </em>If Guice, when trying to create an instance, does not find an explicit binding, it tries to create one using a Just-in-time binding.</p><p>Guice can create these bindings by using the class’s <em>injectable constructor</em>. This is either a non-private, no-arguments constructor or a constructor with the @Injectannotation.</p><h3>Task</h3><p>Now let’s move to the project we cloned from Github.</p><p>Like the examples in the<a href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536"> previous article</a>, this maven project implements a BillingService which charges a PizzaOrder using a credit card and generates a Receipt.</p><p>The project structure is as follows:</p><p><strong>Interfaces</strong></p><ul><li>BillingService — charges an order using a credit card</li><li>CreditCardProcessor — debits some amount from a credit card</li><li>TransactionLog — logs results</li></ul><p><strong>Classes</strong></p><p>src</p><ul><li>CreditCard — entity representing a Credit Card</li><li>PizzaOrder — entity representing a Pizza order</li><li>Receipt — entity representing a receipt</li><li>RealBillingService implements BillingService</li><li>PaypalCreditCardProcessor implements CreditCardProcessor</li><li>BankCreditCardProcessor implements CreditCardProcessor</li><li>InMemoryTransactionLog implements TransactionLog</li><li>GuiceTest — Main class which uses BillingService</li><li>BillingModule — All Guice bindings go here</li><li>GuiceInjectionTest : Unit tests to check binding constraints</li></ul><p>The task here is to create Guice Bindings in the BillingModule such that the following constraints are satisfied:</p><ol><li>All implementations of BillingService should be bound to RealBillingService.</li><li>CreditCardProcessor interface annotated with @Paypal should be bound to PaypalCreditCardProcessor class.</li><li>CreditCardProcessor interface named with string “Bank” should be bound to BankCreditCardProcessor class.</li><li>BillingService instances returned by injector should have an instance of BankCreditCardProcessor as their dependency.</li><li>All implementations of TransactionLog should be bound to InMemoryTransactionLog.</li></ol><p>All five unit tests in GuiceInjectionTests should pass if the above conditions are satisfied. You should also be able to run the main method in GuiceTest.</p><p>To test correctness:</p><ol><li>run unit tests</li></ol><pre>mvn test</pre><p>This should run the test file GuiceInjectionTests.java.</p><p>2. run the main file</p><pre>mvn exec:java -Dexec.mainClass=&quot;GuiceTest&quot;</pre><p>This should execute the main class of the project, which does the end to end work of creating an order, processes payment using a credit card and generates a receipt.</p><p>You can comment if you have any questions and I will try answering them. Please note that there is no single correct answer for this exercise. DM me your solutions and I will add the answers to the repository. Or better still, send me a pull request :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f25ce588774" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/a-hands-on-session-with-google-guice-5f25ce588774">A hands-on session with Google Guice</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystify Dependency Injection and see it in action with this quick intro]]></title>
            <link>https://medium.com/free-code-camp/demystifying-dependency-injection-49d4b6fe6536?source=rss-58630b928d85------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d4b6fe6536</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Sankalp Bhatia]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 17:42:44 GMT</pubDate>
            <atom:updated>2018-04-26T23:18:17.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnStARpFrN-7liCbeUKXRw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ALMp3vMzPig?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fabien Butazzi</a> on <a href="https://unsplash.com/search/photos/mist?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Dependency Injection (DI) is a topic which I found a little difficult to grasp during my initial days as a software developer. I just could not find a good definition of the term.</p><p>In this article, I’ve tried to put my understandings of it in fairly simple language. It is intended for people starting out with DI, or those who just want to get a little more insight.</p><h3><strong>What is Dependency Injection?</strong></h3><p>First things first: what is it? Dependency Injection, like so much other software development jargon, is a fancy term for a rather simple concept.</p><p>The definition which I found most useful is:</p><p><strong><em>Dependency injection means giving an object its instance variables.</em></strong></p><p>That’s it. Providing (injecting) dependencies for a class. Simple right? Indeed.</p><p>Now, there are three ways of providing a class its dependencies in Java. All of them achieve…(coughs) Dependency Injection.</p><p>They are:</p><ul><li>Constructors</li><li>Setters</li><li>Directly setting public fields</li></ul><h3>Let’s see Dependency Injection in action</h3><p>I have an application class named MyMessagePublisher which has a dependency on a certain EmailService class.</p><h4><strong>Dependency Injection using Constructor:</strong></h4><pre>public class MyMessagePublisher {<br><br>    private EmailService emailService = null;<br>    <br>    public MyMessagePublisher(EmailService emailService){<br>        this.emailService = emailService;<br>    }<br>}</pre><p>See what the constructor is doing there? It is telling MyMessagePublisher to use the EmailService provided by it. The class instantiating MyMessagePublisher should provide (inject) an EmailService instance (using the constructor) to be used by MyMessagePublisher. Something like this:</p><pre>EmailService emailService = new EmailService();<br>MyMessagePublisher myMessagePublisher = <br>                           new MyMessagePublisher(emailService);</pre><p>Good job, Constructor!</p><h4><strong>Dependency Injection using Setter:</strong></h4><pre>public class MyMessagePublisher {<br>    private EmailService emailService = null;<br><br>    public MyMessagePublisher() {<br>    }<br><br>    public setEmailService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><p>What’s going on here? The class using MyMessagePublisher can now set the EmailService which they want to use. Something like this:</p><pre>MyMessagePublisher myMessagePublisher = new MyMessagePublisher();<br>myMessagePublisher.setEmailService(new EmailService());</pre><p>Good job, Setter!</p><h4><strong>Dependency Injection by directly setting public fields</strong></h4><p>Never do this!! If you have reached this far reading this article, I believe you know that this approach is evil.</p><h3><strong>Benefits of Dependency Injection</strong></h3><p>I’ll start this section by explaining what we miss out on if we do not use DI.</p><p>Consider this code. I have defined the EmailService and MyMessagePublisher classes. MyMessagePublisher itself instantiates an EmailService object instead of using the DI techniques mentioned above.</p><pre>public class EmailService {<br>        public void sendEmail(String message, String receiver){<br>        System.out.println(&quot;Email sent to &quot; + receiver);<br>    }<br>}</pre><pre>public class MyMessagePublisher {<br>    private EmailService emailService = new EmailService();<br>    public void processMessages(String message, String receiver){<br>        this.emailService.sendEmail(message, receiver);<br>    }<br>}</pre><p>The above code has some limitations:</p><ol><li>If EmailService initialization logic changes (it takes a constructor parameter to initialize), we would need to make changes to MyMessagePublisher class along with everywhere else in the codebase where we are using EmailService without DI.</li><li>It has tight coupling. Let’s say we want to move away from sending emails and instead start sending SMSs. We will then have to write a new publisher class.</li><li>This code is not testable. We will be sending emails to everyone while unit testing MyMessagePublisher class.</li></ol><p>This is the solution I propose:</p><pre>public class EmailService implements MessageService {<br>    @Override<br>    public void sendMessage(String message, String receiver) {<br>        //logic to send email<br>    }<br>}</pre><pre>public class SMSService implements MessageService {<br>    @Override<br>    public void sendMessage(String message, String receiver) {<br>        //logic to send SMS<br>    }</pre><pre>public interface MessageService {<br>    void sendMessage(String message, String receiver);<br>}</pre><pre>public class MyMessagePublisher {<br><br>    private MessageService messageService;<br>    <br>    public MyMessagePublisher(MessageService messageService){<br>        this.messageService = messageService;<br>    }<br>    <br>    @Override<br>    public void processMessages(String msg, String rec){<br>        this.service.sendMessage(msg, rec);<br>    }<br><br>}</pre><p>This implementation overcomes all three limitations mentioned above.</p><ul><li>EmailService (or MessageService) initialization logic moves to the module initializing MyMessagePublisher</li><li>We can move to a different implementation of MessageService which sends SMS without changing code in MyMessagePublisher</li><li>The code is testable. We can use a dummy implementation of MessageService while unit testing MyMessagePublisher</li></ul><p>Sweet. We have achieved DI using Constructors of our classes. Easy right? But there are some shortcomings here as well.</p><h3>Issues with Vanilla Dependency Injection</h3><p>When does this become a problem? <strong>When the code grows</strong>.</p><p>So what are the alternatives? <strong>Dependency Injection Containers </strong>(Spring, Guice, Dagger, and so on).</p><p>Let’s try to answer the questions above in more detail.</p><p>Consider the code below. We are designing an AllInOneApp which offers multiple services like booking movie tickets, recharging prepaid connections, transferring money, and online shopping.</p><pre>public class BookingService {<br>    private SlotsManager slotsManager;<br>    private MyMessagePublisher myMessagePublisher; //Looks familiar?<br>}</pre><pre>public class AllInOneApp  {<br>    BookingService bookingService; // Class above<br>    RechargeService rechargeService;<br>    MoneyTransferService moneyTransferService;<br>    ShoppingService shoppingService;<br>}</pre><p>AllInOneApp needs four dependencies to be initialized. Let’s use vanilla Dependency Injection using Constructor here and instantiate the AllInOneApp class.</p><pre>public static void main(String[] args) {</pre><pre>AllInOneApp allInOneApp = new AllInOneApp(<br>                new BookingService(new SlotsManager(),<br>                                   new MyMessagePublisher(<br>                                              new EmailService())), <br>                new RechargeService(...), <br>                new MoneyTransferService(..),<br>                new ShoppingService(...));</pre><pre>}</pre><p>This looks messy. Can we identify the problems here? A couple of them are:</p><ul><li>The class initializing AllInOneApp needs to know the logic to construct all the dependency classes as well. This is cumbersome when writing code in any decent sized project. Managing all these instances by ourselves is not what we want to do while writing business specific code.</li><li>Although I have seen people prefer this kind of DI, I personally believe this code is less readable as compared to this:</li></ul><pre>AllInOneApp myApp = SomeDIContainer.getInstance(AllInOneApp.class);</pre><p>If all the components use DI, somewhere in the system some class or factory must know what to inject into all these components (AllInOneApp, BookingService, MessageService etc).</p><p><strong>This is where Dependency Injection containers come into picture</strong>. It is called a container and not a factory because the container often takes on more responsibility than just instantiating objects and injecting dependencies.</p><p>DI containers let us define what components are to be initiated and what dependencies to be injected in those components. We can also configure other instantiation features, like the object being a singleton or getting created every time it is requested.</p><p>I will be writing another article explaining the usage of one of the popularly used DI Containers, Google Guice, which will have a hands on practice section as well. I will update this story with it’s link soon. I will now leave you with this <a href="https://github.com/google/guice/wiki/GettingStarted">user guide</a> which is a good place to start.</p><p>Thank you for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d4b6fe6536" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/demystifying-dependency-injection-49d4b6fe6536">Demystify Dependency Injection and see it in action with this quick intro</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>