<?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 Amit Kumar on Medium]]></title>
        <description><![CDATA[Stories by Amit Kumar on Medium]]></description>
        <link>https://medium.com/@amitkma?source=rss-4586b66ac140------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*27sulFcHQuOu_SYO.jpg</url>
            <title>Stories by Amit Kumar on Medium</title>
            <link>https://medium.com/@amitkma?source=rss-4586b66ac140------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:26:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitkma/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[Understanding Inversion of Control (IoC) Principle]]></title>
            <link>https://medium.com/@amitkma/understanding-inversion-of-control-ioc-principle-163b1dc97454?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/163b1dc97454</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 15:18:54 GMT</pubDate>
            <atom:updated>2019-08-20T15:18:54.004Z</atom:updated>
            <content:encoded><![CDATA[<p>The biggest issue, any enterprise app can face is the complexity of wiring different elements or components together. Over a long period of time, a number of frameworks have been created to provide a facility to assemble and bind these elements from different layers. These frameworks are commonly known as <strong>Containers</strong> and some of the very popular examples of such frameworks are <strong>PicoContainer</strong> and <strong>Spring</strong>. There are various interesting design principles used inside these containers and Inversion of Control is one such principle. In this article, we will understand what Inversion of Control exactly is and how it is used in a modern-day enterprise application.</p><h3>What is IoC???</h3><p>As the name suggests, Inversion of Control <strong>Principle </strong>(it’s a principle, not a design pattern) is basically about inverting the control flow of a program. This term was popularized by Stefano Mazzocchi in a defunct Apache Software Foundation project, <a href="https://en.wikipedia.org/wiki/Apache_Avalon">Avalon</a>, then further popularized in 2004 by <a href="https://en.wikipedia.org/wiki/Robert_Cecil_Martin">Robert C. Martin</a> and <a href="https://en.wikipedia.org/wiki/Martin_Fowler_(software_engineer)">Martin Fowler</a>.</p><p>As Martin Fowler said, “<em>Inversion of control is a common characteristic of frameworks, so saying that these lightweight containers (spring and pico container, etc.) are special because they use inversion of control is like saying my car is special because it has wheels.</em>” It is basically a defining characteristic of a framework. Inversion of Control is used to increase the modularity of the program and makes it extensible. But the question still is, “<strong>What aspect of control are they really inverting?</strong>”</p><p>In early days of computer software, the command-line was used for general programs and thus those user interfaces were controlled by the application itself. In such programs, you directly control the flow of the program by entering the response into the command-line but in the GUI program, you basically hand over the control to the window system (UI framework) which then decides what to do next. Here the main control of the program moved away from you to the UI framework. Inversion of Control is a key part of what makes a framework different from a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client whereas a framework does some work for you, you just need to plug your behavior into some places by either by subclassing or by plugging into your own classes. Then framework will call your code when it is required.</p><p>Note: Do not confuse it with “<a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle"><strong>Dependency Inversion Principle</strong></a>”. DIP is a completely different principle which also does the job of providing loose coupling between classes and inverting the flow of dependencies. (Will write an article on it soon.)</p><h3>Implementation Techniques</h3><p>Let’s now discuss how Inversion of Control can be implemented in the various programs. There are several basic design patterns which are used to implement IoC in object-oriented programming.</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Service_locator_pattern">service locator pattern</a></li><li>Using <a href="https://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> pattern</li><li>Using a contextualized lookup</li><li>Using <a href="https://en.wikipedia.org/wiki/Template_method_design_pattern">template method design pattern</a></li><li>Using <a href="https://en.wikipedia.org/wiki/Strategy_design_pattern">strategy design pattern</a></li></ul><p>In all of the above patterns, Service Location (SL) and Dependency Injection (DI) are the most widely used patterns. In this article, we will understand the difference between DI and SL. In the further article of this series, we will look into these patterns deeply and learn how to write such patterns. Don’t confuse SL and DI, they both are completely different and the flow of the code too.</p><h3>Let’s take an example</h3><p>To understand Inversion of Control and it’s implementation by using dependency injection and service locator pattern, we take an example, a very simple one. In this following example, we have a component called “Library” which is used to return a list of books authored by a specific author. The code is self-explanatory and very simple for anyone to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f8cb8eb6664d3e294b2de01e28db84/href">https://medium.com/media/52f8cb8eb6664d3e294b2de01e28db84/href</a></iframe><p>It gets all the books from a finder object and then just checks if it is written by a particular author or not. The whole catch here is the finder object and how we basically connect it with the Library component. Reason why we are interested in this finder object is because we want booksAuthoredBy() to be completely independent of the implementation of Finder . This Finder can be remote implementation which fetches books from a server or it can also be a local database implementation which fetches books from a locally stored database. This can easily be done by creating an Interface BookFinder and then providing its implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/577a0459aedeca5075218991ab85a713/href">https://medium.com/media/577a0459aedeca5075218991ab85a713/href</a></iframe><p>So far so good as I know the finder and I know it’s implementation. But we are making it as a framework and it must be extensible and usable by others too. Now think, if you are a college library manager and you want to use this framework for your college but you have your own database of books which is stored on some other server in a different way. You want to provide your own implementation of BookFinder rather than using my implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*cNE3LWNAiYUQsLrAkikA3Q.png" /><figcaption>Simple Dependency Diagram of Framework.</figcaption></figure><p>If you look at the above code and the diagram, you will notice that our Library class depends on both the interface BookFinder and it’s implementation class BookFinderImpl (RemoteBookFinder in the above example). As we are making it as an extensible framework, it would be better it depends only on the interface, not on the implementation details of it. But then how would get the instance to work with??? Now it’s the time to use <strong>Inversion of Control principle</strong> into a real system.</p><p>As mentioned above, there are various ways in which IoC can be implemented and used. Let’s take a look at both <strong>Dependency Injection</strong> and <strong>Service Locator</strong>.</p><h3>Dependency Injection (aka D. I.)</h3><p>The overall idea of Dependency Injection is to have a separate object, an <strong>Assembler </strong>which can then populate various fields by different instances or implementation by injecting those into the class. Now our dependency diagram looks like this -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*wGcXvIuP9QYkVKlh17DcGA.png" /><figcaption>Dependency Diagram after using DI pattern.</figcaption></figure><p>It can be seen that now our Library class only depends on BookFinder i.e. the interface. The internal implementation of the Assembler is out of the scope of this article and will be discussed in the next part of this article. There are three styles popular for doing DI in such frameworks.</p><ul><li>Constructor Injection</li><li>Setter Injection</li><li>Interface Injection</li></ul><h4>Setter and Field Injection using Dagger</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a90dbf5b2b99cf8de6f8cb32b4da238/href">https://medium.com/media/7a90dbf5b2b99cf8de6f8cb32b4da238/href</a></iframe><p>In the above code snippet, you will see that class Library doesn’t know anything about the implementation of interface BookFinder. All work of assembling and providing dependencies is being done by <a href="https://dagger.dev/">Dagger</a> which is a compile-time DI framework for Java &amp; Android. (Internals of Dagger will be discussed in the upcoming articles)</p><h3>Service Locator (aka SL)</h3><p>Dependency Injection (DI) allows us to make our Library extensible so that anyone can provide the suitable implementation of BookFinder based on their needs/use-cases. But DI is not the only way to break this dependency, SL is such another technique to implement Inversion of Control.</p><p>The idea behind a service locator is to have an object that knows how to get all of the services that an application might need. So in our implementation of the Library Framework, Service locator would have a method that returns a BookFinder when one is needed. Now our dependency diagram will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*EfAFtp0lApHhPuQdUfCMDw.png" /><figcaption>Dependency Diagram after using the SL pattern.</figcaption></figure><p>Let’s take a look at how a simple Service Locator can be implemented. In our implementation, we are going to use a single instance of locator class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fda03857c35b005f01be530c3d39b66/href">https://medium.com/media/9fda03857c35b005f01be530c3d39b66/href</a></iframe><h3>Difference between Dependency Injection and Service Locator</h3><p>Though both the approaches solve the fundamental problem of large enterprises applications ie. decoupling the dependencies from each other and in both the cases our application code (class Library) is independent of the correct implementation of the interface BookFinder . However, in the Service Locator pattern, application explicitly requests the dependencies by sending a message to the locator but in Dependency Injection, the dependency just appears without asking explicitly.</p><p>Dependency injection can help make it easier to see what the component dependencies are and it also makes testing easy. With dependency injector, you can just look at the injection mechanism, such as the constructor, and see the dependencies. With the service locator, you have to search the source code for calls to the locator. While doing testing, you can easily provide the mock implementation of your actual classes in DI pattern. There is not much difference between Dependency Injection or Service Locator pattern. So it just depends on your use-case and how well you are familiar with a particular framework. But as Martin Fowler said —</p><blockquote>The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator. So the decision between locator and injector depends on whether that dependency is a problem.</blockquote><p>He then further says that —</p><blockquote>So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.</blockquote><p>That’s all about the Inversion of Control for this article. There are few more topics and detailed articles to come on this topic and I will write them in upcoming days.</p><p>I hope you have enjoyed reading this article and if you do kindly show some ❤ by clapping and sharing it with your fellow devs. Every clap is appreciated and motivates me to write more. Ask any doubt/suggestion/correction in the comment section below or Tag/DM me on twitter.</p><p>Follow me on here to receive further updates related to this and upcoming articles. Follow me on Twitter — <a href="https://twitter.com/iamitkma">https://twitter.com/iamitkma</a>. Thank you very much for reading so far. ❤❤❤ Much love ❤❤❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163b1dc97454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Year working with /e/ Foundation]]></title>
            <link>https://medium.com/@amitkma/one-year-working-with-e-foundation-2cb559b3556?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb559b3556</guid>
            <category><![CDATA[eelo]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[efoundations]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 10:59:28 GMT</pubDate>
            <atom:updated>2019-03-20T11:01:25.694Z</atom:updated>
            <content:encoded><![CDATA[<p>I am Amit Kumar and I have been working with <a href="http://e.foundation/">/e/ Foundation</a> since last year. It’s a non-profit project for the public by the public (open source). It’s been a great experience working with people from different countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*QqF5MGrgPs4TSkorN2GPBw.png" /></figure><h4>How I come to know /e/ Foundation (previously Eelo)?</h4><p>Once I was talking with my friends and we were discussing the Syria and Yemen crisis. We discussed it for 2–3 hours in night but I strongly remembered that neither I or my friend searched anything about it on Internet at that time nor watched any video on Youtube. But to my utter surprise, next morning when I opened <strong>Youtube</strong>, I just saw a video in my recommendations related to Syrian Crisis. I was thinking that maybe I have searched about it so I decided to check my history but there is no instance related to that (neither in Youtube nor in google my-activity). I realised that my phone mic was listening to my conversations and literally listens everything I say (as far as I have discovered so far).</p><p>Then, It was about January’2018 when one person also shared the same experience. At that time, I come to know how companies like Google and Apple track every single data that goes into phone, PC or any other device which uses some OS or service from these companies. And the more unhappy thing for me was that these data is shared with third parties without giving a clear indication to the users. From my location to my voice search, from my web search to my hotel booking, From my emails to my drive storage, Everything was being used by these companies. As a regular user of these services, I used gmail, google drive, google maps, google photos, google voice or literally anything which google provides. Although it doesn’t directly seems a serious concern to a normal user but the kind of manipulation it can do to your thought process is something which everybody should understand.</p><p>So going through all the above experience, Initially I thought to compile my own ROM and remove all such stuffs from that like Google Apps and disable all such permissions or sensors by default (so that my mic won’t hear me again). I started using Mozilla and setup my own sync server on my local machine (because I didn’t want to use any cloud server or such service provider). I started to watch youtube videos in incognito mode because I don’t want to see the same result in my feeds just to suffer from only one type of bias. For my phone, I started using LineageOS with a very minimal set of Google Apps (needed as to use services like Uber and other apps). I was a noob with ROM compilation and completely ungoogling it was a tough task for me. So I started to look for meaningful alternative that provides real solution to such data slavery. I came across one such thing known as <strong>EELO</strong>.</p><h4>What is /e/ (or Eelo)?</h4><blockquote><a href="https://e.foundation/e-story/"><strong>/e/ </strong></a>is a non-profit project, in the public interest. We build open-source mobile operating systems that respect users’ data privacy. We’re an international core team of experienced entrepreneurs, developers and designers, and a growing community of contributors.</blockquote><p>/e/ is started by Gaël Duval, the man who created the successful Mandrake Linux. After launching the crowdfunding campaign, a large number of supporters from different countries came to the front to support such initiative. You can read more about it <a href="https://e.foundation/about-e/">here</a> or you can read articles written by Duval on <a href="https://hackernoon.com/leaving-apple-and-google-my-eelo-odyssey-introduction-d22741f990d7">medium</a>.</p><h4><strong>How I joined /e/?</strong></h4><p>Once I looked about /e/, I was desperately waiting to use it but as It was just started it was not ready to use. I saw that Gaël Duval was looking for developers. I am an Android Developer so I instantly decided to drop a mail and I did. I received a reply from Gaël Duval and then I started to work with /e/.</p><h4>Experience</h4><p>It’s been a year since I started to work /e/ and I can say for sure, It’s really a very great experience. Core team consists of people from different countries. Few of them are from my home country (India). The most inspiring person in the team is Gaël Duval. The kind of knowledge and understanding level he has is very amazing to me. He just keeps on going things and tries to make them easy for the development team to achieve the goals. Every people in team is very helpful and like to share knowledge and skills. Romain Hunault helps me very much with day to day git issues and build server configuration. <br>Overall, I feel very grateful to work with such wonderful team.</p><p>If you read it so far, I would like to Thank you very much. Kindly show some ❤ by tapping on Clap icon and follow me for more such articles and stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb559b3556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Kotlin and Why should you use it?]]></title>
            <link>https://medium.com/@amitkma/what-is-kotlin-and-why-should-you-use-it-3856bc779aa3?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/3856bc779aa3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 06:00:03 GMT</pubDate>
            <atom:updated>2018-08-27T06:00:03.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YK5PLgDKciZ0J66Ilvb9wQ.png" /><figcaption><a href="https://kotlinlang.org/">https://kotlinlang.org</a></figcaption></figure><p><strong>Kotlin</strong> is a <strong>modern programming</strong> language which targets java platform and run on JVM. Although it’s not a very new language but it has become quite popular after <strong>Google</strong> started to support Kotlin as its official language. Kotlin v1.0 developed by <a href="https://www.jetbrains.com/">JetBrains</a> was released way back in <a href="https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/">Feb, 2016</a>. Kotlin is <strong>concise, more expressive than Java, safe, functional, pragmatic and interoperable with Java</strong>.</p><h3>Kotlin Primary Features</h3><p>Kotlin has most of the key features a modern programming language should have. Kotlin is <strong>based on JVM</strong> and aims to provide a safer alternative to Java. Java is an immensely popular language and used in a vast variety of platforms (eg. From embedded systems to Data centers). Kotlin can do most of the work which is done by Java like <strong>building server applications, android applications and running microservices</strong>. It can also be compiled to <strong>JavaScript</strong> which means you can run <strong>Kotlin in Browser</strong>. But here are some of the key traits which are not present in Java</p><h3>1. Expressiveness</h3><p>Kotlin can help you in reducing the amount of boilerplate code that you write, results in saving your time to write <strong>business logic code</strong>.For example, if you are building a mobile application, you will have to write (or at least generate) a <strong>POJO</strong> class like below —</p><pre><strong>public</strong> <strong>class</strong> <strong>Actor</strong> <strong>{</strong><br>    <strong>private</strong> <strong>long</strong> id<strong>;</strong><br>    <strong>private</strong> String name<strong>;</strong><br>    <strong>private</strong> <strong>int</strong> age<strong>;</strong><br>    <strong>private</strong> String url<strong>;</strong><br><br>    <strong>public</strong> <strong>long</strong> <strong>getId()</strong> <strong>{</strong><br>        <strong>return</strong> id<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> <strong>void</strong> <strong>setId(long</strong> id<strong>)</strong> <strong>{</strong><br>        <strong>this.</strong>id <strong>=</strong> id<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> String <strong>getName()</strong> <strong>{</strong><br>        <strong>return</strong> name<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> <strong>void</strong> <strong>setName(</strong>String name<strong>)</strong> <strong>{</strong><br>        <strong>this.</strong>name <strong>=</strong> name<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> <strong>int</strong> <strong>getAge()</strong> <strong>{</strong><br>        <strong>return</strong> age<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> <strong>void</strong> <strong>setAge(int</strong> age<strong>)</strong> <strong>{</strong><br>        <strong>this.</strong>age <strong>=</strong> age<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> String <strong>getUrl()</strong> <strong>{</strong><br>        <strong>return</strong> url<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>public</strong> <strong>void</strong> <strong>setUrl(</strong>String url<strong>)</strong> <strong>{</strong><br>        <strong>this.</strong>url <strong>=</strong> url<strong>;</strong><br>    <strong>}</strong><br><br>    <strong>@Override</strong><br>    <strong>public</strong> String <strong>toString()</strong> <strong>{</strong><br>        <strong>return</strong> &quot;Actor{&quot; <strong>+</strong><br>                &quot;id=&quot; <strong>+</strong> id <strong>+</strong><br>                &quot;, name=&quot; <strong>+</strong> name <strong>+</strong><br>                &quot;, age=&quot; <strong>+</strong> age <strong>+</strong><br>                &quot;, url=&quot; <strong>+</strong> url <strong>+</strong><br>                &quot;}&quot;<strong>;</strong><br>    <strong>}</strong><br><strong>}</strong></pre><p>Imagine if you have 20s or 50s of such <strong>POJO</strong>. It would be difficult to write all those classes and overriding toString(), equals() and hashCode() etc. In <strong>Kotlin</strong>, you just need to use <strong>data class </strong>-</p><pre>data <strong>class</strong> <strong>Actor(</strong><br>        var <strong>id:</strong> Long<strong>,</strong><br>        var <strong>name:</strong> String<strong>,</strong><br>        var <strong>age:</strong> Int<strong>,</strong><br>        var <strong>url:</strong> String<br><strong>)</strong></pre><p>And Kotlin will write all the boilerplate code (<strong>setters</strong>, <strong>getters</strong> and even overrides the <strong>equals()</strong> and <strong>hashCode()</strong>) which makes code less verbose and more expressive.</p><h3>2. Statically Typed</h3><p>Kotlin is a <strong>statically typed language</strong> same as <strong>Java</strong>. Statically typed means that the type of every expression is known at compile time and thus compiler can validate the methods and fields. But unlike java, Kotlin doesn’t require you to specify the type of every variable explicitly. Most of the time, it can automatically be determined by the context. This ability of compiler (determining type by context) is known as <strong>Type Interference</strong>.</p><pre>val x <strong>=</strong> 10<strong>;</strong></pre><p>Here, a <strong>variable</strong> is initialized with an integer value, so <strong>Kotlin Compiler</strong> automatically determines the type of variable <strong>x</strong> which is <strong>Int</strong>.</p><h3>3. Null Safety</h3><p>While writing java code, you may find a situation when your app throws a <strong>NullPointerException (The Billion Dollar Mistake)</strong> and then you realized that you forgot to add a null check. In Java, you constantly need to check if your instance reference is null or not before using it, thus making the code <strong>defensive</strong>. <strong>Kotlin’s type system</strong> is aimed to eliminate NPE’s from code, thus making Kotlin a <strong>null safe language</strong> like many other modern language. You have to explicitly specify if something can be null or not by using <strong>? operator</strong>. Only possible situations when a NPE can be thrown —</p><ul><li>Calling throw NullPointerException() explicitly.</li><li>Usage of !! operator (will be described in some other post).</li><li>Data inconsistency with initialization.</li><li>Java Interoperation (accessing a member of null reference of a platform type, Generic type with incorrect nullability, etc).</li></ul><h3>4. Object Oriented and Functional</h3><p>While Kotlin is a <strong>Object Oriented</strong> programming language, it’s functions and properties are first class. First class functions means you can <strong>work with them as values</strong>, <strong>store in variables</strong>, <strong>pass them as arguments</strong> or even <strong>return them from other Higher Order Functions</strong> (will be explained in other post). In short, you can use them as you use non-function values which also provides more abstraction and less duplication of code. Using <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming (Wikipedia has a very good article written about it)</a> paradigm, objects become immutable, which guarantees that their state can’t be changed after creation. Functional style programming is <strong>more concise</strong>, <strong>elegant</strong> and <strong>succinct compared to imperative programming</strong>. Kotlin has many features to support functional style programming, some of them are listed below:</p><ul><li><strong>Functional Types</strong> — allows functions to receive other function as parameters or return other functions.</li></ul><pre>fun <strong>&lt;</strong>T<strong>,</strong> R<strong>&gt;</strong> Collection<strong>&lt;</strong>T<strong>&gt;.</strong>fold<strong>(</strong><br>    <strong>initial:</strong> R<strong>,</strong> <br>    <strong>combine:</strong> <strong>(acc:</strong> R<strong>,</strong> <strong>nextElement:</strong> T<strong>)</strong> <strong>-&gt;</strong> R<br><strong>):</strong> R <strong>{</strong><br>    var <strong>accumulator:</strong> R <strong>=</strong> initial<br>    <strong>for</strong> <strong>(element:</strong> T in <strong>this)</strong> <strong>{</strong><br>        accumulator <strong>=</strong> combine<strong>(</strong>accumulator<strong>,</strong> element<strong>)</strong><br>    <strong>}</strong><br>    <strong>return</strong> accumulator<br><strong>}</strong></pre><ul><li><strong>Lambda Expressions</strong> — A lambda expression is a function literal (way of defining functions) that are not declared, but passed as an expression which prevents you from having to write the specification in an abstract class or interface and then implementation in a class.<br>val sum <strong>=</strong> <strong>{</strong> <strong>x:</strong> Int<strong>,</strong> <strong>y:</strong> Int <strong>-&gt;</strong> x <strong>+</strong> y <strong>}</strong></li><li><strong>Data Classes</strong> — Already explained earlier.</li></ul><h3>5. Use-site Variance</h3><p><strong>Generic types</strong> in java are invariant. There are <strong>wildcards</strong> in java but Kotlin doesn’t have any. In java, Collection&lt;String&gt; is a subtype of Collection&lt;? extends Object&gt; but <strong>not</strong> a subtype of Collection&lt;Object&gt; which is obvious to ensure runtime-safety.</p><pre><strong>interface</strong> <strong>Collection&lt;</strong>E<strong>&gt;</strong> <strong>...</strong> <strong>{</strong><br>  <strong>void</strong> <strong>addAll(</strong>Collection<strong>&lt;?</strong> <strong>extends</strong> E<strong>&gt;</strong> items<strong>);</strong><br><strong>}</strong></pre><p>The wildcard type argument ? extends E means we can safely read E&#39;s from the items but can not write to it because we don&#39;t know what objects comply to that unknown subtype of E. This <strong>extends-bound</strong> (upper bound) is of covariant type. Similarly, there is contravariant type <strong>super-bound</strong> (lower bound) which suggest that you can only write E to the collections of `? super E` but can not read E&#39;s from it.</p><p>Kotlin doesn’t have any such wildcards but have variance annotations. Kotlin Provides two type of variance annotation, <strong>out</strong> (makes a type parameter covariant) and <strong>in</strong> (makes a type variant contravariant). Consider the following example —</p><pre><strong>interface</strong> <strong>Event&lt;</strong>out T<strong>&gt;</strong> <strong>{</strong><br>    fun <strong>nextT():</strong> T<br><strong>}</strong><br><br>fun <strong>demo(strs:</strong> Event<strong>&lt;</strong>String<strong>&gt;)</strong> <strong>{</strong><br>    val <strong>objects:</strong> Event<strong>&lt;</strong>Any<strong>&gt;</strong> <strong>=</strong> strs <em>// This is OK, since T is an out-parameter</em><br><strong>}</strong></pre><p><strong>out</strong> variance is kind of <strong>Producer</strong> (? extends) and complementary <strong>in</strong> variance is kind of <strong>Consumer</strong> (? super) (Similar to PECS). The above kind of variance declaration is known as <strong>Declaration-site Variance</strong> which is quite similar to Java wildcards but less verbose and complex.</p><blockquote><em>PECS: Producer Extends, Consumer Super.</em></blockquote><p>In addition to Declaration-site Variance, Kotlin supports <strong>Use-site Variance</strong> (Type projections). Sometimes, there are situations where a type parameter <strong>can not</strong> be either co- or contravariant. Have a look to the following class:</p><pre><strong>class</strong> <strong>Event&lt;</strong>T<strong>&gt;</strong> <strong>{</strong><br>    fun <strong>pull():</strong> T <strong>{</strong> <strong>...</strong> <strong>}</strong><br>    fun <strong>push(event:</strong> T<strong>)</strong> <strong>{</strong> <strong>...</strong> <strong>}</strong><br><strong>}</strong></pre><p>Here, Event can not be restricted to only either produce or consume T’s. The following function maps the event and convert that into some other event.</p><pre>fun <strong>map(from:</strong> Event<strong>&lt;</strong>Any<strong>&gt;,</strong> <strong>to:</strong> Event<strong>&lt;</strong>Any<strong>&gt;)</strong> <strong>{</strong><br>    <em>// Map the from event into to</em><br><strong>}</strong><br><br>val <strong>userId:</strong> Event<strong>&lt;</strong>String<strong>&gt;</strong><br>val <strong>user:</strong> Event<strong>&lt;</strong>User<strong>&gt;</strong><br><strong>map(</strong>userId<strong>,</strong> user<strong>)</strong> <em>// Error: because it expects (Event&lt;Any&gt;, Event&lt;Any&gt;)</em></pre><p>Event&lt;T&gt; is invariant in T so Event&lt;String&gt; or Event&lt;User&gt; is not a subtype of Event&lt;Any&gt;. So to ensure that map function only read from from and doesn’t do any bad, for example writing to from, we need to prevent it. It can be done by using <strong>out variance on site</strong> like below.</p><pre>fun <strong>map(from:</strong> Event<strong>&lt;</strong>out Any<strong>&gt;,</strong> <strong>to:</strong> Event<strong>&lt;</strong>Any<strong>&gt;)</strong> <strong>{</strong><br>    <em>// Map the from event into to</em><br><strong>}</strong></pre><p>This approach is known as <strong>type projection</strong>. In a similar way, you can use <strong>in variance</strong> also to only write to that particular parameter.</p><h3>Use of Kotlin</h3><p>Kotlin can be at various places where Java is used but two main usage of Kotlin to look upon are <strong>Kotlin on Server side</strong> and <strong>Kotlin on Android</strong>.</p><p>Server side programming includes a variety of applications like <strong>web apps, backend for mobile apps and even microservices to communicate</strong>. Kotlin is completely interoperable with java so no need to worry about working with existing codebase. Kotlin lets you use functional style programming to write code with more confidence and concise syntax and full abstraction. In addition to that, Kotlin also has <strong>coroutines</strong> to write code that works <strong>asynchronously</strong> which makes writing microservices more easy.</p><p>Kotlin language feature with a support plugin, turns <strong>android development</strong> into a much pleasurable experience and let you write less number of lines for code. Adding listeners to <strong>view events</strong>, <strong>binding layouts</strong> and <strong>asynchronous programming</strong>, all these can be done by Kotlin in very less code or even no sometimes. A library named <a href="https://github.com/kotlin/anko"><strong>Anko</strong></a> built by Kotlin team, can be used to generate layout without using xmls. All these combined together provides you a <strong>nicer experience</strong> for building android apps.</p><h3>Final Words</h3><p><strong>Kotlin</strong> is a powerful modern language which seamlessly work with a very old and popular language <strong>Java</strong>. The above mentioned features are only the key features of it, there are many more to describe but this post can not accommodate all of them. If you are a new <strong>android developer</strong>, you must start learning Kotlin as well because it’s supported by Google so you can expect lots of new <strong>tools</strong> and <strong>apis </strong>built around Kotlin. If you are experienced with Java and Android Development, you should try Kotlin to <strong>increase your productivity</strong> and <strong>write much more meaningful code</strong>.</p><p>Thanks for reading so far. I hope you have enjoyed this article. If you have any suggestions or query, kindly do comment below. Show some ❤ ❤ ❤ by clapping(👏👏👏👏) and sharing this article.</p><p>This article was originally published at <a href="https://devcompat.github.io/What-is-Kotlin-and-Why-to-use-it/">https://devcompat.github.io/What-is-Kotlin-and-Why-to-use-it/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3856bc779aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger Useful Techniques — #1 Map Multibindings]]></title>
            <link>https://medium.com/@amitkma/dagger-useful-techniques-1-map-multibindings-92900f26bd73?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/92900f26bd73</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Fri, 29 Sep 2017 06:52:19 GMT</pubDate>
            <atom:updated>2017-10-12T16:43:39.794Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to a series of Dagger Useful Techniques to make your dependency injection experience smoother. In this series, I would like to help the developers to make the most of Dagger who are using it for dependency injection. But before I start, there are something to clarify.</p><p>This article is all about dagger techniques, not about how one can implement dagger for dependency injection. I assume that you are already familiar with the basics of dependency injection using dagger. Although I am sharing some link which will be helpful if you are new to dependency injection and want to use dagger —</p><ol><li><a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection (Wikipedia)</a></li><li><a href="https://www.raywenderlich.com/146804/dependency-injection-dagger-2">Dependency Injection in Android with Dagger 2</a></li><li><a href="http://frogermcs.github.io/dependency-injection-with-dagger-2-the-api/">Dependency Injection with Dagger 2 — the Api</a></li><li><a href="https://www.youtube.com/watch?v=IKD2-MAkXyQ">Dagger 2 Intro Video</a></li><li><a href="https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2">Codepath Dependency Injection Tutorial</a></li></ol><p>This is the <strong>Part 1</strong> of this series.</p><h3>Map Multibindings</h3><p>The beauty of Dagger is the annotations. We all love annotations because annotations can be interpreted at compile time by the IDE or compiler or at run-time by the framework. Dagger uses annotation to generate lots of code for you which is used for injection.</p><p>According to the official docs of dagger —</p><blockquote>Dagger lets you use multibindings to contribute entries to an injectable map as long as the map keys are known at compile time.</blockquote><blockquote>To contribute an entry to a multibound map, add a method to a module that returns the value and is annotated with <a href="https://google.github.io/dagger/api/latest/dagger/multibindings/IntoMap.html">@IntoMap</a> and with another custom annotation that specifies the map key for that entry. To contribute an entry to a qualified multibound map, annotate each @IntoMap method with the qualifier.</blockquote><blockquote>Then you can inject either the map itself (Map&lt;K, V&gt;) or a map containing value providers (Map&lt;K, Provider&lt;V&gt;&gt;). The latter is useful when you don’t want all of the values to be instantiated because you’re going to extract one value at a time, or because you want to get a potentially new instance of each value each time you query the map.</blockquote><p>The above description looks very theoretical (but I recommend you to read it and try to understand) and you are wondering what is the need of doing all this if we can directly inject different components. So let me explain this by an example. Look at the screenshot below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*cggPa8MqUE-vwQ2mpEyebg.png" /><figcaption>Screenshot taken from Google Allo</figcaption></figure><p>As you can clearly see, there are different view types like text_message type, image_message type and information_message type. These all can be implemented using different types of viewholder. Here the <strong>Map Multibinding </strong>can play an important role which let you return particular viewholder corresponding to a message type. The advantage of this approach, it provides viewholder at compile time so you can ensure whether a correct viewholder is returning or not and this is also simplifies injection of view holders (I will explain later how).</p><h3>Sample Code</h3><p>(Read the above contents from official doc, follow line by line and try to relate that content with the following implementation)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381c80e59b3ee424543ee6c2e5010c5c/href">https://medium.com/media/381c80e59b3ee424543ee6c2e5010c5c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/605e5cadbf1ee91ca8c26977a688ed55/href">https://medium.com/media/605e5cadbf1ee91ca8c26977a688ed55/href</a></iframe><p>Instead of using custom MapKey, you can use default keys provided by dagger — @StringKey, @IntKey, @LongKey, @ClassKey. More info <a href="https://google.github.io/dagger/api/latest/dagger/multibindings/package-summary.html">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b79ce3267f14f86c6f22f921303461ca/href">https://medium.com/media/b79ce3267f14f86c6f22f921303461ca/href</a></iframe><p>@Binds is a drop in replacement for Provides methods which simply return an injected parameter. Prefer @Binds because the generated implementation is likely to be more efficient.</p><p>Now you can inject this like below —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c0b2c48c2db392ed02a7b372e5a4e8/href">https://medium.com/media/29c0b2c48c2db392ed02a7b372e5a4e8/href</a></iframe><p>This will simplify the injection of Viewholder by just adding a single method to ViewholderModule. There are some other concepts related to multibinding in dagger about which you can read <a href="https://google.github.io/dagger/multibindings">here</a>.</p><h3>Final Words</h3><p>That’s all about <strong>Map Multibindings</strong>. Although there is a lot to say about multibinding but I would like you to check the docs and try to figure out which suits you best. I have not mentioned about how injection works in dagger or how to connect module (ViewHolderModule in above case) to component because I assumed that you have a basic familiarity about dagger. In next part, I will describe techniques available in new <strong>Dagger 2.11</strong> which simplifies the injection a lot easier.</p><p>I hope you have enjoyed reading this article. You can find source code which has above implementation here — <a href="https://github.com/amitkma/android-architecture-boilerplate/tree/master/mobile-app/src/main/java/com/github/amitkma/boilerplate/app">Click Here</a>. Check my github profile for other sample projects — <a href="https://github.com/amitkma">https://github.com/amitkma</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92900f26bd73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing app with JSON Web Tokens]]></title>
            <link>https://medium.com/@amitkma/securing-app-with-json-web-tokens-7d4748b99a16?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4748b99a16</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json-web-token]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Sun, 23 Jul 2017 14:34:19 GMT</pubDate>
            <atom:updated>2017-07-23T16:12:58.042Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will explain what Json Web Tokens (JWTs), why one should use them and how one can use them to ensure security in the application. JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) for safely passing claims in space constrained environments. JWT defines a simple and compact way to securely transmitting information between two parties (for ex. client and server) in the form of json object. I am not going to tell you the coding but surely I will explain the coding also in the next part.</p><h3>What are Json Web Tokens?</h3><p>A Json Web Token looks like this — eyJhbGciOiIiLCJ0eXAiOiJKV1QifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.u8eAOPhMYxbVA344-mqOythdoPqJ4C2gYl1qu0bqehk</p><p>Although, it looks complex but it is actually very compact and self contained representation of claims with a signature to verify it’s authenticity. JWT is just a string with the following format —<strong> header.payload.signature</strong> Each of the three parts are separated by dots. Let’s explain each of them.</p><h4>Header</h4><p>The header is a json object consist of two parts - <strong>typ</strong>: type of the token which is “JWT” itself and <strong>alg</strong>: hashing algorithm used to sign jwt.</p><pre>{   <br>    &quot;alg&quot;: &quot;HS256&quot;,   <br>    &quot;typ&quot;: &quot;JWT&quot; <br>}</pre><p>Then this json object is <strong>Base64Url</strong> encoded to get first part of the token.</p><h4>Payload</h4><p>Payload is the element which contains all the user related data. In addition to that, there are some reserved claims which may also be present in payload.</p><pre>{ <br>    &quot;iss&quot;: &quot;own-auth&quot;, <br>    &quot;name&quot;: &quot;John Doe&quot;, <br>    &quot;admin&quot;: true <br>}</pre><p>Here we are adding only name and admin property of a user. you can add as many as you want. “iss” is a reserved claim that uniquely identifies the party that issued the JWT. You can read more about it <a href="https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields"><strong>here</strong></a>. Then the payload is also <strong>Base64Url</strong> encoded to form the second part of the token.</p><h4>Signature</h4><p>Signature is computed by using a hashing algorithm on the basis of encoded header, encoded payload and secret key. <strong>Secret Key</strong> must be stored in a safe place on autorization server and it should never be disclosed. For example, if we use HMAC SHA256 algorithm, the signature would be</p><pre>HMACSHA256(<br>    base64UrlEncode(header) + &quot;.&quot; +   <br>    base64UrlEncode(payload),   <br>    secretKey)</pre><p>The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.</p><p>After putting all the above three components together what we get is a three part base64 string seperated by dots that can be passed in any html or http request. If you find all above is a bit complicated, you don’t need to worry because there are lots of library which do all the encoding and hashing, you just need to pass the data (claims). For libraries — <a href="https://jwt.io/#libraries">https://jwt.io/#libraries</a></p><h3>Why should you use Json Web Tokens?</h3><p>Let’s talk about why jwt is better than cookies or simple web tokens. The major benefits are following -</p><ul><li>As JWTs are self contained token, so server doesn’t need to ask database to know about the user because user info is already embedded inside the token. It reduces the need to query database multiple times.</li><li>You don’t need to store different cookies for different value data such as user_id, user_last_login or last_visited_page. All this can be stored within a single jwt.</li><li>Token can expire like cookies but you have more control over it.</li><li>Tokens works in the same way on both mobile platform or web platform.</li></ul><h3>How should you use Json Web Tokens?</h3><p>When the user successfully logs in, irrespective of the authentication mechanism such as email, oauth or phone with otp, a JSON web token is generated at server side with all the necessary claims and returned to the client which must be saved locally at the client side for authorising future requests.</p><p>When the user wants to make a request to the protected api, user agent must send the JWT in the <strong>Authorization</strong> header as follows.</p><p>Authorization: Bearer &lt;token&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7T41R0dSLEzssIXPHpvimQ.png" /><figcaption>Source : <a href="https://cdn.auth0.com/content/jwt/jwt-diagram.png">https://cdn.auth0.com/content/jwt/jwt-diagram.png</a></figcaption></figure><p>This authentication mechanism is stateless because as server never stores the user state. The server only checks the <strong>Authorization</strong> header and get the token. Then, server will validate the token against the secret key. If the token is valid, server grants the permission to the client.</p><blockquote><strong>Note :</strong> As you have seen we have just encoded and signed the data and not encrypted it. Encoding is used to transform the data’s structure. JWT are not meant to encrypt or obscure the data so JWT don’t gurantee any security for sensitive data. The purpose of JWT is to check whether data has been tampered in middle or not. It is better to encrypt the jwt before sending on wires if you are having some confidential information in it such as access_roles or payment_information. I will explain this in the next article.</blockquote><p>External References —</p><ol><li><a href="https://en.wikipedia.org/wiki/JSON_Web_Token">https://en.wikipedia.org/wiki/JSON_Web_Token</a></li><li><a href="https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html">https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html</a></li><li><a href="https://tools.ietf.org/html/rfc7519">https://tools.ietf.org/html/rfc7519</a></li><li><a href="https://scotch.io/tutorials/the-anatomy-of-a-json-web-token">https://scotch.io/tutorials/the-anatomy-of-a-json-web-token</a></li><li><a href="https://github.com/jwtk/jjwt">https://github.com/jwtk/jjwt</a> — JWT library for Java</li></ol><p><strong>I hope you have enjoyed this article.</strong> <strong>Click ❤️ below to recommend this article if you found helpful, It would let others to get this article in their feed. For more such articles, follow </strong><a href="https://medium.com/@amitkumar_76187"><strong><em>me</em></strong></a><strong>, you will be notified.</strong></p><p>Thanks for reading!! 😀 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4748b99a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Model-View-Presenter]]></title>
            <link>https://medium.com/@amitkma/understanding-model-view-presenter-1d79448d39cd?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d79448d39cd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Fri, 02 Jun 2017 13:48:53 GMT</pubDate>
            <atom:updated>2017-06-02T13:48:53.131Z</atom:updated>
            <content:encoded><![CDATA[<p>Model-View-Presenter (MVP) pattern is an android architecture pattern, which for a while now gaining importance and popularity. There are already lots of article already written and published over the internet. Here, I am going to discuss what it is and how easily it can be implemented. There are various ways to implement MVP in your app architecture (Be clear, MVP is not an architectural pattern). To understand MVP, it is better to first define what Model, View and Presenter are.</p><p><strong>Model: </strong>It is a data access layer for managing data. It can be an interface which is responsible for accessing APIs and local database or cache etc. It can be an interactor (if using <a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">Uncle Bob Clean Architecture</a>) or repository (if using <a href="https://martinfowler.com/eaaCatalog/repository.html">Repository Pattern</a>) depends on which type of pattern are you.</p><p><strong>View:</strong> It is the only layer for presenting data and reacting to user actions (a button click for example). In case of android, View can be implemented by activity, fragment, widgets or any custom view. This view will contain a reference to the presenter and call a method from presenter.</p><p><strong>Presenter:</strong> This layer works as a middle-man between view and model. It fetches data from the model layer, format the data and return to the view. It also reacts to user interactions through view interface and update the model.</p><h3>What is MVP Pattern?</h3><p>MVP pattern separates the presentation layer from the business logic.It draws sharp line between how interface works and how we show it and decouples the two.</p><h3>Why to use MVP?</h3><ul><li>It maximize the amount of code that can be tested with automation.</li><li>It separates business logic from the view logic to make the code easier to test and understand.</li></ul><h3>Need of MVP in android</h3><p>In android, components are closely coupled to life-cycle of the app. For example, activities are coupled to data access mechanisms and it is also bound to the life-cycle. To make an app maintainable and testable, it is very important to keep layers separated and this is where MVP helps. It decouples the view from data source. For example, if you change your data source, you don’t need to make any change to the views.</p><h3>How to implement MVP</h3><p>There are various ways to implement MVP. Although you are free to use any which best suits your app architecture, here I will only discuss the way which I think better and solves most of the problems. In this article, we will make a note taking app with MVP pattern. This app will be based on feature layered application. If you don’t want to read the whole article, you can view the source code <a href="https://github.com/amitkma/AndroidMvpSample"><strong>here</strong></a>.</p><h4>Step-1: Make Base View and Presenter.</h4><p>First you need to make a base MVP view and MVP presenter which you must extend in all other views or presenter respectively. So, for that, we create a directory(package) named “base” and then create two interface named <a href="https://github.com/amitkma/AndroidMvpSample/blob/master/app/src/main/java/com/github/amitkma/androidmvp/ui/base/MvpPresenter.java">MvpPresenter.java</a> and <a href="https://github.com/amitkma/AndroidMvpSample/blob/master/app/src/main/java/com/github/amitkma/androidmvp/ui/base/MvpView.java">MvpView.java</a> as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794a59c9997c35dec1f6487cb3da4e33/href">https://medium.com/media/794a59c9997c35dec1f6487cb3da4e33/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0719f31d53ec6c74038be4c8e5ebe2c/href">https://medium.com/media/a0719f31d53ec6c74038be4c8e5ebe2c/href</a></iframe><h4>Step-2: Make Contract between view and presenter</h4><p>Now that, you have created base presenter and view, it’s time to make contract for a new feature (display and add notes). The <strong>contract describes the communication between view and presenter, </strong>it helps you to design in a cleaner way the interaction. To do it, create a directory named “main” (because we are using feature layered architecture) and within this directory create an activity and name it “<a href="https://github.com/amitkma/AndroidMvpSample/blob/master/app/src/main/java/com/github/amitkma/androidmvp/ui/main/MainActivity.java">MainActivity</a>”. After creating your feature activity, you need to make a contract for your view and presenter. We name it “<a href="https://github.com/amitkma/AndroidMvpSample/blob/master/app/src/main/java/com/github/amitkma/androidmvp/ui/main/MainContract.java">MainContract.java</a>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d89014c8de93b8e726289080bda266ef/href">https://medium.com/media/d89014c8de93b8e726289080bda266ef/href</a></iframe><p>You can make contract according to your feature like note-detail feature, it can be like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cae7d8249988769a6eb00b2465df496/href">https://medium.com/media/4cae7d8249988769a6eb00b2465df496/href</a></iframe><h4>Step-3: Implement Contract Presenter and View</h4><p>After completing the above two steps, you need to implement your feature presenter and view. You can implement your view in activity, fragment, custom view or any in class that you want to behave as a view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a24ac56b8a73153082c4cea250351888/href">https://medium.com/media/a24ac56b8a73153082c4cea250351888/href</a></iframe><p>To implement presenter, create a class &amp; name it “<a href="https://github.com/amitkma/AndroidMvpSample/blob/master/app/src/main/java/com/github/amitkma/androidmvp/ui/main/MainPresenterImpl.java">MainPresenterImpl.java</a>”. In this class, create a constructor with <strong>MainContract.View</strong> as parameter (Of course, you can add other parameters as well like DataManager. This assures that view is not null at any time unless you set it to null and you don’t have to check the nullity of view. In this constructor set presenter to the specified view. You can find the implementation below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88bef041f9085f12b1957a0d4e82a291/href">https://medium.com/media/88bef041f9085f12b1957a0d4e82a291/href</a></iframe><p>That’s all. You have finally implemented the MVP in your app. You can add as many feature layer as you want to have, just follow above steps. Though the above implementation is not enough, but it gives you the overall idea about how we can implement it in android app. You can find the code <a href="https://github.com/amitkma/AndroidMvpSample">here</a>.</p><h4>Summary</h4><ol><li>Create base view and presenter.</li><li>Make a contract (the view contract and presenter contract)</li><li>Implement view and presenter contract (business logic inside presenter implementation)</li></ol><h3>What’s next</h3><p>If you have completed the above article, I recommend you to read the following articles and samples.</p><ol><li><a href="https://medium.com/@cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf">Model-View-Presenter:Android guidelines</a></li><li><a href="https://hackernoon.com/presenters-are-not-for-persisting-f537a2cc7962">Presenters are not for persisting</a></li><li><a href="https://android.jlelse.eu/dont-put-view-null-checks-in-your-presenters-4b6026c67423">Don’t put view != null checks in your Presenters</a></li><li><a href="https://github.com/googlesamples/android-architecture">Google samples:Android Architecture</a></li><li><a href="https://medium.com/@Miqubel/refactoring-to-mvp-b504a3774ffd">Refactoring to MVP</a></li><li><a href="https://medium.com/@Miqubel/testing-android-mvp-aa0de6e165e4">Testing Android MVP</a></li></ol><p>Thanks for reading this article. I hope you enjoyed this article and make you. Click ❤ below to recommend this article if you found helpful and support the project on <a href="https://github.com/amitkma/AndroidMvpSample">github</a>. It would let others to get this article in their feed. Also if you have any doubt or query, feel free to leave your feedback.</p><p>You can find more code in <a href="https://github.com/amitkma/">my github.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d79448d39cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stitch — Threading using Annotations]]></title>
            <link>https://medium.com/@amitkma/stitch-threading-using-annotations-b4ee26abf66e?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ee26abf66e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Thu, 25 May 2017 15:06:03 GMT</pubDate>
            <atom:updated>2017-05-25T15:06:03.645Z</atom:updated>
            <content:encoded><![CDATA[<p>Working on a project, you often need to write the same code again and again. Same thing had happened to me. When I was working on a project, I faced a problem with threading. I had to create a thread object, then pass a runnable or callable to it. It becomes more tedious when you want method to return something, you have to create a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html"><em>FutureTask</em></a><em> </em>and you have to repeat yourself.</p><p>To deal with it, I found <a href="http://reactivex.io/"><em>RxJava</em></a><em> </em>(API for asynchronous programming and the best so far) but it is very hard to understand it and use it properly. However I suggest you to use it in any project if you want asynchronous programming. So I thought to create a<em> </em><a href="https://github.com/amitkma/Stitch"><em>library</em></a> that generates the boilerplate code for threading.</p><h3>Stitch — What is it</h3><blockquote>In the most simple words, Stitch is a threading library using annotations built for android.</blockquote><h3>How to use Stitch</h3><p>Using stitch is very simple. You don’t need to understand <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html"><em>ThreadPoolExecutor</em></a> or <a href="https://developer.android.com/reference/android/os/Looper.html"><em>Looper</em></a><em>.</em> Simply add <strong>“Stitch”</strong> to your project and you are good to go. Add the following lines to your module level build.gradle (ie. app/build.gradle).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8efc96adf3ba93620f1e3f900756f15b/href">https://medium.com/media/8efc96adf3ba93620f1e3f900756f15b/href</a></iframe><p>Now sync your module and gradle will automatically add Stitch to your module. Currently, there are three types of annotations which Stitch support.</p><p><strong>CallOnAnyThread — </strong>This annotation annotates a method to execute on any thread from thread pool. This library create a fixed size thread pool on the basis of availbale processors. If all threads of the thread pool are busy, the task will be added to the task queue wait until a thread is available to process that task.</p><p><strong>CallOnNewThread — </strong>A method which is annotated with @CallOnNewThread will always execute on a new thread. So the task will never have to wait and always start executing immediately.</p><p><strong>CallOnUiThread — </strong>Want to do some ui changes like setting text, starting animation or anything else, simply annotate the method with @CallOnUiThread.</p><p>Any method which you want to execute on any particular thread, simply annotate that method using one of the annotations mentioned above like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551fb4cd55e58558331864a7b92f752c/href">https://medium.com/media/551fb4cd55e58558331864a7b92f752c/href</a></iframe><p>Now, build the project using terminal or by Build -&gt; Rebuild Project in android studio. Stitch Compiler will generate a new class file for the class in which annotated methods are. The name of generated class will be the Name of existing class in which methods are annotated+ &quot;Stitch&quot; . For example in above case, name of generated file will be &quot;<strong>ExampleClassStitch</strong>&quot; because class name is “ExampleClass”.</p><p>Next, is to get the instance of the generated class (for calling the methods). So to get the instance of generated class, you need to stitch generated class and the required class like below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e980bca11ca67cdf1550db9b04dd7430/href">https://medium.com/media/e980bca11ca67cdf1550db9b04dd7430/href</a></iframe><p>After that, you can call the method as usual and the method will execute upon the annotated thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e0bfc04a187dc6c15af87ccfe99569/href">https://medium.com/media/50e0bfc04a187dc6c15af87ccfe99569/href</a></iframe><p>and done!!!, this method will be executed on any thread from the thread pool.</p><p><strong>Remember — Don’t make any change/update UI using @CallOnAnyThread or @CallOnNewThread otherwise android will throw an exception.</strong></p><h3>Is there any performance issue?</h3><p>The answer is absolutely not and this is because this library generates the code at compile time and zero reflection is used at runtime. So there is no performance issue.</p><p>This library is open source at github. Here is the link —<a href="https://github.com/amitkma/Stitch"><em> </em><strong><em>Stitch</em></strong></a><strong><em>. </em></strong>For more information check <a href="https://github.com/amitkma/Stitch/blob/master/README.md"><em>README</em></a> and if you found any issue just open it on github. You can contribute to this library also. For more info about contribution, read <a href="https://github.com/amitkma/Stitch/blob/master/CONTRIBUTING.md"><em>Contribution Guidelines</em></a><em>.</em></p><p><strong>I hope this article will help you in threading and make you a good developer. Thanks for reading this article. Click ❤ below to recommend this article if you found helpful and star the library on </strong><a href="https://github.com/amitkma/Stitch"><strong><em>github</em></strong></a><strong>. It would let others to get this article in their feed. Also if you have any doubt or query, feel free to ask me.</strong></p><p>For more articles about android and other tech, follow <a href="https://medium.com/@amitkumar_76187"><strong><em>me</em></strong></a>, you will be notified.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ee26abf66e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maintaining Code Style for Android App]]></title>
            <link>https://medium.com/@amitkma/maintaining-code-style-for-android-app-e7bf99f3b409?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7bf99f3b409</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Sun, 14 May 2017 07:32:34 GMT</pubDate>
            <atom:updated>2017-05-14T07:39:32.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*6u51C_pl-UH3X3CbggmCjA.png" /><figcaption>Code Quality Sarcasm (Source: <a href="https://xkcd.com/1513/">https://xkcd.com/1513/</a>)</figcaption></figure><blockquote><em>“Any fool can write code that a computer can understand. Good programmers write code that humans can understand”. — Martin Fowler.</em></blockquote><p>If you have ever worked in a team on a project, you definitely know how important it is to understand the code of your teammates. Whenever you work on a project, it is very important that you and your team follow the same <strong>code style</strong>. <a href="https://en.wikipedia.org/wiki/Programming_style"><em>Code Style</em></a> (Programming Style) is a set of rules or guidelines used when writing the source code for program. It helps developers to read and understand code conforming to the style.</p><p>Learning to write code is easy but learning to write clean code is hard work. It requires more than just the knowledge of principles and patterns. You must sweat over it. You must practice it yourself, and watch yourself fail. You must watch others practice it and fail. You must see them stumble and retrace their steps. For more detailed explanation of “why code style is important”, you can read this <a href="https://coryrylan.com/blog/why-enforcing-code-style-is-important"><em>article</em></a> written by <a href="https://coryrylan.com/"><em>Cory Rylan</em></a>.</p><p>However if you follow all the guidelines and set of rules to write your code, it is important to validate all the source code against the guidelines of your organisation/team before pushing the changes. As being an android developer, I will discuss how to do it in android project.</p><p>In this project, we will use <a href="http://checkstyle.sourceforge.net/"><em>Checkstyle</em></a><strong> </strong>tool which checks the java code automatically which makes it ideal for projects that uses a style guidelines.</p><h3>How to use Checkstyle</h3><p>First, you need to have a guidelines in xml format to use in Android Studio so that you can reformat your source code according to the guidelines. You can make your own set of rules for android studio but I’d like to prefer <em>official android guidelines</em>. There are other guidelines configuration file also available which you can download from the following links. Additional links related to the guide and tools are at the bottom of the articles.</p><ol><li><a href="https://github.com/google/styleguide/blob/gh-pages/intellij-java-google-style.xml"><strong>Google Java Style</strong></a></li><li><a href="https://github.com/android/platform_development/blob/master/ide/intellij/codestyles/AndroidStyle.xml"><strong>Android Style</strong></a><strong> </strong>(I prefer this)</li><li><a href="https://github.com/square/java-code-styles/blob/master/configs/codestyles/SquareAndroid.xml"><strong>Square Android Style</strong></a></li></ol><p>If you don’t know how to add style to your project in android studio, follow this link —<a href="https://blog.metova.com/how-to-import-the-official-android-code-style-to-android-studiointellij/"> <em>How to Import The Official Android Code Style</em></a><em>.</em></p><p>Based on the code style which you are following, create a checkstyle configuration file. The checkstyle configuration which I am using can be found at this <a href="https://github.com/dot-wave/DotStyleConfig/blob/master/checkstyle/checkstyle-config.xml"><em>github repo</em></a><em>.</em> You are free to modify the configuration of this file but make sure that it must be consistent with the code style which you or your organisation follow.</p><p>— In the root directory of your android project, create a folder named <strong>“config” </strong>. In this directory paste the “<strong>checkstyle-config.xml”</strong> which you have downloaded from above github link.</p><p>Now create a file named “<strong>style-script.gradle”</strong> in the same config directory and paste the code below-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc381ec2c37501d1fe955852e6583c1e/href">https://medium.com/media/dc381ec2c37501d1fe955852e6583c1e/href</a></iframe><p>I’m not going to explain how <a href="https://docs.gradle.org/current/userguide/tutorial_using_tasks.html"><em>gradle tasks</em></a> work because it is a beyond the scope of this article and surely I will write an article about <a href="https://gradle.org/"><em>Gradle</em></a> also. After adding the style-script to your project, you need to apply that script to the build.gradle in app module. Add the following line in your app module build.gradle.</p><pre>apply from: &#39;../config/style-script.gradle&#39;</pre><p>Now you can build your project and run the command below in the terminal (make sure you are in root dir) to execute checkstyle task. (You can also run any task within android studio)</p><pre>$ ./gradlew checkstyle</pre><p><strong>Note :</strong> Don’t forget to replace the <strong>./gradlew</strong> with the <strong>gradle</strong> if you are using gradle instead of gradle-wrapper.</p><p>Upon execution of the above command, xml and html reports will be generated in the build directory of the app module.</p><pre>root-project &gt;&gt; app &gt;&gt; build &gt;&gt; reports &gt;&gt; checkstyle &gt;&gt; checkstyle.html</pre><p>Open the html file and you will see something similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XecLgkE4Y8vJh2id_71NvQ.png" /><figcaption>Checkstyle html report generated after execution of checkstyle report</figcaption></figure><p>You can view the errors and change them accordingly. After following all the guidelines you will see no errors occurring and BUILD_SUCCESSFUL.</p><p>That’s all for this article. There are also some other tools which help to maintain the code style and quality throughout the life-cycle of your project. I will discuss all that tools in the upcoming articles.</p><h4>Additional Links:</h4><ol><li><a href="https://google.github.io/styleguide/"><em>Google Style Guide</em></a></li><li><a href="https://source.android.com/source/code-style"><em>Android Code Style Guide</em></a></li><li><a href="http://checkstyle.sourceforge.net/config.html"><em>Checkstyle Configuration Guide</em></a></li><li><a href="https://docs.gradle.org/current/userguide/checkstyle_plugin.html"><em>Checkstyle Gradle Plugin</em></a></li></ol><p><strong>I hope this article will help you to write a better code and make a good developer. Thanks for reading this article. Click ❤ below to recommend this article if you found helpful. It would let others to get this article in their feed. Also if you have any doubt or query, feel free to ask me.</strong></p><p>For more articles about android and other tech, follow <a href="https://medium.com/@amitkumar_76187"><strong><em>me</em></strong></a>, you will be notified.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7bf99f3b409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Best Practices of Java in Android]]></title>
            <link>https://medium.com/@amitkma/10-best-practices-of-java-in-android-96dd7b98e292?source=rss-4586b66ac140------2</link>
            <guid isPermaLink="false">https://medium.com/p/96dd7b98e292</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amit Kumar]]></dc:creator>
            <pubDate>Fri, 02 Dec 2016 06:34:31 GMT</pubDate>
            <atom:updated>2016-12-02T07:19:23.904Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, I am sharing what i have learnt in the journey of Android Development. I always think to write code in terms of APIs (Application Programming Interfaces). Of course, there may be ten different ways to write a program but seven of them will be inefficient and not reusable. Well, this is not a complete set of practices but these must be in a developers’ toolkit. Here are some of the practices -</p><h4>1. Use static factory methods instead of constructors</h4><p>You don’t need to create a new object each time, they’re invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*yj_uLn5hQS9I7Sb9bqBwhA.png" /><figcaption>Static method example</figcaption></figure><h4>2. Use builders when there are many constructor parameters</h4><p>When there are some required and some optional parameters, Builder pattern is better than telescoping pattern. In short, whenever there is more than 3 parameters, you must consider builder rather than constructors.</p><pre><strong>public class </strong>BlogPost {<br><br>    <strong>private final </strong>String <strong>post_title</strong>;<br>    <strong>private final </strong>String <strong>post_description</strong>;<br>    <strong>private final </strong>String <strong>author</strong>;<br>    <strong>private final long posted_on</strong>;<br>    <strong>private final int num_of_likes</strong>;<br>    <strong>private final int num_of_comments</strong>;<br><br>    <strong>public static class </strong>Builder {<br>        <em>//Required Parameters<br>        </em><strong>private final </strong>String <strong>post_title</strong>;<br>        <strong>private final </strong>String <strong>post_description</strong>;<br><br>        <em>//Optional parameters<br>        </em><strong>private </strong>String <strong>author </strong>= <strong>&quot;&quot;</strong>;<br>        <strong>private long posted_on </strong>= 0l;<br>        <strong>private int num_of_likes </strong>= 0;<br>        <strong>private int num_of_comments </strong>= 0;<br><br>        <strong>public </strong>Builder(String post_title, String post_description) {<br>            <strong>this</strong>.<strong>post_title </strong>= post_title;<br>            <strong>this</strong>.<strong>post_description </strong>= post_description;<br>        }<br><br>        <strong>public </strong>Builder author(String authorName) {<br>            <strong>author </strong>= authorName;<br>            <strong>return this</strong>;<br>        }<br><br>        <strong>public </strong>Builder posted_on(Long posted_on) {<br>            posted_on = posted_on;<br>            <strong>return this</strong>;<br>        }<br><br>        <strong>public </strong>Builder numLikes(<strong>int </strong>val) {<br>            <strong>num_of_likes </strong>= val;<br>            <strong>return this</strong>;<br>        }<br><br>        <strong>public </strong>Builder numComments(<strong>int </strong>val) {<br>            <strong>num_of_comments </strong>= val;<br>            <strong>return this</strong>;<br>        }<br>        <br>        <strong>public </strong>BlogPost build(){<br>            <strong>return new </strong>BlogPost(<strong>this</strong>);<br>        }<br>    }<br><br>    <strong>private </strong>BlogPost(Builder builder){<br>        <strong>post_title </strong>= builder.<strong>post_title</strong>;<br>        <strong>post_description </strong>= builder.<strong>post_description</strong>;<br>        <strong>author </strong>= builder.<strong>author</strong>;<br>        <strong>posted_on </strong>= builder.<strong>posted_on</strong>;<br>        <strong>num_of_likes </strong>= builder.<strong>num_of_likes</strong>;<br>        <strong>num_of_comments </strong>= builder.<strong>num_of_comments</strong>;<br>    }<br>}</pre><p>Then you can use it as follows</p><pre>BlogPost <strong>blogPost </strong>= <strong>new </strong>BlogPost.Builder(<strong>&quot;My First Post&quot;</strong>, <strong>&quot;description of my post&quot;</strong>).author(<strong>&quot;Amit Kumar&quot;</strong>).numLikes(2).build();</pre><h4>3.Best way to implement a singleton is to use single-element enum.</h4><pre><strong>public enum </strong>BlogPost {<br>    <strong><em>INSTANCE</em></strong>;<br>    <br>    <strong>public void </strong>buildPost() {...}<br>}</pre><h4>4. Always override toString</h4><p>It is recommended that all subclasses must override this method. Providing a good toString implementation, helps you in generating a useful diagnostic message. But you must clearly document your intentions and specify the format.</p><h4>5. Immutable class are easier to design and use than mutable class.</h4><p>To make a class immutable, you must follow these 5 rules.</p><blockquote><em>Don’t provide any methods that modify the object’s state</em></blockquote><blockquote><em>Ensure that the class can’t be extended.</em></blockquote><blockquote><em>Make all fields final.</em></blockquote><blockquote><em>Make all fields private.</em></blockquote><blockquote><em>Ensure exclusive access to any mutable components.</em></blockquote><h4>6. Use static member classes over non static</h4><p>If you have a nested class that doesn’t depend or serve any other class except the enclosing class it must be a top-level class. Otherwise if that class doesn’t not access an instance of enclosing class, it must be a static class. It helps you to prevent memory leaks.</p><h4>7. Use enums instead of int constants</h4><pre>public enum Apple { FUJI, PIPPIN, GRANNY_SMITH }<br>public enum Orange { NAVEL, TEMPLE, BLOOD }</pre><p>Enums provide compile-time type safety. If you declare a parameter to be of<br>type Apple , you are guaranteed that any non-null object reference passed to the parameter is one of the three valid Apple values. Attempts to pass values of the wrong type will result in compile-time errors so they can be easily removed at compile time.</p><h4>8. Return an empty array or list, not nulls</h4><pre>public List&lt;Post&gt; getPosts() {<br>if (posts.size() == 0)<br>return null;<br>...<br>}</pre><p>There is no need to return null when no posts are available. You can simply return an empty array. Doing this, will help client to write less code that is client won’t need to check null.</p><pre>public List&lt;Post&gt; getPosts() {<br>if (posts.size() == 0)<br>return Collections.emptyList();<br>...<br>}</pre><h4>9. For-each loops are faster than traditional for loops</h4><pre><strong>private </strong>List&lt;User&gt; <strong>userList</strong>;<br><em>//Traditional for loop<br></em><strong>for </strong>(<strong>int </strong>i = 0; i &lt; <strong>userList</strong>.size(); i++) {<br>    doSomething(<strong>userList</strong>.get(i));<br>}<br><br><em>//for-each loop<br></em><strong>for </strong>(User user : <strong>userList</strong>) {<br>    doSomething(user);<br>}</pre><p>For-each loops are more efficient to iterate over a list and array.</p><h4>10. Use lazy initialisation judiciously</h4><p><a href="http://www.javaworld.com/article/2077568/learn-java/java-tip-67--lazy-instantiation.html">Lazy initialisation</a> is an approach of delaying the initialisation of a field until it is needed. In most of the cases, normal initialisation is preferable to the lazy one because lazy initialisation doesn’t improve the performance significantly and as it is slow so the normal one is preferred. The best advice is “don’t do it unless you need to”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96dd7b98e292" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>