<?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 Nitin Verma on Medium]]></title>
        <description><![CDATA[Stories by Nitin Verma on Medium]]></description>
        <link>https://medium.com/@nitin-code?source=rss-9bf4d136e72a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eII29fvlJ888n5mDm84wHA.jpeg</url>
            <title>Stories by Nitin Verma on Medium</title>
            <link>https://medium.com/@nitin-code?source=rss-9bf4d136e72a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:55:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nitin-code/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[Encrypting data in Android Room DB]]></title>
            <link>https://medium.com/mindorks/encrypting-data-in-android-room-db-bab0d70039af?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bab0d70039af</guid>
            <category><![CDATA[room]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 06:57:41 GMT</pubDate>
            <atom:updated>2021-10-15T16:22:55.908Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to encrypt/decrypt DB data by writing a layer on top of Room Dao’s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*jl0FIRQraipyWaAER_VAzQ.jpeg" /></figure><p>Android Room library is great and very easy to use but it doesn’t provide any feature to encrypt/decrypt data(as of 2021). So in this post I will be sharing a way that I have used in many of my projects to do this by adding a code layer before calling Room Dao methods. For this post it is a <strong>pre-requisite</strong> that you understand Room Library and have implemented it in one of your apps.</p><p>In a nutshell this is what we are going to do:<br>From our code (basically Repository) we are not going to call Dao method directly. we will make a new class SecureDao. This class will be responsible to encrypt/decrypt data using some class (like CryptoUtils) and call dao methods internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*gRpkxf40xVtKsxSKhpbXPA.png" /><figcaption>Basic flow</figcaption></figure><p>Let’s implement it for a very basic use case. Suppose that you want to insert userId into a user table with two columns only : key, userId. <br>For this we will have a very basic below Dao method in <strong>UserDataDao </strong>interface:</p><pre>@Insert(onConflict = OnConflictStrategy.ABORT)<br>suspend fun insertUserId(userData: UserData)</pre><p>Now we will make same method in our <strong>UserDataDaoSecure </strong>class, In the constructor we will have userDataDao and cryptoUtils:</p><pre>suspend fun insertLoginData(userDataEntity: UserDataEntity) {<br>    userDataDao.insertUserId(encrypt(userDataEntity))    <br>}</pre><pre>private fun encrypt(userDataEntity: UserDataEntity):UserDataEntity{<br>   userDataEntity.let{<br>      return UserDataEntity(<br>         it.key, // no operation on this<br>         cryptoUtils.encrypt(it.userId) // encrypt it<br>      )<br>   }<br>}</pre><p>Now from your code or repository layer, you can simply call userDataDaoSecure.insertLoginData(userDataEntity)</p><p>This is the simple trick that I use to encrypt/decrypt data in Android DB. To improve it further I usually implement Dao interface in my secure Dao class. This ensures that whatever methods I have in my dao, I have to implement them in my secureDao class.</p><p>This was a very simple example. To see it’s usage and the code in securityUtils you can check this project in github:</p><p><a href="https://github.com/Ni3verma/Safe-Box">Ni3verma/Safe-Box</a></p><p>Safe-Box is an open source android app. You are welcome to contribute to this project or raise any issue. You can also download it from play store</p><p><a href="https://play.google.com/store/apps/details?id=com.andryoga.safebox">Safe Box - Apps on Google Play</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bab0d70039af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/encrypting-data-in-android-room-db-bab0d70039af">Encrypting data in Android Room DB</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command pattern — Part 2]]></title>
            <link>https://nitin-code.medium.com/command-pattern-part-2-47977bbb8510?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/47977bbb8510</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[command-pattern]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 05:40:36 GMT</pubDate>
            <atom:updated>2019-09-10T05:40:36.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Command pattern — Part 2</h3><h4>Learn how to decouple the requester of action from the executor of action.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9it4vnTb5K6F3jp-uYRbA.jpeg" /><figcaption>Credits : Image from Dreamstime.com</figcaption></figure><p>Welcome to Part-2 of fifth pattern in my Design pattern series. Before reading this make sure you have gone through <a href="https://medium.com/@Nitin_code/command-pattern-part-1-37034a5e73ac">Part-1 of command pattern</a> also.</p><blockquote>Here’s a recap of mappings that we did in part-1</blockquote><pre>Order -- Command<br>takeOrder() -- setCommand()<br>orderUp() -- execute()<br>cook -- Receiver</pre><p>I will be building our remote control in bottom up fashion. Let’s start with Command interface. As already discussed this interface will have only 1 method which we will call execute()</p><pre>public interface Command{<br>   public void execute();<br>}</pre><p>Now let’s make a Concrete Command class which will implement the Command interface and override the execute method. In execute method do the action on the receiver. When we make object of this command we need to pass a Light object. This light object might be referencing to gate light or living room light or any other light. whichever light is passed to this command object constructor will be turned on when execute method is called. See the code below to completely understand it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ad692109cd83ff0838e1a4e68a4d80d/href">https://medium.com/media/9ad692109cd83ff0838e1a4e68a4d80d/href</a></iframe><p>As we discussed in part-1, we will now set this command object to remote control slot and when remote button is pressed, it will simply run whateverCommand.execute() which will result in completion of our action. Let’s see the code to understand it even better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1a1b73d8700bc2a47c120349213028f/href">https://medium.com/media/f1a1b73d8700bc2a47c120349213028f/href</a></iframe><p>For now we have a single slot(<em> or button </em>) on our remote. In future we will set different commands such as GateLightOffCommand, TvOnCommand, SprinklerOnCommand, etc on different slots by using setCommand method. Next we will test our SimpleRemoteControl class and to simulate button press, we will manually call buttonWasPressed method.</p><p>Now let’s test our SimpleRemoteControl class and see how to set command and receiver and actually see everything wired up. Note that for now we have only one slot, so setCommand and buttonWasPressed can be simply called otherwise we’ll have to give slot position also. You will see this next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d1a70c2f3a969adfad1c0764a7754c5/href">https://medium.com/media/1d1a70c2f3a969adfad1c0764a7754c5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*hhhXobAj6v2kXSp_W_-DSQ.png" /></figure><p>Just for recap, these are the steps: <br>first make a receiver — make a command object and pass the receiver — set this command object to button — when button is pressed run command.execute() . As every command class implements Command interface so all of them will have execute method.</p><p>Before moving on to set different commands on different slots, first let’s discuss a important point. so when we press some button, can we simply call command.execute() every time? Well the answer is NO, let’s see why.</p><p>when we will have multiple slots each having different command associated with it, then we will change the signature of void buttonWasPressed() to void buttonWasPressed(int slot). suppose that we simulate click of first button. This button is empty that is no command is associated with this button( <em>see above diagram</em>). so when we run command.execute() we will get the famous NullPointerException. we can get around it by first checking whether command is null or not. If it’s not only then run the execute method. But there is a better way which is using a <strong>null object</strong>. Null objects are very famous in Design pattern world. you will see their usage in a number of patterns. let’s see what it means to make a null object.</p><p>make a new class NoCommand which will also implement Command interface and override the execute method. This Command class won’t require any receiver as it doesn’t perform any operation on any appliance.</p><pre>class NoCommand implements Command{<br>  public void execute(){<br>    print(&quot;no command attached&quot;);<br>  }<br>}</pre><p>Now in the constructor of RemoteControl, make a new NoCommand object and set it to every slot by default. whenever you want to set a particular command on some slot, you can always call setCommand method and set it. Now you don’t have to perform any null checks and you can safely call command.execute()on every slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*vKKhcBaZr6RHZai9G8uq1g.png" /><figcaption>Remote</figcaption></figure><p>Let’s try to make this remote control with multiple commands. It has total 4 slots. 2 slots for turning something ON and 2 for OFF. first two slots will turn Gate light on and off and the next two slots doesn’t do anything.</p><p>Below you can see the implementation of Remote control class for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21c2d358aeddcd9f738a26c52d576157/href">https://medium.com/media/21c2d358aeddcd9f738a26c52d576157/href</a></iframe><p>so initially we will set NoCommand to each slot. In remoteControlTest class we can set command to a slot by calling setCommand method. This is similar to how we set command previously.</p><p>Your are done with command pattern. I hope you understood how to decouple the executor from the requester of action. In our example we made remote control a dumb object. It doesn’t know about anything except for calling execute method whenever button is pressed.</p><p>There are number of uses of this pattern. You can search about them. for example: adding undo functionality, queuing requests, logging requests and crash failure recovery. Tell me in comment section if you want me to make part-3 on them also.</p><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below.</p><p>Let’s connect on <a href="https://www.linkedin.com/in/nitinverma1120/">LinkedIn </a>and <a href="https://github.com/Ni3verma">GitHub</a>.</p><p>References:<br>- Head first design patterns <a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124">book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47977bbb8510" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command pattern —Part  1]]></title>
            <link>https://nitin-code.medium.com/command-pattern-part-1-37034a5e73ac?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37034a5e73ac</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[command-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Fri, 06 Sep 2019 06:21:28 GMT</pubDate>
            <atom:updated>2019-09-10T06:04:33.141Z</atom:updated>
            <content:encoded><![CDATA[<h3>Command pattern —Part 1</h3><h4>Learn the basics and terminology of command pattern.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9it4vnTb5K6F3jp-uYRbA.jpeg" /><figcaption>Credits : Image from Dreamstime.com</figcaption></figure><h4>Prerequisite:</h4><ol><li>If you’re not not familiar with the term ‘design patterns’ make sure to check out my <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></li><li>You understand java or any other OOP language</li><li>You have a basic idea about <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">inheritance</a>, <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">polymorphism</a>, and <a href="https://en.wikipedia.org/wiki/Interface_(computing)">interfaces</a>.</li></ol><p>In this part I will explain this pattern with the help of an illustrative example, we won’t do any coding. Implementation will be covered in part-2.</p><p>Let’s say that you want to build a home automation remote control. It will have some slots( <em>or buttons</em> ) and each slot will control a appliance. You can have various appliances such as gate light, living room light, TV, etc.</p><p>One common and bad approach to do this would be to add appliance call logic in RemoteControl class itself like this:</p><pre>// RemoteControl class code</pre><pre>GateLight gateLight = new GateLight();<br>// some code</pre><pre>// on click of slot 1 do this:<br>gateLight.on();<br>// on click of slot 2 do this:<br>gateLight.off();</pre><pre>// on click of slot 3 do this:<br>tv.on();<br>// on click of slot 4 do this:<br>tv.off();</pre><pre>// other code</pre><p>There are several reasons why this approach is bad:</p><ol><li>Think of it like you own a company which make this remote. Your company only make the remote control, it doesn’t itself make appliances. so your remote will support different <strong>vendors</strong>. for example <strong>Bajaj </strong>smart fan or <strong>Havells </strong>LED smart bulb or <strong>Sony</strong> smart TV. These vendors will have various operations that can be applied on their appliance. Like let’s say that when sony tv turns on they want to execute this code snippet in sequence :<br>tv.on(); // turn it on<br>tv.setVolume(5); // set the volume to mid when it turns on<br>tv.setChannel(0); // set the channel to 0 when it turns on<br>tv.setBrightness(60); // set the brightness to 60 when it turns on<br>Now how do you think you as a engineer in remote control company is going to get this code snippet. Do you think every vendor will mail you code snippets like this on how to actually perform a operation and then you will add that snippet in RemoteControl class? Obviously NO !!<br>So what’s currently wrong with our approach is that vendors are exposing their API and we are trying to implement them by calling them. But what should actually happen is that we should expose some API and those vendors who want their appliance to be controlled by our remote should implement our API. so basically we are doing exact opposite! This point is the most important, I hope that it’s clear to you. <strong>give it a read 2–3 times or ask me in comment section if you have any doubt.</strong></li><li>Not all appliances will only have on and off function. like you have seen in previous point we can have a range of methods like setChannel , setVolume , etc. So we can have diverse vendors and diverse methods of each appliance. If we provide implementation of all buttons then our RemoteControl class will be very hard to maintain and making changes in it will be a nightmare.</li><li>This approach doesn’t follow<strong> open-close principle</strong>, there is no <strong>separation of concerns</strong>, high <strong>coupling</strong>, not modular and definitely not scalable. <br>( <em>if you don’t know about these terms, search and learn about them. These are very important and common in design patterns. )</em></li></ol><p>So this is what we are going to do. we will load each button of remote with <strong>some object</strong>. This object will know how to do the operation. Remote will not have any idea what the work is or who is going to do the work, it just knows that it has a object for each button that knows how to talk to the right appliance to get the work done. This way our remote is decoupled from the actual appliance. This way our remote is dumb and we have delegated all of the responsibility to this object. You will get to know about this mysterious super-intelligent object in part-2. This is the magic of command pattern, It allows you to decouple the requester of action from the object that actually performs the action.</p><p>Before moving on to part-2 and coding, first let’s see a real life example which will help you understand this pattern even better.</p><p>So you are in a restaurant and you want to eat one burger and a shake. You give your order to waitress. She writes it down on a piece of paper and goes inside and yells “order up” and gives the paper to cook. He prepares your order and you eat it. This Example is insanely simple but we will try to go deep into it and map this procedure with command pattern.</p><p>Here are few points to note:</p><ol><li>Do you know how to make burger and shake? Does waitress know how to prepare food items? Answer is clearly <strong>NO.</strong> Only cook knows how to prepare these items. You don’t tell the procedure when you give order, only thing that you have to do is select food items and the job of waitress is to take order from you and give it to cook.</li><li>So you don’t know how to make food items but still once you give order, you get that food item magically. maybe it’s not magical for you but wait, compare it with our original problem of home automation remote : what if we do something so that remote button doesn’t know how to turn on TV but once user presses it, magically TV turns on. Read the point again, maybe now you will find it magical 🔥<br>So if you or waitress don’t know about the procedure to prepare food item, why should our remote control class know the procedure to turn on the TV or any other appliance?</li><li>So all of this magic is happening because of one very important thing which is <strong>Order</strong>. yes that piece of paper on which order is written is the real Hero here. Think of it like this, every order implements some interface and override one method <strong>orderUp(). </strong>when waitress receives a order object, she goes inside and yells “order up”(or execute orderUp() method) and passes it to cook. <br>some important mapping from this point to command pattern:<br>1) we’ll call this order object as <strong>Command Object. </strong>we will have various commands such as LightOnCommand, TvOnCommand, etc<strong><br></strong>2) Each command object implements Command interface which has only one method <strong>execute(). </strong>You can map OrderUp to this method.<br>3) we will call our cook as <strong>Receiver.</strong> He is the one who knows how to actually do the task. for example in LightOnCommand we will have a object of Light as receiver and in overriden execute method, we’ll do light.on(); ( <em>don’t worry if you don’t get it, you will see this in next part. just remember the mappings. </em>)<br>4) Once the execute method is called, the receiver takes over and executes the task just like how cook takes over and prepares the meal.</li><li>Just like waitress took the order(<em>call it takeOrder() or setOrder()</em>), we’ll call this procedure as setting a command(<em>or setCommand()</em>).</li><li>So this is what we’ll do in part-2 : set some command on a button. when button is pressed call command.execute() and in the overrided execute method, actually do the operation with the help of receiver.</li></ol><p>I’m sure you are confused with all of these new terms (<em>and you should be</em>) but don’t worry everything will be clear in part-2. Here’s a recap of mappings and do give this article one more read before moving on.</p><pre>Order -- Command<br>takeOrder() -- setCommand()<br>orderUp() -- execute()<br>cook -- Receiver</pre><p>Let’s continue with part-2</p><p><a href="https://medium.com/@Nitin_code/command-pattern-part-2-47977bbb8510">Command pattern — Part 2</a></p><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below.</p><p>Let’s connect on <a href="https://www.linkedin.com/in/nitinverma1120/">LinkedIn </a>and <a href="https://github.com/Ni3verma">GitHub</a>.</p><p>References:<br>- Head first design patterns <a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124">book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37034a5e73ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about GSSoC 2019]]></title>
            <link>https://nitin-code.medium.com/all-about-gssoc-2019-11d7c2445ae7?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/11d7c2445ae7</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[contribution]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[gssoc]]></category>
            <category><![CDATA[gssoc19]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Thu, 23 May 2019 14:58:45 GMT</pubDate>
            <atom:updated>2019-05-23T14:58:45.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcTA3sdGKFdZDkcwYi1U4Q.png" /></figure><p>Before I share my experience, let me tell you two very important things:</p><ol><li>This post is <strong>not</strong> about GSoC, popularly known as google summer of code. This one is about <a href="https://www.gssoc.tech/">GSSoC</a>(Girlscript summer of code). I have repeated this line thousands of time to my friends, teachers, family over the past 3 months!</li><li>GSSoC is <strong>not</strong> only for girls. It’s open for all, whether you want to participate or do mentorship. In my university, people still think that GSSoC is only for girls. So spread this news.</li></ol><p>I already knew about GSSoC in my univ but how I came to know that boys can also participate in it is by luck. It was mid january and I was searching about how to get into GSoC. I read many blogs and then I started to watch some youtube videos. On one of the video comments, I saw this word “<a href="https://www.gssoc.tech/"><strong>GSSoC</strong></a>”. I opened gssoc website to see the registration dates for my female friends. In the FAQ section, there was this question that immediately caught my attention:<br>“Is it strictly for girls or can boys also participate?” It was clearly answered that it is open for both boys and girls.</p><p>After reading it, I immediately applied for it. It consisted of very basic questions about you, your experience, why do you want to participate, what do you expect, etc. <br>Before reading further, just go to their <a href="https://www.gssoc.tech/">website</a> and apply for it. why shouldn’t you? It’s free of cost. you have nothing to loose and who knows, you might gain something !</p><p>Don’t be afraid of this “<strong>open source</strong>” word. even if you don’t know about it, doesn’t matter if you have never used github, or if you have never made any project. remember that GSSoC is for the beginners like you so that you can learn about these things. Let me tell about you about me. before GSSoC although I knew about github basics but I had <strong>never ever </strong>contributed to someone else’s repository(project). I didn’t know about pull requests or anything about working in team. and currently while writing this post, I am second on leaderboard !! so again go for it, partiipate and if you are dedicated you will learn a lot of things.</p><p>I got the acceptance mail one day before valentine. I joined the slack channel. For next 3–4 days, everyone is introducing themselves. All projects are announced and you can see details of each project on gssoc.tech website. Upto 28 feb it was time for community bonding. here’s my tips to get most out of this period:</p><ol><li>Explore all of the projects. write down the projects that you are interested in. Next see github repository of these projects. choose the project that looks best to you and join it’s channel on slack(for each project they have a separate channel)</li><li>Most important, this is the time to learn about github. It’s very important that when the coding period begins, you know about these terms: commit, repository, push, pull, issue, pull request.<br>These two courses by udacity are enough:<br><a href="https://www.udacity.com/course/how-to-use-git-and-github--ud775">https://www.udacity.com/course/how-to-use-git-and-github--ud775</a><br><a href="https://www.udacity.com/course/github-collaboration--ud456">https://www.udacity.com/course/github-collaboration--ud456</a></li><li>Run the project that you have choosen in your own local machine. If you encounter any error, ask in slack channel. Mentors are always there to help you. just don’t be shy to ask.</li><li>Carefully read <strong>CONTRIBUTING.md </strong>file in root of repository. It consist of all the steps that you need to follow for contributing to this repository.</li><li>Before coding period begins, test that you are able to send a pull request to the repository. send a test pull request just to check your github skills. delete the pull request after that.</li><li>Explore the code base. try to understand the flow of project. ask your mentors if you face any problem.</li></ol><p>Now that you have github skills, read contributing.md file and mentors support, next step is to start contributing to the project. All of the issues are labelled with level of difficulty. Each level have different score.<br>Beginner-10, Easy-20, Medium-30, Hard-50<br>I’ll suggest you to grab a beginner issue first. just write down the comment : “I’ll like to work on this issue.” and you are done. issue is assigned on first come, first serve basic. ie: one who comments first will get the issue. solve the issue and send a PR(pull request). mentors will check your PR, they will ask you to do some corrections(if any). add new changes and commit again. this cycle will repeat untill your code is perfect. then it will be merged and you will get points.</p><p>Remember to <strong>comment on only one issue at a time</strong>. otherwise it become hard for owner and mentors to track the participants. This is how the flow is: comment on a issue, start working on it, send a PR, wait for PR to get merged, <strong>only</strong> when it’s merged -&gt; comment on next issue which is not assigned to anyone.</p><p>One very important thing: if there is no open issue, don’t sit and wait for mentors to add a new issue. Instead explore the project, run it on your machine, find a bug and <strong>create a new issue </strong>and assign it to yourself. If you don’t find any bug, try to find something that lacks in this project. Raise a issue that you want to add this new feature, if mentors approve it then start to work on it.</p><p>Sometimes the changes that mentors require on your PR will frustate you (to be honest). They will ask you to remove extra line, sometimes a single extra space, sometimes change name of your variables. But try to understand the reason behind such things. <strong>Rules</strong> must be followed in open source development because you are not the only developer. After you many contributors will come, so code is written in a proper style which is easy for everyone to understand.</p><p>so make sure that you solve as many issues as possible in this 3 month period. After all there are prizes and swags for top performers.</p><p>Inspired by this journey, I have also made my own project in Android and open sourced it on github. If you are also a android developer in kotlin and know about jetpack components, have a look at my project and contribute to it. currently it is in very young stage, soon I will update it with readme and contributing files.</p><p><a href="https://github.com/Ni3verma/Code-Time">Ni3verma/Code-Time</a></p><p>I am a android developer. I contributed to <a href="https://github.com/Swati4star/Images-to-PDF">this</a> project of swati garg. My mentors were Paras and vyankatesh. All of them are really helpful. At the time of writing this post, I still have 7days to contribute. I’ll update this story and tell you about what happens in the end, what’s the prize and swags that particiants get.</p><p>Follow me on Medium to get the updates and do read my other stories ✌️. connect with me on linkedIn :</p><p><a href="https://www.linkedin.com/in/nitinverma1120/">Nitin Verma | LinkedIn</a></p><p>For those who are reading this in 2020 or after. Clap if I helped you, encouraged you or boosted you to participate in it. Maybe next time you will see me as a mentor or maybe you will contribute to a new project of mine. cheers 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11d7c2445ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns: The Decorator Pattern]]></title>
            <link>https://medium.com/better-programming/decorator-pattern-4f92897e4b4?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f92897e4b4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Tue, 07 May 2019 02:38:11 GMT</pubDate>
            <atom:updated>2019-05-13T16:28:37.780Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to make your code cleaner and more modular with the Decorator pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v3nF-R9DSqvde9baEfXYQ.jpeg" /></figure><h3>Prerequisites:</h3><ol><li>If you’re not not familiar with the term ‘design patterns,’ make sure that to check out my <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></li><li>You understand Java or any other OOP language.</li><li>You have a basic idea about <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">inheritance</a>, <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">polymorphism</a>, and <a href="https://en.wikipedia.org/wiki/Interface_(computing)">interfaces</a>.</li></ol><p>To see the full code, please check my GitHub repository:</p><p><a href="https://github.com/Ni3verma/Coffe-Shop">Ni3verma/Coffe-Shop</a></p><p>Suppose that you have a coffee shop, and it’s the fastest growing shop around. Just look across the street and you will see it’s other branch. You serve four types of beverages: house blend, dark roast, decaf, and espresso.</p><p>When you first started the business, you designed your classes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*TVCZCIQA7VvFahD8sr5Qpw.png" /></figure><p>Beverage is abstract class and cost method is also abstract in it. Subclasses will implement it. Beverage has four sub-classes: HouseBlend, DarkRoast, Decaf, and Espresso. All of them override cost method and return their own cost. Here, we have used <strong>inheritance</strong>.</p><p>In addition to coffee, you can also ask for condiments like steamed milk, soy, mocha, and whipped milk. You can implement it similar to before and use inheritance. This way we will have a huge number of classes: HouseBlendMilk, HouseBlendMocha, HouseBlendSoy, HouseBlendWhip, HouseBlendMilkMocha, HouseBlendMilkSoy, etc. The list goes on. There will be around 100 classes that we will have to make.</p><p>That’s what happen when we overdo inheritance. It can easily result in class explosion<strong>. </strong>There is clearly a better way to implement like this. Let’s find one.</p><h3>Approach 1:</h3><p>To see code related to approach 1, click below:</p><p><a href="https://github.com/Ni3verma/Coffe-Shop/tree/d6b1e42d7dca41c04d03654566889cb93eb136e8">Ni3verma/Coffe-Shop</a></p><p>or if you have already cloned the repository, check out <a href="https://github.com/Ni3verma/Coffe-Shop/commit/d6b1e42d7dca41c04d03654566889cb93eb136e8">simple approach commit</a>.</p><p>In this approach we will add some boolean variables in Beverage class as flags. If it’s true, it means that condiment is present, so add its cost. This time cost() method is <em>not</em> abstract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89285b937e6b7ac57114956dcf91eb96/href">https://medium.com/media/89285b937e6b7ac57114956dcf91eb96/href</a></iframe><p>In our concrete Beverage class like DarkRoast, we will override the cost method and add cost after calculating condiment cost by calling super.cost().</p><p>Let’s say for Dark roast coffee, we will add 20 extra rupees.</p><pre>@Override    <br>public int cost(){        <br>  return super.cost() + 20;  <br>}</pre><p>Here’s how we will make HouseBlend milk coffee. Its output will be cost of house blend coffee + cost of steamed milk (condiment).</p><pre>Beverage b = new HouseBlend();       <br>b.setMilk(true);        <br>System.out.println(&quot;total cost = &quot;+b.cost());</pre><p>Our code will work perfectly, but there are few problems with this simple approach:</p><ul><li>If there is a price change for condiment, or a new condiment is to be added, we will have to modify our existing code and make new methods. Note that adding new things should not alter existing code, as it may result in bugs.</li><li>We may have some new beverages, like iced tea. For this, there is no point of adding milk condiment, but we will inherit it from Beverage class.</li><li>What if customer wants a double Mocha?</li></ul><h4>Approach 2:</h4><p>To see code related to it, checkout <a href="https://github.com/Ni3verma/Coffe-Shop/commit/ff45635a276aff23fed6875d77c9c14792f6520e#diff-e7de9043f1a8c235dcce04e119ea062cR9">this commit</a>.</p><p>In this approach, we will use decorator pattern. In this design pattern we have a <strong>component </strong>(like DarkRoast) and <strong>decorators </strong>(like Whip, Mocha, etc.). We wrap this component with decorators. This is what I mean by wrapping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*QmZgBIvY7l0k9431AIKTmg.png" /></figure><p>Now, when we want to compute the cost, we will call cost method on the outermost decorator, and then it will call cost method of its inner decorator/component. This will continue, until it reaches its component (DarkRoast here). Then DarkRoast will return its own cost to Mocha, Mocha will add its own cost to it and return the total to Whip. Whip will add its own cost, and return the total out. This is the flow:</p><p>Cost of DarkRoast = 20, Mocha = 50, and Whip = 60.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*9YKA1ORd-waKHsJgYtZRqw.png" /><figcaption>Total cost is 130 rupees</figcaption></figure><p><strong>The Decorator pattern </strong>attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending a functionality.</p><p>Now that we have some ideas in our mind about how this pattern works, let’s see how we will implement this type of behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*14AiqaYqPHKj8SRtSekDqQ.png" /></figure><ol><li><strong>Component: </strong>It is a abstract class; both concrete components and Decorator abstract class will inherit its behavior.</li><li><strong>Concrete Component: </strong>extends Component. It is the object to which we are going to dynamically add new behavior. It can be used on its own or wrapped by a decorator. (For example, we can order DarkRoast coffee or DarkRoast with Mocha.)</li><li><strong>Decorator: </strong>It also extends component and is an abstract class.</li><li><strong>Concrete Decorator: </strong>Each decorator has a component, which means that it has an instance variable that holds reference to a component (the dotted line represents this). It extends Decorator abstract class, like Milk, Soy, etc.</li></ol><p>Now let’s see our abstract Component class, in our case Beverage.java file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6194604b085c1229d2985591b59b4ab/href">https://medium.com/media/b6194604b085c1229d2985591b59b4ab/href</a></iframe><p>The cost method is abstract because we want all of the classes that inherit it (concrete components and decorators) to override it and provide their own cost.</p><p>Now let’s see one of our concrete component class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb0f668ee0d7a26fd47d936e40860847/href">https://medium.com/media/eb0f668ee0d7a26fd47d936e40860847/href</a></iframe><p>Whenever we define a concrete component, we will give it description in constructor and override cost method and return its cost.</p><p>Now it’s time to see the main class where magic happens. Let’s see the abstract decorator class; in our case, it’s CondimentDecorator.java.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4237f7bf7d2b0e019f76887db26316e6/href">https://medium.com/media/4237f7bf7d2b0e019f76887db26316e6/href</a></iframe><p>Note that it also extends Beverage. The getDescription method is abstract because we want all of the concrete decorators to override it and provide their own implementation for it. As we have not implemented cost method here, every concrete decorator will have to override it also. Additionally, we have a instance variable beverage because we will require it in concrete decorator class. Only because of this will we be able to form a chain of call to parent’s cost method like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*9YKA1ORd-waKHsJgYtZRqw.png" /></figure><p>Let’s have a look at one of concrete decorator class, Mocha.java:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca47d389015ad1e6336d438f3a5df02/href">https://medium.com/media/cca47d389015ad1e6336d438f3a5df02/href</a></iframe><p>In the constructor, it will receive a Beverage and set its instance variable to it and override the methods. Note that the beverage variable is inherited from the CondimentDecorator class.</p><p>Before ordering coffee, remember that both decorators (Whip, Soy) and components (DarkRoast, Decaf) extends component (Beverage) class. So we can say that:</p><ol><li>DarkRoast is a Beverage.</li><li>DarkRoast with Mocha is also a Beverage.</li><li>DarkRoast with Mocha and Whip is also a Beverage.</li></ol><p>Now let’s order some coffee! 😃 In your main method, test this code:</p><pre>Beverage b1 = new Espresso();<br>System.out.println(b1.getDescription() + &quot; Rs.&quot; + b1.cost());</pre><pre>// ** OUTPUT **<br>// Espresso Rs.30</pre><p>Ordering a simple coffee is easy and simple; let’s add a condiment.</p><pre>Beverage b2 = new DarkRoast();<br>b2 = new Mocha(b2);<br>System.out.println(b2.getDescription() + &quot; Rs.&quot; + b2.cost());</pre><pre>// ** OUTPUT **<br>// Dark roast, Mocha Rs.70<br>// Rs 70 = Rs 20(of DarkRoast) + Rs 50(of Mocha)</pre><p><em>b2 = new Mocha(b2)</em>. This is what we mean by decorating a object. We have taken a object of DarkRoast and decorated with the Mocha class. Remember that the concrete decorator (Mocha here) class receives a beverage in its constructor? Here we have passed b2. So you can say that in the Mocha class beverage = b2, and at this time b2 was an object of theDarkRoast class. When we compute the cost, beverage.cost will return the cost of b2 (DarkRoast = Rs 20), and then we add 50 in it, so the result is Rs 70.</p><p>Now let’s add two condiments, Mocha and Whip:</p><pre>Beverage b2 = new DarkRoast();<br>b2 = new Mocha(b2); // wrap it with mocha<br>b2 = new Whip(b2); // wrap it with whip<br>System.out.println(b2.getDescription() + &quot; Rs.&quot; + b2.cost());</pre><pre>// ** OUTPUT **<br>// Dark roast, Mocha, Whip Rs.130<br>// Rs 130 = Rs 20(of DarkRoast) + Rs 50(of Mocha) + Rs 60(of Whip)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*HDzctcfBAAwjiObTDUJ9QA.png" /></figure><p>As I have already told you, (DarkRoast +Mocha) is also a beverage. This is the reason that we can pass b2 object in Whip constructor. Again, the flow is similar as before. When we call <em>b2.cost(), </em>first it will compute beverage.cost(), and for Whip, beverage is DarkRoast + Mocha. When we call beverage.cost() on this DarkRoast + Mocha, it will call its beverage.cost(), and for (DarkRoast + Mocha) system, beverage is DarkRoast. Here beverage.cost() will give us 20; we add 50 (Mocha cost) to it and return 70. This 70 is received by Whip, and it adds 60 and returns 130.</p><pre>Beverage b2 = new DarkRoast();<br>b2 = new Mocha(b2); // wrap it with mocha<br>b2 = new Whip(b2); // wrap it with whip</pre><p>I know that the above part of the code is a little bit confusing. But you’ll learn to decorate objects in a much better way when you learn about the <em>Factory</em> and <em>Builder</em> patterns. Some of you might be saying that you have never seen code like this. But if you have ever written a piece of code in Java, then to take user input, you either use Scanner<strong> </strong>or InputStreamReader<strong> </strong>or some other method. Let’s see how to read user input by InputStreamReader:</p><pre>BufferedReader br = <br>new BufferedReader(new InputStreamReader(System.in));<br>String s = br.readLine();</pre><p>Here we are wrapping an InputStreamReader within a BufferedReader so you have been using Decorator pattern from the beginning without even knowing about it!</p><p>Last important point to note is that, although Decorator is a subclass of the Component class, we can not directly make objects of concrete decorator without passing in a concrete component. For example, here we cannot directly order only Mocha because it requires a Beverage to pass in constructor. Mocha is a decorator so it must be used to decorate a Beverage. So first make a object of concrete component like DarkRoast, Decaf, or some other coffee and then decorate it with decorators.</p><p>Thank you so much for sticking with me for this long. Hope you learned about decorators and components.</p><h3>References</h3><ul><li><a href="https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124">Head First Design Patterns</a> (Amazon)</li><li><a href="https://github.com/Ni3verma/Coffe-Shop">My GitHub repo for this article</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f92897e4b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/decorator-pattern-4f92897e4b4">Design Patterns: The Decorator Pattern</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract factory pattern]]></title>
            <link>https://nitin-code.medium.com/abstract-factory-pattern-2193667dcad6?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2193667dcad6</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Sat, 20 Apr 2019 05:54:38 GMT</pubDate>
            <atom:updated>2019-04-20T05:57:34.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZR4m60fUPleKgCXSmh6ZQ.jpeg" /></figure><p>Welcome to third pattern in my Design pattern series. Before reading this story <strong>make sure that you have read </strong><a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40"><strong>Factory Pattern</strong></a><strong> story</strong>.</p><p><a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40">Factory Pattern</a></p><h4>Prerequisite:</h4><ol><li>You have read <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns</em></a><em> and</em><strong> </strong><a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40">Factory Pattern</a>.</li><li>You understand java or any other OOP language</li><li>you have basic idea about inheritance, polymorphism, interfaces</li><li>you find my stories interesting 😉</li></ol><p>In our<strong> </strong><a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40">Factory Pattern</a> story, we made a pizza shop where regional pizza stores (like NYStylePizzaStore) instantiate that region particular pizza(like NYStyleCheesePizza). Github repository for same can be found <a href="https://github.com/Ni3verma/PizzaShop">here</a></p><p><a href="https://github.com/Ni3verma/PizzaShop">Ni3verma/PizzaShop</a></p><p>We can say that each pizza is composed of set of ingredients. A pizza can have following ingredients: Cheese, Sauce, Clams, Dough, Veggies,etc. In New York people like Thin crust and in Chicago people like Thick crust. So if we have a set of ingredients then we can make a new pizza. So now let’s build a factory to create ingredients. Just follow along, it’s not as complicated as it sounds!</p><p>Let’s define a interface that all our PizzaIngredient Factories will implement.</p><pre>public interface PizzaIngredientFactory{<br>  public Dough createDough();<br>  public Sauce createSauce();<br>  public Cheese createCheese();<br>  public Veggies[] createVeggies();<br>  public Pepperoni createPepperoni();<br>  public Clam createClam();<br>}</pre><p>As previously in factory pattern post, here also we will have different regional factories for ingredients. for eg: below you can see a regional ingredient factory to get a idea of what I am talking about.</p><pre>public class NYPizzaIngredientFactory implements PizzaIngredientFactory{<br>  public Dough createDough(){<br>    return new ThinCrustDough();<br>  }<br>  public Sauce createSauce(){<br>    return new MarinaraSauce();<br>  }<br>  public Cheese createCheese(){<br>    return new ReggianoCheese();<br>  }<br>  public Veggies[] createVeggies(){<br>    Veggies veggies[] = {new Garlic(), new Onion(), new Mushroom()}<br>    return veggies;<br>  }<br>  public Pepperoni createPepperoni(){<br>    return new SlicedPepperoni();<br>  }<br>  public Clam createClam(){<br>    return new FreshClams();<br>  }<br>}</pre><p>Similarly we can have ChicagoPizzaIngredientFactory where we will return Thick crust dough, Mozzarella cheese, frozen clams, plum tomato sauce, sliced pepperoni and some veggies like spinach, black olives.</p><blockquote><strong>Note </strong>that the new classes that you see here like Dough, Sauce, FreshClams and many more are <strong>not </strong>available in github repo because that repository is<strong> only for</strong> <a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40">Factory Pattern</a> story.</blockquote><p>our new Pizza class will look like this. Note that as compared to our previous story Pizza class, we have added some new ingredients and made prepare method as abstract. If you want to compare it with previous story version, click <a href="https://github.com/Ni3verma/PizzaShop/blob/master/src/Pizza/Pizza.java">HERE</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2777f5a71ce2d6c9345c8a58f4183652/href">https://medium.com/media/2777f5a71ce2d6c9345c8a58f4183652/href</a></iframe><p>As now we have regional pizza stores and regional pizza ingredients, so now we don’t have to make classes for regional pizzas. what it means is that, now we don’t need to have NYStyleCheesePizza /ChicagoStyleVeggiePizza. we simply need to have CheesePizza /VeggiePizza. They will extend our abstract pizza class and implement abstract prepare method.</p><p>here’s how one our concrete CheesePizza class will look like</p><pre>public class CheesePizza extends Pizza{<br>  PizzaIngredientFactory ingredientFactory;</pre><pre>  public CheesePizza(PizzaIngredientFactory ingredientFactory){<br>    this.ingredientFactory = ingredientFactory;<br>  }</pre><pre>  void prepare(){<br>    print(&quot;preparing &quot; + name);<br>    dough = ingredientFactory.createDough();<br>    sauce = ingredientFactory.createSauce();<br>    cheese = ingredientFactory.createCheese();<br>  }<br>}</pre><p>Note that ingredients produced depends on the factory that we are using. eg : In this line of code dough = ingredientFactory.createDough() , Dough type that will be returned depends upon the IngredientFactory that we use. If the factory is of type NYPizzaIngredientFactory then it will return ThinCrustDough.</p><p>Region specific pizza stores will use region specific ingredients. eg: NYStylePizzaStorewill use NYPizzaIngredients. so we will couple them together. Here’s how our NYStylePizzaStoreclass will look like now. wanna compare with previous story? click <a href="https://github.com/Ni3verma/PizzaShop/blob/master/src/PizzaStore/NYStylePizzaStore.java">HERE</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd0e6ba2a1d17f7a1b8c333dd33713f/href">https://medium.com/media/0cd0e6ba2a1d17f7a1b8c333dd33713f/href</a></iframe><p>We have done a lot of changes in our code. Mostly we made new classes. We provided a means of creating a family of ingredients for pizzas by introducing a new type of factory called an Abstract factory.</p><blockquote>Abstract factory gives us an interface for creating a family of products without specifying their concrete classes. abstract factories helps us to produce different products for different contexts — such as different regions, different looks, etc.</blockquote><p>In the above definition, family of products in our example refer to Dough, Sauce, Cheese, Clams… if we have this family then we can make a pizza.</p><p>Let’s try to understand the class diagram. Below I have only shown some part of it (related to New York)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*J5E6Zkd2gUN1kWrIzP6awA.png" /></figure><p>Few important points to be noted here:</p><ol><li>The abstract PizzaIngredientFactory is the interface that defines how to make a family of related products.</li><li>Clients of the abstract factory are the concrete instances of the pizza abstract class.</li><li>Job of the concrete pizza factories is to make pizza ingredients. A factory knows how to create the right object for their region.</li><li>Each family produces a different implementation for the family of products. Here we have only shown New York factory, but by now you can easily make Chicago factory also, this factory will create ThickCrustDough instead of ThinCrustDough and similarly for other ingredients.</li></ol><p>Below you can see the general class diagram of a abstract factory pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*CXmYHZ4OGlETwGOooIdiVg.png" /></figure><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below (if you have any 😉) ✌️</p><p>References:<br>- Head first design patterns <a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124">book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2193667dcad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Pattern]]></title>
            <link>https://nitin-code.medium.com/factory-pattern-c0c284530d40?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c284530d40</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 02:39:13 GMT</pubDate>
            <atom:updated>2019-04-20T05:56:23.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-dsDq_0lBbWAD_TaEqNnQ.jpeg" /></figure><p>Welcome to second pattern in my Design pattern series. Before reading this story make sure that you have read <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></p><h4>Prerequisite:</h4><ol><li>Again make sure that you have read <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></li><li>You understand java or any other OOP language</li><li>you have basic idea about inheritance, polymorphism, interfaces</li><li>you find my stories interesting 😉</li></ol><p>Let’s say that you want to start a new pizza shop. You serve different kinds of pizzas and obviously you also have menu. Let’s see a method that might appear in our Pizaa store code.</p><pre>public Pizza orderPizza(String type) {<br>  Pizza pizza;<br>  if (type.equals(&quot;cheese&quot;))<br>    pizza = new CheesePizza();<br>  else if (type.equals(&quot;clam&quot;))<br>    pizza = new ClamPizza();<br>  else if (type.equals(&quot;veggie&quot;))<br>    pizza = new VeggiePizza();<br>  else<br>    return null;</pre><pre>  //once we have correct type of pizza, do operations on it<br>  pizza.prepare()<br>  pizza.bake();<br>  pizza.cut();<br>  pizza.box();</pre><pre>  return pizza;<br>}</pre><p>So first we make a correct type of pizza by using if-else blocks and then we perform operations on it. please note that prepare,bake,cut,box doesn’t depend upon type of pizza that we are instantiating. All it cares is that we call these methods on a Pizza(supertype obviously)</p><p>Now see this part of above code:</p><pre>if (type.equals(&quot;cheese&quot;))<br>    pizza = new CheesePizza();<br>  else if (type.equals(&quot;clam&quot;))<br>    pizza = new ClamPizza();<br>  else if (type.equals(&quot;veggie&quot;))<br>    pizza = new VeggiePizza();</pre><p>If you have done coding a lot then you know that this type of code occurs very frequently in any project. you can easily imagine that similar code block will also appear when we are making bill for a user and a lot of other places. we know that change is the only constant in any software project. Let’s say we want to add a new type of pizza or delete clamPizza then making changes in this type of code is even more difficult because we have to go to every place and make same changes.</p><p>Now let’s move object creation out of orderPizza() method into a separate class SimplePizzaFactory whose job is just to create a pizza.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2cb1147c6152f0bc39c5fc87b8e373/href">https://medium.com/media/eb2cb1147c6152f0bc39c5fc87b8e373/href</a></iframe><p>Now our code from PizzaStore has reduced to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/971b2a87c0fa71a63b5447d9cab34e2b/href">https://medium.com/media/971b2a87c0fa71a63b5447d9cab34e2b/href</a></iframe><blockquote><strong>It might look like that the changes that we made has no advantage. We are just pushing the problem off to another object.</strong><br>But remember that by doing this, we have reduced code duplication and now we have only <strong>one place to make changes</strong> when required in future. and this is not the final design. This is just the introduction to the world of factories 😃</blockquote><p>Now let’s discuss about simple factories. our class diagram looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Bf-SqDvcHir8EXKjjNsmSw.png" /></figure><p><strong>PizzaStore:</strong> This class is the <strong>client </strong>of the factory. It need SimplePizzaFactory to get instance of type Pizza.<br><strong>SimplePizzaFactory: </strong>This is the factory where we create pizzas. It should be the <strong>only </strong>part of our application that refers to concrete Pizza classes.<br><strong>Pizza: </strong>This is the <strong>product</strong> of the factory. here this is a abstract class which has some methods already implemented.<br><strong>Concrete Pizza classes:</strong> these are our concrete products. Each of them should extend Pizza class. As long as this is the case, our factory can create instance and hand it back to the client. Here they are CheesePizza, ClamPizza, VeggiePizza.</p><p>Now you have learned about simple factory. Remember that they always have a client and a product. This is what factories are for, they create products(in real world and in softwares too !!)</p><p>Time for a break 😃 ✌️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7HVdHgbN7kQLQ-OJ" /><figcaption>Photo by <a href="https://unsplash.com/@adeolueletu?utm_source=medium&amp;utm_medium=referral">Adeolu Eletu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your pizza shop has now become famous and everyone loves it. You want to expand your business to New York and Chicago. Let’s see how you can do this:</p><p><strong>Approach 1: </strong>You can make different factories for New York and Chicago whose names will be NYPizzaFactory and ChicagoPizzaFactory respectively. We will also have NYStylePizzas and ChicagoStylePizzas. Factory will instantiate proper type of pizza. I won’t go into much detail as we will focus on approach 2. But here’s how we will order pizza with this approach</p><pre>NYPizzaFactory nyFactory = new NYPizzaFactory();<br>PizzaStore nyStore = new PizzaStore(nyFactory);<br>nyStore.order(&quot;cheese&quot;);</pre><p><strong>Approach 2: </strong>Now we will tie the store and the pizza creation together. So instead of having multiple factories, we will have multiple stores. Let’s discuss about it in detail</p><p>In case you want to see the full code, see this <a href="https://github.com/Ni3verma/PizzaShop">repository</a>. you can import the project in Netbeans.</p><p><a href="https://github.com/Ni3verma/PizzaShop">Ni3verma/PizzaShop</a></p><p>Now we will move our createPizza factory method back into PizzaStore but as a <strong>abstract method</strong>. now our PizzaStore will also be a <strong>abstract class</strong>. Each region will have it’s own PizzaStore type which will extend this PizzaStore and provide implementation for createPizza method(<em>make instance of concrete Pizza type</em>) eg:NYPizzaStore will make different type of NYStylePizzas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ad451e409a83f2442f05a3d773b675/href">https://medium.com/media/06ad451e409a83f2442f05a3d773b675/href</a></iframe><p>Let’s see one of the sub-type of PizzaStore and see what exactly it is doing</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec4293978a2060ba92017afcf6a0b2c/href">https://medium.com/media/3ec4293978a2060ba92017afcf6a0b2c/href</a></iframe><p>So now instantiation is handled by sub-classes of PizzaStore in their overrided createPizza method. abstract createPizza() method in abstract PizzaStore class act as a factory method. It returns a product( here type Pizza) and this product is used in orderPizza method.</p><pre>//Here&#39;s how you can order pizza using this approach<br>PizzaStore store = new NYPizzaStore();<br>Pizza pizza = store.orderPizza(&quot;cheese&quot;);</pre><p>In the above code when we call store.orderPizza(&quot;cheese&quot;) , then orderPizza() method of PizzaStore will be called and futher this method will createPizza() method, but createPizza is abstarct in this class and has no implementation, so what will it do? It all depends on which sub-class of PizzaStore in instantiated. As we have instantiated NYPizzaStore, so createPizza() of NYPizzaStore will be called, and it will return appropriate Pizza type.</p><p>So when orderPizza() calls createPizza() , one of your subclasses will be called into action to create a pizza. which kind of pizza will be made? it’s decided by the choice of pizza store you order from. NYStylePizzaStore will return NYStylePizza and ChicagoStylePizzaStore will return ChicagoStylePizza.</p><p>All factory patterns encapsulate object creation by letting subclasses decide what object to create. Let’s check the class diagram to see main components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*yDD5Jcd5uTgp4oH8xMJ2TA.png" /><figcaption>creators and products</figcaption></figure><h4><strong>Key points:</strong></h4><ol><li>abstract creator class defines a abstract factory method that subclasses implement to produce products. Here createPizza is our factory method. It produces products.</li><li>Often the abstract creator class contains code that depends on product of factor method which is produced by sub class.</li><li>classes that produce products are called concrete creators</li><li>Factories produce products and here our product is pizza</li></ol><h3><strong>Factory method defined:</strong></h3><p>This pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p><p>Creator class is written without the knowledge of the actual products that will be created, it is decided purely by the choice of the subclass that is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*wuWSzTtNqmdc3gRc92TYaA.png" /><figcaption>general design</figcaption></figure><p>Wanna learn about <strong>Abstract Factory pattern </strong>also? see my story on it.</p><p><a href="https://medium.com/@Nitin_code/abstract-factory-pattern-2193667dcad6">Abstract factory pattern</a></p><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below (if you have any 😉) ✌️</p><p>References:<br>- Head first design patterns <a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124">book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c284530d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Pattern]]></title>
            <link>https://medium.com/better-programming/strategy-pattern-ec05e990f944?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec05e990f944</guid>
            <category><![CDATA[thinking-outside-the-box]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 09:51:09 GMT</pubDate>
            <atom:updated>2019-04-16T02:39:49.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*XpadFZyg7G3WE7UJPqMWhg.png" /></figure><p>So this is the first pattern in my Design pattern series. Before reading this story make sure that you have read <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></p><h4>Prerequisite:</h4><ol><li>Again make sure that you have read <a href="https://medium.com/@Nitin_code/design-patterns-introduction-30b9f3c5f7e"><em>Introduction to design patterns.</em></a></li><li>You understand java or any other OOP language</li><li>you have basic idea about inheritance,polymorphism,interfaces</li><li>you find my stories interesting 😉</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rOMVr9VsjUf66nzo" /><figcaption>Photo by <a href="https://unsplash.com/@chilinik?utm_source=medium&amp;utm_medium=referral">Nikita Kostrykin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Suppose that you are developing a new game. let’s call it <strong>Napalm 🔥 </strong>(cool name..?)</p><p>Now Napalm is all about fighting. For now assume that they can move, run and tell who they are. You designed 4 characters : Wizard, Giant, Golem and Harry.</p><p>As we are good with OOPS principles so we will use inheritance. Let’s make a superclass <strong>Fighter. </strong>All other characters classes such as wizard,giant,etc will inherit from it(as they all are fighters !). All characters move and run in same fashion so we will provide common implementation of these methods in fighter class and every child class will inherit it and we will <strong>override </strong>displayName method in each child class so that they tell it properly who they are. Our design will be similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*6Otr_pGRjiMhs0ukHamduQ.jpeg" /><figcaption>UML <strong>like </strong>diagram (initial design)</figcaption></figure><p>Everything looks good and you are adding more features in Napalm. You have a crazy idea to add a new power to throw <strong>fire🔥 !!<br></strong>You decided to give this power to harry and wizard.<br>How hard it can be to implement it 😌? You just need to add fire method in Fighter class. Your new design will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*tACAIP3KLqTBky3qSldWRQ.png" /><figcaption>added fire power</figcaption></figure><p>Now you have fire power inherited into wizard and harry.</p><pre>Wizard ron=new Wizard();<br>ron.fire(); // and ron will fire<br>// similarly with object of harry class</pre><p>But wait there is a major problem !! When we added fire method in Fighter class(parent) then all of it’s chil classes will inherit. <strong>Note</strong> that not all characters have all powers. some can fly while some can’t, some can throw fireballs while some can’t(<em>sensitive skin issues</em> 😶) but now golem and giant also has fire power(<em>this is not what we want</em>).<br>When we added fire method in parent class, it was great use of inheritance for the purpose of <strong>code</strong> <strong>reuse </strong>but not so well when it comes to <strong>maintenance</strong>. Moreover what if we want different types of fire powers in different characters? Let’s say wizard can throw fire balls and harry can shoot a fire laser. Adding a single implementation in supercalss won’t let us do this. we will have to override the method and provide implementation in every character class.</p><p><strong>Solution 1 : </strong>we can override fire method in other sub-classes to do nothing, this way only wizard and harry will get fire power. But this solution is <strong>not good</strong> in the long run. Think about it, soon we will add new characters in our game and new powers will also be added for some of them. If we continue with this approach then we’ll have to remember to <strong>override and do nothing</strong> for all new powers in all children classes. Our second problem of having different behaviors of fire power still remains.</p><p><strong>Solution 2 :</strong> you might be thinking about it for a while. As we want only certain characters to get a new power we can also use <strong>interfaces. </strong>Only certain classes will implement a interface and override the methods. So we’ll make a FirePowerInterface.java interface in which we will have a fire method and Wizard, harry classes will implement this interface and implement the methods of interface. This way both of our problems are solved:</p><ol><li>fighters such as golem don’t have fire power</li><li>wizard can throw fireballs and harry can shoot fire beam</li></ol><p>Here’s our new design :</p><blockquote><em>Solid lines means </em><strong><em>extends </em></strong><em>and dotted lines mean </em><strong><em>implements.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*CZllq4CRSxv7tFKMPVp3LQ.png" /><figcaption>using interface</figcaption></figure><p>But wait now we have a even bigger problem !! By using interfaces we are not reusing our code. Every class who implement this interface will have to override the methods and provide implementation. Second problem is that it will be really hard to introduce changes. In future let’s say if we want to change the fire power (<em>eg: it’s color or damage or range or any other implementation part</em>) then we will have to go to every class which implements this interface and make same changes several times which makes our code not maintainable.</p><p>Can you think of some other approach to solve our problem? Grab a cup of coffee and think about it. Just take a break, as now I want your full attention.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1J3CbFgn5o7DGRuE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1J3CbFgn5o7DGRuE%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbG51YTI0ZmU3ZTI1OGx2ZGVjY3h4NmJhYTJjeHFuOGZsOGQ1bTd4eiZlcD12MV9naWZzX2dpZklkJmN0PWc%2Fl1J3CbFgn5o7DGRuE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa8f4266a7202d18b96ad7d41b42eef/href">https://medium.com/media/5fa8f4266a7202d18b96ad7d41b42eef/href</a></iframe><p>We know that fire() is the part of Fighter class which vary across various various fighters. so we’ll pull out this method and create a new set of classes to represent each fire behavior. This way, the character classes won’t need to know any of the implementation details for their own behaviours. Now instead of defining fire method in it’s own class, Fighters will <strong>delegate</strong> it’s fire behavior. Here’s our set of classes that represent fire behaviors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*-WyYA9CZCPyyV3OP2hnE6g.png" /><figcaption>fire behavior</figcaption></figure><h4>Wiring up :</h4><p>First we will add a instance variable in Fighter class named fireBehavior of interface type.</p><pre>FireBehavior fireBehavior;</pre><p>Each Fighter object will set this variable during instantiation. Advantage of making this variable of interface type(and not a particular class) is that we will be able to able to set it in a polymorphic way at run time(more on this later). We will also make a new method in Fighter class named <strong>performFire(). </strong>Rather than handling the fire behavior itself, object will delegate the behavior to the object referenced by fireBehavior. we don’t care what kind of object it is, all we care is that it knows how to fire !</p><pre>public void fireBehavior(){ <br>  fireBehavior.fire();<br>}</pre><p>Our wizard class will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ddb8bd1b57e7fa88c1d25dc745eba85/href">https://medium.com/media/1ddb8bd1b57e7fa88c1d25dc745eba85/href</a></iframe><p>Our Fighter class will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/458437cf53cf05a65397eb6bd43c862b/href">https://medium.com/media/458437cf53cf05a65397eb6bd43c862b/href</a></iframe><p>Here’s our FireWithBalls.java class where our our implementation of fire() method will live</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4be45920703100eafa10dae1916002/href">https://medium.com/media/6a4be45920703100eafa10dae1916002/href</a></iframe><pre>//now wizard can fire like this:<br>Wizard obj = new Wizard();<br>obj.performFire();<br>//that&#39;s all !!</pre><p>now only change that we need to make in Harry class will be that it’s fireBehavior will be initialized with FireNoWay.</p><p>We have following advantages by doing things like this:</p><ol><li>character who can’t fire won’t be able to fire as their fireBehavior will be initialized with FireNoWay.</li><li>if we need to change something with the implementation of fire power(let’s say related to fire with laser) then we have to make changes at only one place (ofcourse in FireWithLaser’s overloaded fire method !)</li><li>We can change fire behavior <strong>dynamically. </strong>we are going to do this with few lines of code. but before it, let’s discuss why would we need to do it? Suppose that in our game whenever a character reaches a score of 100(or it’s multiple) then he gets a special power(<em>ummm…let’s say fire bomb whose code is in FireWithBomb.java class…a new class,, you got the pattern</em>). Now whenever this happens we need to change fireBehavior from <em>whatever it is</em> <strong>to</strong> FireWithBomb. now let’s add this functionality also.</li></ol><h4>Setting behavior dynamically:</h4><p>add a new method in Fighter class</p><pre>public void setFireBehavior(FireBehavior fb){<br>  fireBehavior=fb;<br>}</pre><p>with just these lines of code, we can change fire behavior dynamically.</p><pre>Wizard obj = new Wizard();<br>obj.performFire(); // will fire with balls<br>obj.setFireBehavior(new FireWithBomb());<br>obj.performFire(); // now he will throw fire bombs</pre><p>Here’s our new design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*d1SfCuLVCwAp9fk33N6wvg.png" /><figcaption>added fire behavior</figcaption></figure><p>If you have read this far then you have done a great job ! yeahhhh party time. But wait golem and giant are not happy with you as you have not given them any power. Let’s give them a <strong>punch </strong>power. Golem have mega-punch power and giant have….ummm…. giant-punch power 😉. can you add this new puch behavior all by yourself? try it yourself and see our new updated design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*PaTISHoii9TWvO5iGWNB_Q.png" /><figcaption>added punch behavior</figcaption></figure><h3>Conclusion:</h3><p>Now think of each set of behaviors as a <strong>family of algorithms</strong>(<em>see dig below</em>). Note that we have used <strong>composition. </strong>Each fighter <strong>HAS-A </strong>fire behavior and punch behavior to which it delegated fire and punch. Remember to favor composition over inheritance. As you have seen, creating systems using composition gives you a lot more flexibilit. It not only let’s us encapsulate a family of algorithms into their own set of classes, but it also allowed us to change behavior at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*Vg08OepBpz5HadadvaIj0w.jpeg" /></figure><p>Now let’s also cover the formal definition of Strategy pattern:</p><p>The strategy pattern defines a family of algorithms, encapsulates each one, and make them interchangeable. Strategy let’s the algortithm vary independently from the client that uses it.</p><p>You can learn the terminology and theory on google also. I tried to explain it through a example. Hope you liked it.</p><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below (if you have any 😉) ✌️</p><p>References:<br>- Head first design patterns <a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124">book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec05e990f944" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/strategy-pattern-ec05e990f944">Strategy Pattern</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Introduction]]></title>
            <link>https://medium.com/better-programming/design-patterns-introduction-30b9f3c5f7e?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b9f3c5f7e</guid>
            <category><![CDATA[thinking-outside-the-box]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Sun, 06 Jan 2019 08:31:01 GMT</pubDate>
            <atom:updated>2019-05-07T02:39:13.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Om1lfdH6llUENHez7-dgQ.jpeg" /></figure><p>Ever seen a Blueprint of a building/vehicle/toys … ? In real world, a lot of time is invested into <strong>how</strong> to do <em>something</em> before actually <strong>start</strong> doing it. Planning should always come before implementation, same goes for software development also. Every famous <em>software</em> or<em> website</em> or <em>app</em> is made following some design patterns so that it’s easy to maintain, scale and add new features(whenever required).</p><p>Have you ever tried to read the open source projects of big organizations? Do you find them difficult to read or have you ever wondered why they have made so many classes, interfaces, used weird class names with words such as builder, factory, bridge, etc? All because of a simple reason that they follow design patterns and you don’t know much about them.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FHluq5ybFMlnfa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FHluq5ybFMlnfa%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FHluq5ybFMlnfa%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf28a68a5ffd49c93b060fd5f557af09/href">https://medium.com/media/bf28a68a5ffd49c93b060fd5f557af09/href</a></iframe><p>when we start to make a project, we just write code wherever we want to(without any planning). First, we don’t follow OOPS principles properly and Second, we don’t apply design patterns. In the end we are just pushing this huge amount of code.<br>It results in following problems:<br>1. multiple bugs pops up when we try to fix a single bug (a common problem)<br>2. difficult to scale<br>3. extremely hard to add a new feature<br>4. List goes on …</p><p><strong>Design pattern</strong> is a general repeatable solution to a commonly occurring problem in software design. Remember that it is <strong>not a finished design</strong> that can be transformed directly into code. It is a <strong>template</strong> for how to solve a problem that can be used in many different situations. The idea is to speed up the development process by providing tested, proven development paradigm.</p><p>This story is only introduction to design patterns(as title says..duh). Each design pattern will be explained properly in a separate story and links will be added here.</p><ol><li><a href="https://medium.com/@Nitin_code/strategy-pattern-ec05e990f944">Strategy pattern</a></li><li><a href="https://medium.com/@Nitin_code/factory-pattern-c0c284530d40">Factory pattern</a></li><li><a href="https://medium.com/@Nitin_code/abstract-factory-pattern-2193667dcad6">Abstract Factory pattern</a></li><li><a href="https://medium.com/@Nitin_code/decorator-pattern-4f92897e4b4">Decorator Pattern</a></li></ol><p>Design Patterns give you a<strong> shared vocabulary</strong> with other developers. Once you’ve got the vocabulary you can more easily communicate with other developers and inspire those who don’t know patterns to start learning them. It allows you to say more with less. It becomes easy to work in team. It also elevates your thinking about architectures by letting you think at the pattern level, not the nitty gritty object level. Project becomes easy to maintain,scale.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUPGctqlPdtaxvoAus%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUPGctqlPdtaxvoAus%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxUPGctqlPdtaxvoAus%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f5311c42339f310d5fa1a2c47a1a6ee/href">https://medium.com/media/5f5311c42339f310d5fa1a2c47a1a6ee/href</a></iframe><blockquote><strong>Ques 1 : Aren’t libraries and frameworks also design patterns?</strong><br>Well <strong>NO, </strong>You can’t just find a pattern and copy it into your program, the way you can with off-the-shelf functions or libraries. The pattern is not a specific piece of code, but a general concept for solving a particular problem. You can follow the pattern details and implement a solution that suits the realities of your own program.</blockquote><blockquote><strong>Ques 2 : So design patterns can be thought of as algorithms ? 😕<br></strong>Patterns are often confused with algorithms, because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that can achieve some goal, a pattern is a more high-level description of a solution. The code of the same pattern applied to two different programs may be different.</blockquote><blockquote><strong>Ques3 : If I am good with OOPs principles, do I really need to think about Design Patterns? 😎<br></strong>this is one of the true misunderstandings that by knowing the OO basics we are automatically going to be good at building flexible, reusable, and maintainable systems. Constructing OO systems that have these properties is not always obvious and has been discovered only through hard work. These, sometimes non-obvious ways have been collected into a set of patterns called “design patterns”.</blockquote><p>Remember that the best way to use patterns is to load your brain with them and then recognize places in your designs and existing applications where you can apply them. Instead of code reuse, with patterns you get experience reuse. Patterns are not invented, they are discovered !</p><p>Clap 👏 , Comment and share your valuable feedback and don’t forget to ask more questions in comment section below (if you have any 😉) ✌️</p><p>References:<br>1. <a href="https://sourcemaking.com/design_patterns">https://sourcemaking.com/design_patterns</a><br>2. <a href="https://refactoring.guru/design-patterns/what-is-pattern">https://refactoring.guru/design-patterns/what-is-pattern</a><br>3. Head first design patterns book ( <strong>MUST READ !! </strong>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b9f3c5f7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/design-patterns-introduction-30b9f3c5f7e">Design Patterns Introduction</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3-D touch in Android Part 2]]></title>
            <link>https://nitin-code.medium.com/3-d-touch-in-android-part-2-910d3f9382d0?source=rss-9bf4d136e72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/910d3f9382d0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[3d-touch]]></category>
            <dc:creator><![CDATA[Nitin Verma]]></dc:creator>
            <pubDate>Sat, 05 Jan 2019 14:48:25 GMT</pubDate>
            <atom:updated>2019-01-06T02:12:20.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4nHzrlieR8Dm84w2J13Jg.jpeg" /></figure><p>Before you begin with this post, make sure that you have read Part-1 of this two part post series. Click <a href="https://medium.com/@canvas.nv/3-d-touch-in-android-part-1-afb730bc4c15">here</a> to read Part-1.</p><p>click <a href="https://github.com/Ni3verma/3dTouchDemo">here</a> to open github repo.</p><p><strong>Introduction:</strong></p><p>You have come a long way and most of the work is done. Demo app is already working, now we just have to do two things.</p><ol><li>add animations when the dialog peek and pop.</li><li>remove that bug that we noticed in <a href="https://medium.com/@canvas.nv/3-d-touch-in-android-part-1-afb730bc4c15">Part 1</a>(if it’s bug for you)</li></ol><h3><strong>Adding animations 😎</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FDURbX7oesHiaA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FDURbX7oesHiaA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FDURbX7oesHiaA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/68efe7a038e0b31923d1d6e870795b70/href">https://medium.com/media/68efe7a038e0b31923d1d6e870795b70/href</a></iframe><h4><strong>Step 1 : add animation files in anim folder</strong></h4><p>Now is the time to open that mysterious <a href="https://github.com/Ni3verma/3dTouchDemo/tree/master/app/src/main/res/anim"><strong>Anim</strong></a><strong> </strong>folder (in app/src/main/res)in anim folder we have two <strong>.xml </strong>files:<br>(Note that in case you don’t have anim under res,then you have to make one)<br>1) peek_in.xml : animation played when the dialog opens up.<br>2) peek_out.xml : animation played when the dialog closes.</p><p>Notice that everything in &lt;set&gt; tag, happens at the same time. In <strong>peek_in.xml </strong>file we are scaling image from 0 to 1(from nothing to full) and at the same time we are changing it’s alpha property from 0 to 1(from invisible to visible). Note that for this demo I have kept animation part as simple as possible so <strong>peek_out.xml</strong> is almost same as peek_in.xml except that some values are reversed.</p><p>we can also add more tag like translate,rotate and we can also add more properties to tags such as interpolator,duration,repeatCount,repeatMode,etc. Play around these tags and properties to learn more about them.<br>Check out this website to learn more.<br><a href="https://www.tutorialspoint.com/android/android_animations.htm">https://www.tutorialspoint.com/android/android_animations.htm</a><br>don’t just read the code, implement it,tweak it,play with it. That’s how you will learn about it and make your own animations for views.</p><h4><strong>Step 2 : Modify styles.xml</strong></h4><p>click <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/res/values/styles.xml#L11">here</a> to open styles.xml file of github repo. Here we specify that peek_in.xml file is for window enter animation and peek_out.xml file is for window exit animation. we’ll also give this style a name (name=peekAnimation) so that we can refer to this style later in our java file.</p><h4><strong>Step 3 : Add this animation to dialog</strong></h4><p>Now we need to tell dialog to use this animation as it’s window animation(for entry and exit).<br>click <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/java/com/importio/nitin/a3dtouchdemo/MyAdapter.java#L74">here</a> to see this part of code.</p><p>now you are done with animation part .. yeahhhhh !! 😄</p><h3>Removing Bug 🐛</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FGpiCzamVYgVz2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FGpiCzamVYgVz2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FGpiCzamVYgVz2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/458f0b857074ed597deb56d459819e2f/href">https://medium.com/media/458f0b857074ed597deb56d459819e2f/href</a></iframe><p>First try to understand how the code works. Open this(click <a href="https://github.com/Ni3verma/3dTouchDemo/blob/master/app/src/main/java/com/importio/nitin/a3dtouchdemo/MyAdapter.java">me</a>) file of repo. <br>As we have added <strong>touchListener</strong> to the whole view holder of recycler view item, so we will get all touch events.<br>When we long press(more than 250ms) any item of recycler view, then <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/java/com/importio/nitin/a3dtouchdemo/MyAdapter.java#L65">this</a> method runs and dialog is shown.<br>now when we lift our finger up, then <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/java/com/importio/nitin/a3dtouchdemo/MyAdapter.java#L97">this</a> part of code run and dialog hides.</p><p>But when we move our finger then this scroll event(NOTE:not a touch event) is captured by Android and all the further events are not captured by the touchListener that we made so dialog doesn’t hide.</p><p>We can solve it by allowing the recycler view to intercept the touch events(if it gets any). This will happen when we lift our finger off from the screen and touchListener stops getting touch events.<br>So we will add <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/java/com/importio/nitin/a3dtouchdemo/MainActivity.java#L43">this</a> line. Check official documentation of this method <a href="https://developer.android.com/reference/android/view/ViewParent#requestDisallowInterceptTouchEvent(boolean)">here</a>.<br>Then add touchListener on recyclerView.<br>Now our recycler view will intercept the events and we can hide the dialog.<br>check this part of code by clicking <a href="https://github.com/Ni3verma/3dTouchDemo/blob/a5f9ed70fd861619b047b68bd5f5f7d36119c543/app/src/main/java/com/importio/nitin/a3dtouchdemo/MainActivity.java#L72">here</a>.<br>Andddd you are done .. !!<br>Now go out and implement it in your app, make a proper dialog, tweak with animations and impress your users 😉</p><p>I have implemented it in one of my project. Click <a href="https://github.com/Ni3verma/CodeTime/blob/master/extra/ss/peek.png">here</a> to see it.<br>Checkout the whole project on my github account.</p><p><a href="https://github.com/Ni3verma/CodeTime">Ni3verma/CodeTime</a></p><p>CodeTime project is open source. Feel free to contribute to it. ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910d3f9382d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>