<?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 Piotr Chmielowski on Medium]]></title>
        <description><![CDATA[Stories by Piotr Chmielowski on Medium]]></description>
        <link>https://medium.com/@piotr.chmielowski?source=rss-9c23d7f7dcd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k2svD6Mwbpx_ULiA.</url>
            <title>Stories by Piotr Chmielowski on Medium</title>
            <link>https://medium.com/@piotr.chmielowski?source=rss-9c23d7f7dcd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:09:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piotr.chmielowski/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[Singleton is not an anti-pattern]]></title>
            <link>https://medium.com/@piotr.chmielowski/singleton-is-not-an-anti-pattern-51392c3e508e?source=rss-9c23d7f7dcd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/51392c3e508e</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Piotr Chmielowski]]></dc:creator>
            <pubDate>Sun, 27 May 2018 13:14:06 GMT</pubDate>
            <atom:updated>2018-05-27T13:14:06.240Z</atom:updated>
            <content:encoded><![CDATA[<p>The usage of the singleton pattern is very often considered as a bad practice.<br>In this article I’ll try to convince you that is not.</p><p>There are two main arguments against this pattern, let’s discuss them one by one.</p><h3>Argument 1. Code that uses singletons is hard to test</h3><p>Indeed, testing following method in isolation is nearly impossible:</p><pre>void login(String user, String password) {<br>  try {<br>    <strong>UserManager.getInstance()</strong><br>               .login(user, password);<br>    showMessage(“Login successful”);<br>  } catch (InvalidPasswordException e) {<br>    showMessage(“Wrong password”);<br>  }<br>}</pre><p>However, is it hard to test because UserManager is a singleton? I don’t think so. Let’s make it ordinary, non-singleton class and check if testing is easier:</p><pre>void login(String user, String password) {<br>  try {<br>    <strong>new UserManager()</strong><br>        .login(user, password);<br>    showMessage(“Login successful”);<br>  } catch (InvalidPasswordException e) {<br>    showMessage(“Wrong password”);<br>  }<br>}</pre><p>As you can see, from the testability point of view, nothing has changed (maybe now the situation is even worse because with the first snipped we were able to inject mocked class with some dirty trick…).</p><p>There is only one correct technique to refactor our login() method to be more testable —<strong> dependency injection</strong>. For the sake of simplicity I’ll inject UserManager as a method parameter, however in the real world application I’d probably inject it in the class which the login() method is part of:</p><pre>void login(String user, String password, <strong>UserManager manager</strong>) {<br>  try {<br>    <strong>manager</strong>.login(user, password);<br>    showMessage(“Login successful”);<br>  } catch (InvalidPasswordException e) {<br>    showMessage(“Wrong password”);<br>  }<br>}</pre><p>Now, from the testability point of view, there is really no difference in production code if UserManager is a singleton or not:</p><pre>login(<br>    <a href="/service/mailto:jane.doe@domain.com">&quot;jane.doe@domain.com</a>&quot;, &quot;dolphins&quot;, <strong>UserManager.getInstance()<br></strong>);<br>login(<br>    <a href="/service/mailto:jane.doe@domain.com">&quot;jane.doe@domain.com</a>&quot;, &quot;dolphins&quot;, <strong>new UserManager()<br></strong>);</pre><p>Of course, now the method which makes the call to login() is untestable.</p><p>We have to perform the same refactoring steps as before and end with the situation where call to UserManager’s constructor or static getInstance() method is performed only on the top level of our dependency graph (main() method for example).</p><h3>Argument 2. Mutable singleton is just a mutable global variable</h3><p>This is true. However it is hard for me to fully agree with the statement: <em>global mutable state is evil</em>. In my opinion, it just a half-truth. The full one is:</p><blockquote>a mutable state is always problematic, <strong>the bigger the scope is, the more problems we can encounter</strong></blockquote><p>Let me illustrate it. This is saying <em>mutable state is kinda OK, global mutable state is evil</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*rwiHH3z-JPY3x3VVr1s_cA.png" /></figure><p>And this is what I believe: <em>mutable state is always problematic. Singleton is not a special case</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*BJFYGwCnTrtsERMrCYhVgQ.png" /></figure><p>Of course, as you can see on the second picture, singleton indeed is an extreme case.<br>However I’d like to emphasize that singleton pattern is not the only one that I’d put on the far-right on the axis: I’d put there <strong>every class which has a application scope</strong> — even if it does not implement the singleton pattern.</p><p>In the other words — if you create one instance of a mutable non-singleton class (by calling its constructor) and inject it everywhere, be aware that you may have problems with reasoning about current state.</p><p>Moreover, if you create two instances of this class and inject one of them in ten places and second one in another five — you still have to be careful about all side effects of mutating the state.</p><h3>Conclusion</h3><p>Let’s summarize quickly my opinion about the singleton. There is nothing wrong with the pattern itself — it is just a technique for making sure that there is only one instance of the class.</p><p>All the problems which are often being mentioned during discussions on singletons are kind of independent from the pattern itself:</p><ul><li>testability problems are caused just by the lack of dependency injection</li><li>mutability is an orthogonal problem: even if you are not using singleton pattern, you can have problems with mutable state. <br>However you can also have many singletons in your code base but keep most of the classes immutable and your code would be very easy to reason about.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51392c3e508e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Really simple introduction to Dagger2 — part 2— field injection and modules]]></title>
            <link>https://medium.com/@piotr.chmielowski/really-simple-introduction-to-dagger2-part-2-field-injection-and-modules-aba78dda4737?source=rss-9c23d7f7dcd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba78dda4737</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Piotr Chmielowski]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 23:06:39 GMT</pubDate>
            <atom:updated>2017-11-21T23:07:24.403Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@piotr.chmielowski/really-simple-introduction-to-dagger2-b45ba00c0b98">In the previous post</a> I’ve introduced the very basics of Dagger framework. Now, I’d like to introduce two important concepts: field injection and modules.</p><h4>Field injection</h4><p>In the previous part, we have been treating the component as a class with the factory method called getBike:</p><pre>BikeComponent factory = DaggerBikeComponent.<em>create</em>(); <br>Bike bike = factory.getBike();</pre><p>In many cases fetching objects from component directly is not the best solution. Instead of asking “give me a bike”, we can use another approach: ask “hey, I have a member with the type Bike, please set its value”. It is the common pattern in the Android world, for example in Activity classes.</p><p>First, take a look at the Activity with the first approach:</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>AppCompatActivity {<br><br>    Bike <strong>bike</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_main</em></strong>);<br><br>        <strong>bike </strong>= DaggerBikeComponent.<em>create</em>().getBike();<br>        <strong>bike</strong>.ride();<br>    }<br>}</pre><p>Compare it with the second one:</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>AppCompatActivity {<br><br>    @Inject<br>    Bike <strong>bike</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_main</em></strong>);<br><br> <em>       </em>DaggerBikeComponent.<em>create</em>().inject(<strong>this</strong>);<br>        <strong>bike</strong>.ride();<br>    }<br>}</pre><p>Notice two changes:</p><ul><li>field bike is annotated with the Inject annotation</li><li>we are not getting bike directly, instead, the inject method was created</li></ul><p>Now our component looks like:</p><pre>@Component<br><strong>interface </strong>BikeComponent {<br>    // before was: Bike getBike();<br>    <strong>void </strong>inject(MainActivity activity);<br>}</pre><p>So, the inject could be called “find all my fields with the Inject annotation and set its values with the object you create”. The Inject annotation in this context is the message “set me a value”.</p><p>By the way, calling following code in the onCreate of Activity:</p><pre>DaggerBikeComponent.<em>create</em>()</pre><p>…is a bad practice. I have wrote it this way to keep this tutorial simple, but in the real world, you have to take care of keeping one instance during whole application live. Simply start with creating one in onCreate method of the custom Application class. (Sometimes component lifecycle has to be shorter than application’s one — but don’t worry you’ll learn it in the future)</p><h4>Modules</h4><p>The second concept, I’d like to show you is the Module. In the previous article, I’ve added the Inject annotation to constructor of each object in our dependency graph:</p><pre><strong>class </strong>FrontWheel {<br>    @Inject<br>    FrontWheel(Tire tire) {<br>    }<br>}<br><br><strong>class </strong>Saddle {<br>    @Inject<br>    Saddle() {<br>    }<br>}</pre><p>But let’s assume, than from now, the constructor of Saddle class needs the instance of Boolean object:</p><pre><strong>class </strong>Saddle {<br>    @Inject<br>    Saddle(Boolean aBoolean) {<br>    }<br>}</pre><p>How can Dagger know how to create the instance of Boolean? This class is a part of the library so we can not modify it by adding Inject annotation to the constructor (and, as you remember, this annotation tells “If someone need my instance, use this constructor”).</p><p>We have to tell Dagger explicitly how we want it to create a Boolean instance.</p><p>The right tool to use is the module. First create BikeModule — the class with the recipe “how to create Boolean if someone needs it”:</p><pre>@Module<br><strong>class </strong>BikeModule {<br><br>    @Provides<br>    Boolean provideBoolean() {<br>        <strong>return new </strong>Boolean(<strong>true</strong>);<br>    }<br>}</pre><p>Notice two annotations: Provides tells Dagger “here is the recipe”, while Module says “I’m the collection of recipes”. The name of provideBoolean method is not important — we can choose any name we want.</p><p>The second and last step is to connect the component with the module. It’s quite simple:</p><pre>@Component(modules = BikeModule.<strong>class</strong>)<br><strong>interface </strong>BikeComponent {<br>    <strong>void </strong>inject(MainActivity activity);<br>}</pre><p>The only difference is annotation’s parameter.</p><p>And that’s all. Now you know the three most important Dagger’s parts: Component, Module and the Inject annotation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba78dda4737" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Really simple introduction to Dagger2 — part 1 — basics]]></title>
            <link>https://medium.com/@piotr.chmielowski/really-simple-introduction-to-dagger2-b45ba00c0b98?source=rss-9c23d7f7dcd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45ba00c0b98</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Piotr Chmielowski]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 22:17:53 GMT</pubDate>
            <atom:updated>2017-11-26T16:11:35.425Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a very gentle introduction to Dagger2 framework. It is aimed for the beginners and it is exactly the text I wish I had read when I was starting with Dagger one year ago.</p><p>First, I’ll show you how to solve the dependency injection problem by hand, then we will refactor the code to use Dagger (but, what is important, with the smallest possible number of its pieces).</p><h4>Problem description</h4><p>Let’s assume, we need an instance of the Bike class. We look at its code and see, its constructor needs few other objects:</p><pre>Bike(RearWheel rearWheel, FrontWheel frontWheel, Saddle saddle, HandleBar handleBar, Frame frame) {<br>  // ...<br>}</pre><p>We dig further and realize, that Frame’s constructor also has few dependencies:</p><pre>Frame(TopTube topTube, DownTube downTube, SeatTube seatTube) {<br>  // ...<br>}</pre><h4>Let’s solve it manually</h4><p>Five minutes of work and the factory class is created:</p><pre><strong>class </strong>BikeFactory {<br>    Bike getBike() {<br>        <strong>return new </strong>Bike(<br>                <strong>new </strong>RearWheel(<strong>new </strong>Tire()),<br>                <strong>new </strong>FrontWheel(<strong>new </strong>Tire()),<br>                <strong>new </strong>Saddle(),<br>                <strong>new </strong>HandleBar(),<br>                <strong>new </strong>Frame(<strong>new </strong>TopTube(), <strong>new </strong>DownTube(), <strong>new </strong>SeatTube())<br>        );<br>    }<br>}</pre><p>We can use it in a very simple way:</p><pre><strong>new </strong>BikeFactory().getBike().ride();</pre><p>It wasn’t hard but is not trivial to maintain and expand in the future. Moreover — imagine more complicated dependency tree.</p><p>There is an alternative to building object manually.</p><h4>Let’s use Dagger</h4><p>OK, so what can Dagger do for us? The answer is: it can generate the whole getBike() factory method. Let’s check it!</p><p>First, we have to create an interface of the factory class:</p><pre>@Component<br><strong>interface </strong>BikeComponent {<br>    Bike getBike();<br>}</pre><p>Notice two things: I’ve added the Component annotation — it tells Dagger “Hey, this interface wants to be factory! Create the implementation for it!” (its a simplification, because component can have more powers than just being a factory), I’ve also changed the name from BikeFactory to BikeComponent — it is just a common practice in the Dagger world.</p><p>The second step is to annotate each constructor of our dependency with the Inject annotation:</p><pre><strong>class </strong>Frame {<br>    @Inject<br>    Frame(TopTube topTube, DownTube downTube, SeatTube seatTube) {<br>    }<br>}<br><br><strong>class </strong>TopTube {<br>    @Inject<br>    TopTube() {<br>    }<br>}</pre><p>It tells Dagger “Hey, if someone asks for me, use this constructor”.</p><p>The very last step is to let Dagger create the instance of real component:</p><pre><strong>// without Dagger<br>new </strong>BikeFactory().getBike().ride();</pre><pre>// with Dagger<br>DaggerBikeComponent.<em>create</em>().getBike().ride();</pre><p>I’m sure you are asking right now: what is this DaggerBikeComponent class? This is the generated one. You may have to build the project to let it be generated. It contains the implementation of getBike() method — a similar to the one from BikeFactory class.</p><p>So, as you can see, Dagger has resolved all dependencies and generated method which can create whole graph of dependency — and we haven’t written any “new” operator!</p><p>And that’s all! Congratulations, now you know how to use Dagger at a basic level.</p><p>Of course, there are much more concepts to know in order to be a fluent Dagger user, such as field injection or module. You can read about them in<a href="https://medium.com/@piotr.chmielowski/really-simple-introduction-to-dagger2-part-2-field-injection-and-modules-aba78dda4737"> the second part of the guide.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45ba00c0b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>