<?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 Nisal Pubudu on Medium]]></title>
        <description><![CDATA[Stories by Nisal Pubudu on Medium]]></description>
        <link>https://medium.com/@nisal-pubudu?source=rss-91049dca2089------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WqL8P9kTEP8KT1bfh4u2gg.jpeg</url>
            <title>Stories by Nisal Pubudu on Medium</title>
            <link>https://medium.com/@nisal-pubudu?source=rss-91049dca2089------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:58:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nisal-pubudu/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[Design Patterns for Microservices — Circuit Breaker Pattern]]></title>
            <link>https://nisal-pubudu.medium.com/design-patterns-for-microservices-circuit-breaker-pattern-ba402a45aac2?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba402a45aac2</guid>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 21:09:40 GMT</pubDate>
            <atom:updated>2021-06-26T15:04:26.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns for Microservices — Circuit Breaker Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*e3Nbt6-XZo03VWvU376TKQ.jpeg" /><figcaption>Photo by circuitbreakercity.com</figcaption></figure><p>In my previous article: <a href="https://medium.com/nerd-for-tech/design-patterns-for-microservices-aggregator-pattern-99c122ac6b73"><strong><em>Design Patterns for Microservices — Aggregator Pattern &amp; Proxy pattern</em></strong></a>, I have discussed about Aggregator Pattern &amp; Proxy pattern, how to use those, and why Design Patterns matters in Microservices. Also, if you are a new to Microservices, I highly recommend you go through my previous 2 articles: <a href="https://medium.com/geekculture/introduction-to-microservices-9dcaafa5d882"><strong><em>Introduction to Microservices</em></strong></a> &amp; <a href="https://medium.com/geekculture/best-practices-for-microservices-architecture-9cd896fb41b5"><strong><em>Best Practices for Microservices Architecture</em></strong></a>.</p><p>Have you ever wondered, why there are circuit breakers in your house? If your house is powered by electricity, there must be circuit breakers since they control and protect the wiring circuits that feed outlets in your home. When the electricity comes through the main grid, it always flows through these circuit breakers. Therefore, if the main grid behaves in an abnormal way, or if additional power tries to flow, then the particular circuit breaker will switch off. As a result, the internal wiring circuits of your house will be protected. So, this behavior of circuit breakers is very similar to how the Circuit Breaker Design Pattern works.</p><h3>Circuit Breaker Pattern</h3><p>The Circuit Breaker pattern is a popular design pattern used in Microservices Architecture, that falls under the Sustainable Design Patterns category. In Microservices architecture, a service usually calls other services to retrieve data, and there is the chance that the downstream service may be down. It may be cause by slow network connection, timeouts, or temporal unavailability. Therefore, retrying calls can solve the issue. However, if there is a severe issue on a particular microservice, then it will be unavailable for a longer time. In such case, the request will be continuously sent to that service, since the client doesn’t have any knowledge about a particular service being down. As a result, the network resources will be exhausted with low performance and bad user experience. Also, the failure of one service might lead to <strong>Cascading failures</strong> throughout the application.</p><p>Therefore, you can use the Circuit Breaker Design Pattern to overcome this problem. With the help of this pattern, the client will invoke a remote service through a proxy. This proxy will basically behave as an electrical circuit breaker. So, when the number of failures crosses the threshold number, the circuit breaker trips for a particular time period. Then, all the attempts to invoke the remote service will fail within this timeout period. After the timeout expires, the circuit breaker allows a limited number of test requests to pass through it. If those requests succeed, the circuit breaker resumes back to the normal operation. Otherwise, if there is a failure, the timeout period begins again.</p><p>The Circuit Breaker Design pattern have three states:</p><ol><li>Closed</li><li>Open</li><li>Half-Open</li></ol><h4><strong>Closed state</strong></h4><p>In this state, the Circuit Breaker routs the requests to the Microservice and counts the number of failures in each period of time. That means it work without any failures. But if the number of failures in a certain period of time exceeds a threshold, the circuit will trip and will move to an “Open” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLDpD-OKWRAbRog6D5QiRA.png" /><figcaption>Representing Closed state (blogs.halodoc.io)</figcaption></figure><h4><strong>Open state</strong></h4><p>When Circuit breaker moves to the “Open” state, requests from the Microservices will fail immediately, and an exception will be returned. However, after a timeout, the Circuit Breaker will go to the “Half-Open” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_90KuTuqakzeOT50dMaMDA.png" /><figcaption>Representing Open state (blogs.halodoc.io)</figcaption></figure><h4>Half-Open state</h4><p>In this state, the Circuit Breaker allows only a limited number of requests from the Microservice, to pass through and invoke the operation. If these requests are successful, the Circuit Breaker will go back to the “Closed” state. However, if any request fails again, it goes back to the “Open” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Se9BeQ4TxkA7GDdeZssHZg.png" /><figcaption>Representing Half-open state (blogs.halodoc.io)</figcaption></figure><h3>Why Availability Matters in Microservices Architecture</h3><p>Usually when we develop a system or application using whatever architecture (Microservices/ Monolithic), we guaranteed our clients, that the application availability will be 99.999%. That means there is only 0.001% chance for service downtime. At first, you may think that we don’t even have to care about this 0.001%. In that case let’s do some math.</p><pre><strong>24 hrs * 365 days = 8760 hours per year</strong></pre><pre><strong>8760 hrs * 60 mins = 525600 minutes per year</strong></pre><pre><strong>525600 mins X 0.001% = 5.256 minutes of downtime</strong></pre><p>As you can see, 0.001% of non-availability cost total 5.256 minutes of downtime per year. If you still think this is okay since its just 5 min, you are still wrong. Because when it comes to microservices, we have multiple services. As an example, assume there are 100 microservices in your application.</p><pre><strong>(5.256 * 100)/ 60 = 8.78 hours of downtime</strong></pre><p>So, now you can see how critical it is. If you have 100 microservices, it cost total 8.78 hours of downtime in a year. Obviously, it’s not acceptable at all. Therefore, we need to pay more attention in order to protect our services.</p><h3>Use Case of Circuit Breaker Pattern</h3><p>Let’s take an example to understand, where we can apply Circuit Breaker Pattern in Microservices architecture.</p><h4>Scenario:</h4><p>Assume there are 5 different services in a Microservices application. Whenever it receives requests, the server will allocate one thread to call the particular service. But, due to some failure, the service is little delayed, and the thread is waiting. However it’s okay, if only one thread is waiting for that service. But, if the service is a high demanding service that gets many requests, it is not good to hold. Because more threads will be allocated for this service within some time, and these threads will have to wait.</p><p>As a result, the remaining requests that comes to your service will be blocked or queued. Even though, the service is recovered back, the webserver is still trying to process the requests that in the queue. Because the webserver will never recover, since it receives requests continuously. Eventually this might lead to Cascading failures throughout the application. Therefore, this kind of scenarios will lead to crash your services and even the application.</p><h4>Solution:</h4><p>The above scenario is a perfect example to apply Circuit Breaker Pattern. Assume you have defined threshold for a particular service, as it should respond within 200ms. As I mentioned above, that service is a high demand service, that continuously receive requests. In case, if 75% of those requests are reaching the upper threshold (150ms — 200ms) means that service is going to fail soon. However, if several requests exceed the maximum threshold (200ms) means that service not responding anymore. As a result, it will fail back to the consumer and inform this particular service is not available. So, if you remember the above-mentioned states of this pattern, now we are moving to “Open” state from the “Closed” state.</p><p>As a result, all those requests that comes to the particular service, not going to wait anymore. However, after a timeout, the Circuit Breaker sends ping requests to that service in the background. That means now we are in the “Half-Open” state of the Circuit Breaker pattern. If these requests are successful, the Circuit Breaker will allow to send requests for that service again.</p><p>So, you can use the Circuit Breaker Pattern to improve the fault-tolerance and resilience of the Microservice Architecture and also to prevent the cascading of failure to other microservices.</p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fmw8W-RpvCu0%3Flist%3DPLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dmw8W-RpvCu0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fmw8W-RpvCu0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/38e3841c8ea3795f74c10e71dc6cace1/href">https://medium.com/media/38e3841c8ea3795f74c10e71dc6cace1/href</a></iframe><ul><li><a href="https://martinfowler.com/bliki/CircuitBreaker.html">bliki: Circuit Breaker</a></li><li><a href="https://dzone.com/articles/design-patterns-for-microservices-1">Design Patterns for Microservices - DZone Microservices</a></li><li><a href="https://blogs.halodoc.io/circuit-breaker-with-resilience4j/">Introduction to Circuit Breaker with Resilience4j</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba402a45aac2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns for Microservices — Aggregator Pattern]]></title>
            <link>https://nisal-pubudu.medium.com/design-patterns-for-microservices-aggregator-pattern-99c122ac6b73?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c122ac6b73</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[aggregator]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 18:43:30 GMT</pubDate>
            <atom:updated>2021-06-26T15:29:49.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns for Microservices — Aggregator Pattern &amp; <strong>Proxy pattern</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WVvdNlvCOChI0D_I" /><figcaption>Photo by <a href="https://unsplash.com/@photography37?utm_source=medium&amp;utm_medium=referral">Kirana Kepakisan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s software engineering industry, Microservices architecture has become the most favorable choice for modern application development. Microservice are known to solve various challenges, that developers faced during developing the monolithic applications. However, it has several drawbacks when we use this architecture. Therefore, we need to learn common patterns in these problems and solve them with reusable solutions. As a result, we have several design patterns for microservices. So, in this article I’m going to discuss about two popular Design Patterns in Microservices architecture: <strong>Aggregator Pattern </strong>&amp;<strong> Proxy pattern.</strong></p><p>If you are new to Microservices, I highly recommend you go through my previous 2 articles: <a href="https://medium.com/geekculture/introduction-to-microservices-9dcaafa5d882"><strong><em>Introduction to Microservices</em></strong></a> &amp; <a href="https://medium.com/geekculture/best-practices-for-microservices-architecture-9cd896fb41b5"><strong><em>Best Practices for Microservices Architecture</em></strong></a><strong><em>.</em></strong></p><h3>Why Design Patterns Matter in Microservice Architecture?</h3><p>Choosing a proper design pattern in microservices architecture, decides your application is going to work or not. As I mentioned above, there are several design patterns available for microservices architecture. Therefore, you need to choose the right one, as it will really benefits you. But if you don’t choose the suitable design pattern for your case, the whole system will be unstable and perform badly.</p><h3>01) Aggregator Pattern</h3><p>In Microservices Architecture, we split a large, complex application into small, autonomous, independently deployable services. Therefore, it’s necessary to think about how to collaborate the data returned by each service. In IT industry, aggregator refers to a website or program that collects related items of data and displays them. So, in microservices the Aggregator Design Pattern is a service that receives a request, then makes requests of multiple services, combines the results and responds to the initiating request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*qK2uEGMAn_fXt8ietv4FGg.png" /><figcaption>Image: Representation of Aggregator Design Pattern</figcaption></figure><p>In Aggregator Pattern, there are 3 ways to implement it within Microservices application.</p><ol><li>Scatter Gather Pattern</li><li>Chained Pattern</li><li>Branch Pattern</li></ol><p>To explain this clearer, I will use an example as follows.</p><p>Assume you are a software engineer and your team has been assigned to develop a Microservices application for a University. However, they already have a monolithic system and what you have to do is convert this monolithic system into a microservice application. Imagine you have to develop 4 services as follows,</p><ul><li>A service to get Student Information</li><li>A service to get Marks &amp; its related Information</li><li>A service to get Membership Information</li><li>A service to get Achievements Information</li></ul><p>Moreover, you have 2 consumers named as, <strong>“Grading System”</strong> and <strong>“Enrichment Program System”</strong> for these 4 services.</p><h4>Problem:</h4><p>When it comes to implementing, your team might create 1 microservice for each system, since that’s how we supposed to implement a microservices application. But the thing is, what happen when “Grading System” wants student information and marks information, or “Enrichment Program System” wants membership and achievements information?</p><h4>Solution:</h4><p>So, what you can do is, create a service to consume “student information” and “marks information” services and give the response to the consumer that required (Grading System). Basically what happen is, the newly created service will take the request from the “Grading System” and invoked those 2 services to aggregate their responses and send it back to the “Grading System.” In Aggregator Pattern there are 2 ways to implement this solution.</p><p><strong>Solution 01:</strong> When you invoke the Grading System’s service, you can send a parallel call to the “Student Information” and “Marks Information” services, and get those responses to aggregate them as a single response. Now we can send this response back to the Grading System (consumer). So, this is the first solution and it called as “Scatter gather pattern.”</p><p><strong>Solution 02: </strong>Assume the Marks Information service has a dependency on the Student Information service. In that case, you can’t use the Scatter Gather pattern. So, what we can do is invoke the “Student Information” service and get the Student Code along with the response, then pass to the “Marks Information” service. At last, get the marks and its related information and response back to the Grading System. So, this is the second solution and it called as <strong>“Chained Pattern.”</strong> However, this pattern is slower than the Scatter gather pattern.</p><h3>01.1) Branching Pattern</h3><p>This microservices pattern is a mix of Aggregator and Chain design patterns, that allows simultaneous request or response from two or more independent microservices. As you already know, a microservice may need to get the data from multiple sources including other microservices. The Branching Pattern extends the Aggregator Pattern and provides the flexibility to produce responses from multiple chains or single chain. This design pattern comes handy when you need to convert a large monolithic application into a microservices application. To get things clearer, check the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*VJZQ6QnsP0OXk9MfoVEVSw.png" /><figcaption>Image: Representation of Branching Design Pattern</figcaption></figure><p>As you can see, the service “X” is acting as the aggregator while it is branching out into 2 separate branches. The first branch contains an independent microservice (service “Y”) and second branch contains a chain of services, that has 2 microservices.</p><h4>Benefits of using Aggregator Pattern</h4><ul><li>Scalability of both the x-axis and z-axis</li><li>Easy to understand and implement</li><li>Microservices signature flexibility to internal services</li><li>Providing a single access point for microservices</li></ul><h3>02) Proxy Design Pattern</h3><p>Assume your client has a monolithic application and they decided to move it into microservices architecture. In that case your team might assigned to develop multiple services and deploy those continuously. While developing these microservices, there might be scenarios that some services require changes, like updating their functionalities. Updating a particular service can affect the other services, which consume that services. As a result, this might be led to a whole system break, and also it will hold the development of the application. However, we have a well-known solution for this type of situations: The Proxy Design Pattern.</p><h4>What is Proxy Design Pattern?</h4><p>This pattern is very similar to Aggregator Design Pattern and even consider as a variation of it. But in this case, no aggregation needs to happen on the client, but a different microservice may be invoked based upon the business need. <strong>The proxy pattern also able to scale independently on x axis and z axis as Aggregator Pattern.</strong> So, the main idea behind this pattern is, not to expose each microservice to their consumers and instead it should go through an interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*9c_wp9Rvt_WM--alIlykCw.png" /><figcaption>Image: Representation of Proxy Pattern (tsh.io)</figcaption></figure><p>Let’s take an example to understand how the Proxy pattern work in a microservices application. Assume there is an employee management system, and it has a service to get the leave information of employees. Also, this leave-service work with several other services and they already consuming it. However, you decide to deploy a new version of this leave-service with few changes. As a result of those changes, the consumers of this leave-service going to break, since they didn’t get the required update to work with the new leave-service version. This is where the Proxy Pattern comes in handy.</p><p>To overcome the above situation with the Proxy Pattern, we have to create a Proxy service for that particular service (leave-service). Therefore, all the consumers have to communicate the leave-service through this Proxy Service. As a result, developers don’t need to change anything in consumer side. Because, if a consumer need to communicate with the old version of the leave-service, the proxy will direct the request to the old version, and if a consumer need to communicate with the newer version, the proxy will direct the request to the newer version of leave-service. However, if you don’t see any traffic for the older version of that service, you can decommission that particular version.</p><h4>Semantic Versioning</h4><p>Versioning in a microservices application is very crucial part since it has many services with different versions. As we discussed above, we might need to deploy several versions of a same service. Therefore, the Semantic versioning comes really handy.</p><p>Semantic versioning is a technique, that uses three non-negative integer values to identify the version types. In this technique the version format represent as <strong>“MAJOR.MINOR.PATCH.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*DySBD4scwrcCLvzKlTYRCQ.png" /><figcaption>Image: Basic syntax of semantic versioning (devopedia.org)</figcaption></figure><blockquote>I have discussed about “Versioning Microservices” in the following article. Please refer it for more details.</blockquote><p><a href="https://medium.com/geekculture/best-practices-for-microservices-architecture-9cd896fb41b5">Best Practices for Microservices Architecture</a></p><h4>Service Discovery</h4><p>When using the Proxy pattern in your microservices application, it always better and recommended to use a Service Discovery Tool to search the services. Because, if the infrastructure gets changed in a microservices application, the host-name, and IP addresses can also be changed. But if you have a service discovery tool, the proxy can request it to find the correct version and its IP address, host-name, and etc. There are several popular tools such as, <strong>WSO2 Governance Registry, CONSUL,</strong> and <strong>ZooKeeper.</strong></p><blockquote>Please refer the following link to see and compare the best Service Discovery Tools that available.</blockquote><blockquote><a href="https://www.g2.com/categories/service-discovery">https://www.g2.com/categories/service-discovery</a></blockquote><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDZeXqbFvYNA%3Flist%3DPLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3%26start%3D4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDZeXqbFvYNA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDZeXqbFvYNA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/50cb1394888b0b460bee947506c0ee9f/href">https://medium.com/media/50cb1394888b0b460bee947506c0ee9f/href</a></iframe><ul><li><a href="https://www.edureka.co/blog/microservices-design-patterns#Branch">Microservices Design Patterns | Microservices Patterns | Edureka</a></li><li><a href="https://dzone.com/articles/design-patterns-for-microservices-1">Design Patterns for Microservices - DZone Microservices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c122ac6b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Microservices Architecture]]></title>
            <link>https://medium.com/geekculture/best-practices-for-microservices-architecture-9cd896fb41b5?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd896fb41b5</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 21:45:24 GMT</pubDate>
            <atom:updated>2021-06-09T06:23:19.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKgI-hVkFUo7S8mH" /><figcaption>Photo by <a href="https://unsplash.com/@myleon?utm_source=medium&amp;utm_medium=referral">Leon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous article: <a href="https://medium.com/geekculture/introduction-to-microservices-9dcaafa5d882"><strong><em>Introduction to Microservices</em></strong></a><strong>,</strong> I have discussed about Microservice Architecture, its characteristics, and its advantages/ disadvantages. If you are new to microservices, I highly recommend you to go through that article, unless you are comfortable with basic microservices knowledge. So, in this article I’m going to discuss about best practices that you should know to build successful microservices application.</p><h3>Domain Driven Design</h3><p>When you have to develop a Microservices application, the very first challenge you have to face is, to split a large, complex application into small, autonomous, independently deployable services. If it is not split in proper way, it will be not a loosely coupled Microservices. As a result, it will have all the disadvantages of a Monolith architecture. Fortunately, there is a good solution called Domain Driven Design. This helps your software team and architects to understand the different business domains, so they can design microservices based on those business domains. Therefore, it is important to have a fresh Domain Driven Design, before developing a Microservices application.</p><h3>Prevent Hardcoded Values</h3><p>In microservices architecture, there is a disadvantage, that it has all the associated complexities of the distributed system. So, assume in your microservices application, there are 2 services named as “A” and “B”. In case, if service “A” wants to call service “B”, A should have B’s address. The address might be a host name, URL, or an IP address. But the thing is, some developers used to hardcode this address. There is nothing wrong in that, until your network team decide to change the address. As a result, developer need to change that hardcoded address in service “A” and deploy it again. So, in microservices application, the code should be always dynamic. In this scenario you can use a service discovery tool to discover the other service.</p><h3>Logging</h3><p>Logging is something that you must do, whether you develop a monolithic or microservices application. But the problem is, when it comes to microservices, we spend a lot of time thinking about the business boundaries and the best way to split our application logic and we forget to think about the logs. So, lack of logs is not a good practice, and same goes if you have unnecessary logs than required.</p><h4>Correlation ID</h4><p>Usually in microservices, finding issues and logging them is a bit more complicated than monolithic, because it has multiple services. For example, let’s say there are 3 services named as “A”, “B”, and “C”. Now you’re logging access and error logs for each service. Assume if you find an error in Service B, it might be useful for you to know whether the error was caused by the request coming from Service A or the request sent to Service C. So now you have to know all the requests in the services that are related to. However, if you have a correlation request ID, then you only need to look for that ID in the logs. And you will get all logs from services that were part of the main request to the system. Moreover, you can know which service the main request spends the most time in, and if a service is calling other services more than once.</p><p>So, the point is don’t log everywhere, log only where you initiate the process. However, make sure to log a stack trace to understand where the issue actually happened, otherwise you will get confused and have a hard time while searching where the issue occurred.</p><h3>Versioning Microservices</h3><p>Whether you develop a Microservices or Monolith application, there are two standard versioning techniques, which are popular among the software community: Semantic versioning and Calendar versioning. However, when it comes to microservices architecture, versioning is very useful since developers need to target individual services for updates rather than whole applications.</p><h4>1) Semantic Versioning</h4><p>Semantic versioning is a technique, that uses three non-negative integer values to identify the version types. In this technique the version format represent as <strong>“MAJOR.MINOR.PATCH.”</strong></p><p>Semantic versioning is an ideal practice when you are working on a project with many modules (services) and each module is interdependent on another module. As a result, Semantic versioning is considered as the most suitable versioning technique for microservices.</p><h4>2) Calendar Versioning</h4><p>Calendar versioning is bit similar to the previous discussed technique, the Semantic versioning. However, this approach uses calendar dates instead of non-negative integers. In calendar versioning, it doesn’t strictly require a particular date format, but it must clearly indicate the year, month and day.</p><p>Calendar versioning is considered as a good practice when applications operate on regularly scheduled updates, since it helps developers to find previous or existing versions simply by searching for the release date.</p><blockquote>If you want to know more details about microservices versioning techniques, you can follow this link =&gt; <a href="https://searchapparchitecture.techtarget.com/tip/Get-to-know-4-microservices-versioning-techniques">https://searchapparchitecture.techtarget.com/tip/Get-to-know-4-microservices-versioning-techniques</a></blockquote><h3>Handling Authentication and Authorization</h3><p>When you are implementing these mechanisms within your microservices application, you have to make sure that you follow Global Authentication &amp; Authorization strategy. In this strategy, there is a dedicated microservice that handle authentication and authorization process. Therefore, each business service must authenticate the request before processing it by downstreaming it to the authentication service.</p><h3>Managing Dependencies</h3><p>In microservices architecture, managing dependencies is different than monolithic application since, each service operating on its own. However, a service may need access to another service. As an example, assume there are 2 services named as “A” and “B”. So, when you want to deploy A, if it required to deploy B service too, means you violate the microservices architecture. Therefore, make sure to manage dependencies carefully.</p><h3>Fault Tolerance</h3><p>When you are developing a microservices application, there are high possibilities to have more failures. Therefore, you need to properly manage those. Mostly, if your microservice is dependent on another system to provide a response, and if it takes more time to respond, it will affect your applications overall performance. Fortunately, we can avoid this by using a circuit breaker to timeout the external call and returning a default response or an error. This will keep out failing services and as a result, that microservice will work without any failure.</p><h3>Documentations</h3><p>Even though, most of the developers don’t like to hear this word, documentation is an essential part in any software development. Therefore, you need to document your work properly, otherwise another person will not get a clear idea about the services. However, there is a tool called as <strong>Swagger</strong>, which will help you to generate documentations in real time. So, you can write documents in technical terms and Swagger will convert them into proper and attractive documentations.</p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAlj5sqsv0QU%3Flist%3DPLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAlj5sqsv0QU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAlj5sqsv0QU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/74575630926b43b1b044a4f1b09b0b49/href">https://medium.com/media/74575630926b43b1b044a4f1b09b0b49/href</a></iframe><ul><li><a href="https://www.bmc.com/blogs/microservices-best-practices/">15 Best Practices for Building a Microservices Architecture</a></li><li><a href="https://www.capitalone.com/tech/software-engineering/10-microservices-best-practices/">10 Microservices Best Practices for the Optimal Architecture Design | Capital One</a></li><li><a href="https://dzone.com/articles/microservices-logging-best-practices">Microservices Logging Best Practices - DZone Microservices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd896fb41b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/best-practices-for-microservices-architecture-9cd896fb41b5">Best Practices for Microservices Architecture</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Microservices]]></title>
            <link>https://medium.com/geekculture/introduction-to-microservices-9dcaafa5d882?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dcaafa5d882</guid>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 15:38:40 GMT</pubDate>
            <atom:updated>2021-06-07T15:46:07.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FsVsmsercFQGvHlf" /><figcaption>Photo by <a href="https://unsplash.com/@biancablah?utm_source=medium&amp;utm_medium=referral">Bianca Ackermann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the past decade, software development has been rapidly evolving to keep up with technological advances and consumer needs. As a result, Microservices got its chance to show off what it is capable of. Now everybody is talking about microservices and it currently getting a lot of attention from IT industry. At the same time, some software developers and communities pointing that Microservices Architecture is not a completely new thing but a rebranding of SOA. However, Microservices Architecture offers significant benefits compared to Monolithic Architecture. So, before moving into the Microservices, you should have general idea about Monolithic Architecture.</p><h3>Monolithic Architecture</h3><p>The Monolithic Architecture is considered to be a traditional way of building applications. In this architecture, the whole application is developed as a single unit. Just assume you have developed an application based on Monolithic Architecture. The application has a client-side user interface, business layer that contains several processes, and a database. So, all those are put together as a single unit and it makes the application into one large code base. Therefore, if you want to update or change a simple thing, you must access that whole code base. Moreover, you have to update the whole code base, even for a simple change you do. As a result, you might be needed to put down your whole application for several hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*LelubaFyY-CocEwARCT8HQ.jpeg" /><figcaption>Image: Monolithic Architecture Representation (www.n-ix.com)</figcaption></figure><p>If you think Monolithic Architecture is useless nowadays and it doesn’t have any advantages, you are wrong. Because it has several advantages, such as:</p><ul><li>Easier debugging and testing</li><li>Easier deployment</li><li>Easier performance monitoring</li></ul><p>However, there are a few reasons why this Monolith architecture eventually becomes so difficult to manage, such as:</p><ul><li>The codebase is too big for any single developer to fully understand</li><li>Monolithic applications cannot be develop using different technologies and languages</li><li>If the codebase is difficult to understand, changes made will be harmful to the system</li><li>Even if one feature of the system does not work, the entire application will be affected</li><li>Applications cannot be scaled easily since each time the application needs to be updated, the complete system needs to be rebuilt</li><li>Most of the time, Monolith applications have tightly coupled dependencies</li><li>Development may take lot of time to be built since each and every feature has to be built one after the other</li></ul><p>So, the above weaknesses of the Monolith architecture were the main reasons that led to the evolution of Microservices.</p><h3>What are Microservices?</h3><p>Microservices is an architectural style that structures an application as a collection of small independent services, while a monolithic application is a single unified unit. These small services carry out all the application processes as a separate service. As a result, each service has their own business logic and perform specific functions. Usually each service is packaged as an API so it can interact with the rest of the application components and most importantly, every service can be updated, deployed, and scaled individually.</p><p>In software industry there is no exact definition for microservices, but most of the time people refer Martin Fowler’s microservice explanation as a definition for it.</p><blockquote>In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API.</blockquote><blockquote>-Martin Fowler</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CxRX4gmC4isnQNNm9b66oQ.png" /><figcaption>Image: Monolithic vs Microservice Architecture Representation (xbsoftware.com)</figcaption></figure><h3>Characteristic of the Microservice Architecture</h3><h4>Independent components</h4><p>As you already know, in a microservice application all the services can be deployed, maintained, and updated individually, which gives more flexibility. To achieve that, these services do not share libraries and databases among them. Therefore, we can prevent coupling between these services. Assume there is a bug in one microservice, but it only affects for that particular service and does not influence the entire application. If it is monolithic application, it will impact the entire application. Same goes when adding new features to the application. Because it is much easier to add new features to a microservice application than a monolithic one.</p><h4>Maintained by smaller teams</h4><p>Since a microservice project comprises multiple teams responsible for multiple services, each team should be complete in every aspect. As an example, there must be a developer to handle each field, such as user interface, database, business logic, and even QA. Because each team need to understand everything from consumer to backend. However, teams can work independently of each other, since the services are independent.</p><h4>Flexibility in choosing the technology</h4><p>If you are developing a monolithic application, your entire team have to stick on to a single technology or a stack. However, in microservice architecture, teams are not limited by the technology chosen from the start. They are free to apply various technologies and frameworks for each microservice based on the scenario.</p><p>As I already mentioned, you can develop microservices using different languages. But Java is considered as one of the top choices for building applications with this architecture. Java provides several microservice frameworks, such as Spring Boot, Swagger, Jersey, and Dropwizard.</p><h4>Fault tolerant</h4><p>When developing microservice application, Fault Tolerant considered as a must have feature. Because any service call could fail due to unavailability of the supplier. Therefore, if there is a service failure, you need to maintain that situation. Technically this is a disadvantage compared to a monolithic architecture, as it introduces additional complexity to handle it.</p><h4>Better scalability</h4><p>A major advantage of the microservices architecture is that each element can be scaled independently. It ensures your application is up and running at all times, without wasting extra cost on unused modules. In case of monolithic architecture, the whole application has to be scaled even if there is no need in it. Additionally, every monolithic application has limits in terms of scalability. That means if your application got more users than expected, you might have to rebuild the monolithic application.</p><p><strong>The Scale Cube</strong></p><p>Scale cube is a 3D model of scalability, that defined by “The Art of Scalability” book. The scale cube elaborates the microservices scalability using 3-axis, named as X, Y, and Z. The Scale Cube can be represented by the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YRLaCnSkLdIal2cJD1nrQ.png" /><figcaption>Image: Scale cube representation (dzone.com)</figcaption></figure><p><strong>X-Axis Scaling:</strong> This is the simplest form of scaling. In this scaling, multiple instances of the application are deployed and managed by a load balancer. That means if one instance is not enough, you should be able to spawn other instance while keep processing. This scaling model is usually applied where the architecture is monolithic and the application can’t be split into independent, deployable modules.</p><p><strong>Y-Axis Scaling:</strong> In this scaling, Functional decomposition can be achieved by decoupling your architecture into functions. Basically, it splits the application into a number of separate services and each service only responsible for one function. Microservices is an example for functional decomposing as they are independent and smaller services with their own database.</p><p><strong>Z-Axis Scaling:</strong> This scaling model is similar to X-Axis except, its individual instances process only a subset of data. Each of these instance keeps the same set of code, but at the database level, data is partitioned into different shards. Usually this is responsible for routing the request to appropriate application instances.</p><h3>Advantages &amp; Disadvantages of Microservices</h3><p>Before finishing the article, I would like to highlight the major advantages &amp; disadvantages of the Microservices architecture. These advantages are the reason for Netflix, Google, Amazon, and other tech leaders to adopt the Microservices architecture.</p><h4>Advantages</h4><ul><li>Smaller and faster deployments</li><li>Improved fault isolation</li><li>Ease of understanding</li><li>Better scalability</li><li>Mixed Technology Stack</li><li>Granular Scaling</li></ul><h4>Disadvantages</h4><ul><li>Communication between services is complex</li><li>Developers may need to deal with network latency and load balancing</li><li>Testing is difficult compared to monolithic</li></ul><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFO_qg9ETcT0%3Flist%3DPLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFO_qg9ETcT0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFO_qg9ETcT0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d688c763f567eb39adbacd7e41bc8a7e/href">https://medium.com/media/d688c763f567eb39adbacd7e41bc8a7e/href</a></iframe><ul><li><a href="https://www.n-ix.com/microservices-vs-monolith-which-architecture-best-choice-your-business/">Microservices vs Monolith: which architecture is the best choice for your business?</a></li><li><a href="https://www.edureka.co/blog/what-is-microservices/">What Is Microservices | Introduction To Microservice Architecture | Edureka</a></li><li><a href="https://www.chakray.com/what-are-microservices-definition-characteristics-and-advantages-and-disadvantages-2/">Microservices definition, advantages and disadvantages</a></li><li><a href="https://dzone.com/articles/scale-cube-simplified-scale-model">Scale Cube: Simplified Scale Model for Microservices - DZone Microservices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dcaafa5d882" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-microservices-9dcaafa5d882">Introduction to Microservices</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Docker and Container Based Development]]></title>
            <link>https://nisal-pubudu.medium.com/introduction-to-docker-and-container-based-development-7fe45c463cc3?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fe45c463cc3</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[hypervisors]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 20:36:55 GMT</pubDate>
            <atom:updated>2021-06-06T00:13:42.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6B7_7xQRxxegVAZ_" /><figcaption>Photo by <a href="https://unsplash.com/@andasta?utm_source=medium&amp;utm_medium=referral">Andy Li</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are a newcomer to software engineering industry, and if you are working in a project, you probably heard some fancy words like Docker, Container and Kubernetes in some point. It might be sound familiar to some of you, but since you are here, I will give an introduction to Docker and Container based Development in this article. However, before moving into that, you should have basic knowledge about, previous ways of deploying applications.</p><h3>Hypervisors</h3><p>Even before coming to the Hypervisor generation, we used to deploy our application on physical servers. However, we still use that technology, but rarely thanks to the new technologies. It has many disadvantages on several areas compared to Hypervisor. Because when deploying an application, the application server, database, and web server needs separate physical devices for each one. As a result, it needs massive cost to maintain and most importantly it wastes so many resources.</p><p>The Hypervisor was mainly introduced to overcome the above mentioned disadvantages. In simple terms, a hypervisor is a software layer that creates and runs many isolated virtual machines over single hardware. In virtualization, a hypervisor is a key element, which provides organizations to achieve higher cost savings while improving their deployment speed. There are 2 types of Hypervisors named as, <strong>Type-01</strong> and <strong>Type-02 Hypervisor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*K8W5U-UzXIh2q0Cf4cumKw.png" /><figcaption>Image: Type-01 and Type-02 Hypervisors (www.tophack.io)</figcaption></figure><p>Let’s take Type-01 hypervisor for the explanation. As you can see on the image, the hypervisor is installed on a single high processing hardware box (physical server). Then we create multiple virtual machines on top of this hypervisor. Each of these virtual machines are installed with an operating system such as, Linux or Windows. After all we can install our apps on those operating systems. Now we can call this as a proper virtualize environment.</p><p>In this way, we can solve the resource wastage problem and reduce the cost in reasonable amount. But still, its not enough as expected and there are still few disadvantages remains even in this Hypervisor approach. Such as,</p><ul><li>We need to have multiple operating systems and maintain those.</li><li>Virtual Machines are slow and take a lot of time to boot.</li></ul><h3>Containers</h3><p>To overcome the disadvantages of Hypervisor, we can use Containerized applications. In simple terms, Containers are a solution to the problem of how to get software to run and perform correctly, when moved from one computing environment to another. The Containerized application is an OS-level virtualization method used to deploy and run allocated applications without launching an entire virtual machine for each app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BqrnqASrjfTkSP3eyxb_JQ.png" /><figcaption>Image: Overview of Containerized Application (www.plutora.com)</figcaption></figure><p>As you can see on the image, it has a single high processing hardware box (physical server). Then we install a single operating system on top of that hardware. If you remember, in the Hypervisor we have to create multiple virtual machines on top of hardware box, and then install OS in each of those VMs. So, in the Containerized applications we can solve that problem easily and it make this approach very cost-effective.</p><p>After installing the OS, we create the Container Engine on top of that operating system. As a result, we can create Containers within the engine. Finally, we can create our apps on top of each Containers.</p><blockquote><strong>Note: </strong>These containers are so small compared to Hypervisor’s virtual machines.</blockquote><h3>Docker</h3><p>Docker is a software platform for building applications based on containers. This containerization platform is responsible for packaging your application and its dependencies together in the form of a docker container to ensure that your application works perfectly in any environment. Even though, the Container technology has been around for some time, Docker is the reason for popularizing the technology. However, we can create containers without using Docker, but it will be a lot harder process without it.</p><p>Let’s see some of the components, that you should know to create Docker containerized applications.</p><h4>Docker Engine</h4><p>Docker Engine is simply the application that is installed on your host machine. As the heart of the Docker system, it connects all of the platform’s components including, containers, registry, images, and services in a single location.</p><h4>Docker Image</h4><p>Docker Image is a read-only template used for creating Docker containers. Docker lets companies to create and share software through these Docker images. It contains all of the installations, dependencies, libraries, and application code that necessary to create a fully operational container environment.</p><h4>Docker Container</h4><p>In simple terms, Docker Containers are the running instances of Docker Images. It holds the entire package needed to run the application.</p><h4>Docker Registry</h4><p>This is where you can store your Docker Images. The Registry can be either a user’s local repository or a public repository like a <strong>“Docker Hub”</strong> allowing multiple users to collaborate in building an application. As an example, multiple teams within an organization can exchange or share containers by uploading them to the Docker Hub.</p><blockquote><strong>Note:</strong> Other public repositories: Red Hat Quay, Amazon ECR, Google Container Registry</blockquote><h4>Container Orchestration</h4><p>Assume your application has multiple containers for different services, such as authentication, authorization, and HTTP services. Once you’re ready to deploy your application to Docker, you’ll need a way to configure, scale, and monitor all those containers across your application’s architecture. There are several open-source orchestration systems, such as Kubernetes, Docker Swarm, and Mesos to help you in this process.</p><h4>What is Kubernetes?</h4><p>Kubernetes is a popular open source platform for container orchestration, that allows you to automate deploying, scaling, and operating containerized applications. Even though Kubernetes is most often used with Docker, it can also work with any other containers. Kubernetes provides many features, that helps you to deploy containerized applications, such as,</p><ul><li>Container Deployments and Rollout Control</li><li>Built-in Service Discovery and Autoscaling</li><li>Resource Bin Packing</li><li>Persistent Storage</li></ul><p>Before finishing my article, I would like to explain a bit confusing part about Docker, that it is “not persistence.” That means some believes if we shut down the Docker, everything will be erased from that Docker. However, it is completely wrong, since the Dockers by nature is persistence. So, whatever you do, it will remain from wherever you stop.</p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcUiU8yDdQmw%3Flist%3DPLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcUiU8yDdQmw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcUiU8yDdQmw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eaf1a57efe25c3a1e7f6308ce47944b/href">https://medium.com/media/2eaf1a57efe25c3a1e7f6308ce47944b/href</a></iframe><ul><li><a href="https://www.tek-tools.com/apm/what-is-a-hypervisor">What is a Hypervisor and How It&#39;s Transforming Cloud &amp; VMs?</a></li><li><a href="https://www.cio.com/article/2924995/what-are-containers-and-why-do-you-need-them.html">What are containers and why do you need them?</a></li><li><a href="https://www.edureka.co/blog/what-is-docker-container">What Is Docker &amp; Docker Container | A Deep Dive Into Docker | Edureka</a></li><li><a href="https://www.infoworld.com/article/3268073/what-is-kubernetes-your-next-application-platform.html">What is Kubernetes? Your next application platform</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fe45c463cc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Modern JavaScript]]></title>
            <link>https://medium.com/geekculture/introduction-to-modern-javascript-837ed81f6366?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/837ed81f6366</guid>
            <category><![CDATA[modern-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 14:20:53 GMT</pubDate>
            <atom:updated>2021-06-04T06:24:05.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjSbIfb1ZVYeEsZM" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are a software engineer or undergraduate IT student, you might already work with JavaScript language, since it widely used on both client-side and server-side development. JavaScript is a dynamic and lightweight computer programming language. At first, it was introduced as a scripting language for web development in early 90s by Netscape company. As you already know JavaScript is well-known for the development of web pages, until “node.js” introduced in 2009. With the help of “node.js”, we can use JavaScript outside of the web browsers. As a result, it gained a huge popularity among back-end developers, and for several years, JavaScript has been recognized as the most used programming language in the world.</p><h3>ECMAScript</h3><p>Even though JavaScript is popular language among developers, it had a bad reputation because of not evolving properly along past years. But with the introduction of <strong>ECMAScript 6 (ES6)</strong>, JavaScript got some major changes and updates. So, what is this ECMAScript?</p><p>The acronym ECMA is stand for European Computer Manufacturer’s Association. ECMAScript is a specification for scripting languages such as JavaScript and ActionScript. The ECMA releases standard specifications from time to time. These specifications bring new features to the language which improves the developer experience. As an example ES5 version released with several new array methods named as, “map()”, “reduce()”, “filter()”, along with date functions. When it comes to ES6 version, it is known as one of the biggest ECMAScript release yet. It comes with features such as let/const keywords, classes, destructuring, promises, and so on.</p><blockquote><strong>Note:</strong> JavaScript has its own features which are not part of these specifications.</blockquote><p>In the next chapter, I’ll explain some major changes that introduced in newer versions of ECMAScript.</p><h4>Variable Scoping</h4><p>JavaScript has 3 types of variable declaration keywords named as, <strong>var, let, </strong>and <strong>const.</strong> The “let” and “const” keywords were introduced with the ES6 version. These two keywords provide <strong>Block Scope</strong> variables and constants in JavaScript. But before ES6, JavaScript had only two types of scopes, named as <strong>Global Scope</strong> and <strong>Function Scope.</strong> Let’s see an example to get a clear idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c86b8573f3e134184e4e925a2b5cda/href">https://medium.com/media/50c86b8573f3e134184e4e925a2b5cda/href</a></iframe><p>Output:</p><pre>0<br>1<br>2<br>3<br>4<br>Value after iteration: 4</pre><p>As you can see on the result, the code work without any problem. But if you use <strong>“let”</strong> keyword to declare the <strong>“num” variable</strong> instead of “var”, it will get an error on 6th line. The reason for that because “let” provides block scope. The variable declared using “let” keyword, can be only access within that particular code block. In this case within that for-loop.</p><p>To prevent the above problem, we can declare “num” variable above the for-loop scope and then use within it. Using let/const keywords come very handy, when you have to write a very lengthy script that contains many loops and functions. Because you can declare same name variables in each code block without facing any problem due to block scope behavior.</p><h4>Constants</h4><p>From ES6 version, we can use “const” keyword in JavaScript to declare constant variable. As I mentioned in the above section, “const” has the same behavior as “let” keyword but with one difference. That because constant variable cannot be reassigned. Let’s see it with an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/103779080f9e06536a3d46935085969b/href">https://medium.com/media/103779080f9e06536a3d46935085969b/href</a></iframe><p>As you can see on the gist, I have declared 2 variables using “const” keyword. So, if you run first 2 lines, it will give you an error, while next 2 lines (4 &amp; 5) work without any error. The reason for giving error is obvious, because you cannot reassign values for constant variable.</p><p>The reason for not giving any error in 5th line, because the const is only protecting variable which is not object or array. So even it is constant you can change the value inside it, but still cannot reassign another value.</p><h4>Arrow Functions</h4><p>In JavaScript there are several ways to define a function as shown in the following gist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6af2d3d9c7df9816164f1dd95f26685a/href">https://medium.com/media/6af2d3d9c7df9816164f1dd95f26685a/href</a></iframe><p>As you can see on the gist, I have defined 4 methods in 4 different ways. The first method declaration is the regular way of declaring method in JS. All the other 3 methods are declared as <strong>“Arrow Functions”</strong> that were introduced in ES6. These arrow functions allow us to write shorter function syntax than the regular way. In case if you think that both regular and arrow function behaving same way, look at the following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/588ead8a34359403cfa0a642b11ef017/href">https://medium.com/media/588ead8a34359403cfa0a642b11ef017/href</a></iframe><p>Output:</p><pre>This is function1:  { function1: [Function: function1], function2: [Function: function2] }</pre><pre>This is function2:  {}</pre><p>As you can see on the result, when you call <strong>“this” keyword</strong> inside a regular function, it represent the caller of the function (in this case “obj” object), while arrow function ignore the “this” keyword.</p><h4>Object Handling</h4><p>With newer versions of ECMAScript, objects got some reasonable changes. So, lets see how we can handle those with following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e9fc69524149fc1ad46b33f8d9bdab0/href">https://medium.com/media/5e9fc69524149fc1ad46b33f8d9bdab0/href</a></iframe><p>Output:</p><pre>{<br> name: &#39;Nisal&#39;,<br> age: 25,<br> printDetail: [Function: printDetail],<br> salary: 100000,<br> &#39;project 99&#39;: &#39;Ready for the project&#39;<br>}</pre><p>The “employee” is a standard object, that have usual key &amp; value pair until the “printDetail()” function. Then you can see a key named as <strong>“salary”</strong> but without a value. The reason is, if you define a key in this way you can take value from another module. Assume “salary” value depends on another module, so you can define a variable outside the object and assign value for it. Then the “salary” key will get assigned from that value as you can see on the output.</p><p>Then you can see a Dynamic property named as <strong>“status.”</strong> Dynamic property is a technique of using a placeholder for a key. In the 2nd line of the code, it assigning a key named as <strong>“project99”</strong> for that Dynamic property in that object. As you can see on the output, it replaced with that assigned key. This is really useful when you don’t know, what the key would be at the execution time.</p><h4>Object.freeze() method</h4><p>As the name suggest, this method used to freeze an object. That means if we use this method for an object, we cannot change that object anymore. Let’s understand this with an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a1091fdaba4e7da6d795440c1870007/href">https://medium.com/media/1a1091fdaba4e7da6d795440c1870007/href</a></iframe><p>Output:</p><pre>{ name: &#39;Nisal&#39;, contacts: { mobile: &#39;071&#39;, home: &#39;034&#39; } }<br>{ name: &#39;Nisal&#39;, contacts: { mobile: &#39;999&#39;, home: &#39;034&#39; } }</pre><p>In the above gist, I have created an object and add two properties named as name and contacts. Then I have used “.freeze()” method for that object. After that I have tried to assign a new value for <strong>“name” </strong>property, but as the output shows, it doesn’t affect because of using “.freeze()” method.</p><p>But in the 13 line I have tried to assign a new value for <strong>“mobile” property of “contacts” object</strong>, and it got assigned even though I have used the “.freeze()” method. The reason for that result is, if you use “.freeze()” method for an object, it will freeze only the first-level value of that object. That means it doesn’t affect for second-level (inner-level) objects. So, if you going to use this method, make sure to note this point.</p><h4>Classes</h4><p>A JavaScript class is basically a blueprint for creating objects. If you familiar with Java or C# languages, you might already know about classes. Even though it’s not exactly the same, but still share some similarities. Let’s see how we can use classes in JavaScript with following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17f5f127390c7ced5745f4cb2bda1eb/href">https://medium.com/media/c17f5f127390c7ced5745f4cb2bda1eb/href</a></iframe><p>Output:</p><pre>The Camera is designed by Canon, and it&#39;s Rs:25000</pre><p>As you can see, there are some noticeable differences in JavaScript classes. JavaScript class always have a method called <strong>“constructor” </strong>and it invoked automatically when a new object is created. It is used to initialize object properties as shown in the example. But methods should be declared outside of the “constructor.”</p><p>Moreover, I have used inheritance concept in the example by extending “Camera” class by “DSLR” class. So, DSLR class will inherit all the properties and methods from Camera class. In the child class (DSLR) constructor, you must call <strong>“super()”</strong> method in order to pass the “brand” argument that required by the parent class (Camera). Furthermore, you can easily override methods using classes in JavaScript.</p><h4>Destructuring</h4><p>Destructuring was introduced with ES6 version and it is a special syntax that allows us to unpack arrays or objects into a bunch of variables. Destructuring is also useful when there are complex functions that have a lot of parameters, default values, and so on. Let’s see how we can use Destructuring in JS with following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7b8309349f338ffdc990d030584301b/href">https://medium.com/media/c7b8309349f338ffdc990d030584301b/href</a></iframe><p>Output:</p><pre>Nisal Pubudu<br>Nisal Pubudu<br>Full name: Nisal Pubudu</pre><p>In the above gist, I have created an object named as “student” and then access those properties in regular way. Then I have used object destructuring syntax to assign values to three variables using the values from their corresponding keys on the student object. As you can see both proceeds the same output even though the destructuring syntax is simple.</p><p>Also, you can see there is function called “fullName()” that supposed to print full name of the student. For that function, it only required “fName” and “lName” fields. So, I don’t need entire student object in that case. Therefore, I have used destructuring syntax to achieve that as shown in the example.</p><p>Moreover, you can achieve the array destructuring as shown in the following example.</p><pre><strong>const animals = [&quot;Lion&quot;, &quot;Parrot&quot;, &quot;Shark&quot;];</strong></pre><pre>//array destructuring<strong><br>const [Mammal, Bird, Fish] = animals;<br>console.log(`${Mammal}, ${Fish}`); </strong>//Lion, Shark</pre><h4>Promises</h4><p>Promises are the most common way of handling asynchronous operations in JavaScript. Before promises, developers have to use callbacks to handle the asynchronous operations. Therefore, they have to create multiple callbacks within the callbacks, and eventually this bad practice got a slang; <strong>“The Callback Hell.”</strong> As a result, ES6 introduced Promises to handle multiple asynchronous operations easily.</p><p>General behavior of Promises in JavaScript is; when we define a promise in JS, it will be resolved when the time comes, or it will get rejected. That is basically the whole idea behind the Promises.</p><p>There are 3 states of the Promise object.</p><ul><li><strong>Fulfilled:</strong> Indicates that the promised operation was successful.</li><li><strong>Rejected: </strong>Indicates that the promised operation was unsuccessful.</li><li><strong>Pending:</strong> Promise is still pending (not fulfilled or rejected yet).</li></ul><p>Let’s see how we can use Promises in JS with a simple example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f04d4e9ce7fdc9c144d0aaeeafe0836/href">https://medium.com/media/3f04d4e9ce7fdc9c144d0aaeeafe0836/href</a></iframe><p>Output:</p><pre>Promise is resolved successfully!!!</pre><p>As you can see on the gist, I have created a promise named as “myPromise” and it takes two parameters, one for success (resolve) and one for fail (reject). The “condition” variable gets the return value of the “task()” function. For the simplicity of explaining, the “task()” function always return “true” as the value.</p><p>Then the Promise will check the condition, and if it is true, the Promise will be resolved, otherwise it will be rejected. When we using the Promise, “then( )” method will be called after the Promise is resolved. Then we can decide what to do with the resolved Promise. But if the Promise fails, then we need to use the “catch()” method. In this scenario, it met the condition of the promise, and as a result Promise will be resolved.</p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJc2iW4yVv38%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJc2iW4yVv38&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJc2iW4yVv38%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/68dc968947c229b6ca0a10da856ffdb1/href">https://medium.com/media/68dc968947c229b6ca0a10da856ffdb1/href</a></iframe><ul><li><a href="https://www.tutorialspoint.com/javascript/javascript_overview.htm">JavaScript - Overview</a></li><li><a href="https://dev.to/kartik2406/what-is-ecmascript-what-are-its-new-features-31ck">What is ECMAScript? What are its new features?</a></li><li><a href="https://www.geeksforgeeks.org/javascript-promises/">JavaScript | Promises - GeeksforGeeks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837ed81f6366" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-modern-javascript-837ed81f6366">Introduction to Modern JavaScript</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding The Memento Design Pattern]]></title>
            <link>https://nisal-pubudu.medium.com/understanding-memento-design-pattern-5c4f09be639?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c4f09be639</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[behavioral-patterns]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[memento]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Thu, 27 May 2021 22:51:50 GMT</pubDate>
            <atom:updated>2021-05-29T01:00:53.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u8-r3bAYJ1F8tnQv" /><figcaption>Photo by <a href="https://unsplash.com/@wilsonjim?utm_source=medium&amp;utm_medium=referral">Jim Wilson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Memento Pattern (a.k.a. Snapshot Pattern) is a Behavioral design pattern, and it’s used to save and restore previous state of an object. If you want to develop an application, that has undo or rollback functionality, you should go with Memento Design Pattern. Most of the software developers use this pattern whenever they want to develop such functionality within their application.</p><p>A simple example to understand the Memento pattern’s concept is, Windows restore point system. In Windows, we create restore points because we can use those to restore our OS into a previous state, if something breaks or system crashes.</p><p>The Memento Design Pattern has 3 components know as, <strong>Originator, Caretaker, and Memento.</strong></p><p><strong>Originator:</strong> The object that we need to maintain the state. Basically, the Originator object creates a memento object to store its internal state. As a result, the Originator object knows how to save and restore itself.</p><p><strong>Caretaker:</strong> The object that keeps the track about Originator. Basically, Caretaker knows why and when the Originator needs to save and restore itself.</p><p><strong>Memento:</strong> The object that contains basic state storage and retrieval capabilities. Usually, the Memento object is immutable and pass it’s the data only once, through the constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*gJ5GDN5_8BKW-XjVwdSDfg.png" /><figcaption>Image: Memento Pattern UML representation (dotnettricks.com)</figcaption></figure><p>When implementing Memento Design pattern, the Originator coupled with the Memento and pass the state into the Caretaker. So, whenever we need go back into the previous state, we have to talk to the Caretaker and we check the previous state, then move.</p><p>So, in the next chapter, I will explain how to apply Memento Design Pattern with a real-world example using Java.</p><h3>Use case of Memento Design Pattern</h3><p>Assume there is a sport club, that require a software to keep track on their players’ rank. The player rank will be measured according to two facts: <strong>“performance”</strong> and <strong>“health state.”</strong> So, the sport club considers these two facts, when assigning ranks to their players in every training session.</p><p>In a training session, a player can score performance marks up to 100 and lowest is 0. The health state comes with 2 different states named as, <strong>“Healthy” </strong>and <strong>“Unhealthy.”</strong> If a player can perform well and get marks more than 80 while getting “Healthy” as the health state, that player will receive <strong>“Excellent”</strong> rank in that session. Also, there are 4 more ranks, known as <strong>Good, Average, Poor, </strong>and <strong>Very Poor.</strong> But all these marks, health states, and ranks valid only for that particular training session. Whenever they begin a new session in another day, players will be assigned with new marks and states for that session.</p><p>Additionally, the sport club required a functionality to undo the progresses of sessions. Because there are some situations, the coach might need to undo the recent sessions details and go back to a previous session. Especially when a player tests positive for a drug test or if they perform any unlawful act, their participation in several sessions will be removed. As a result, the coach has to roll back their progress according to that particular scenario.</p><p>Now let’s see the implementation of this example.</p><h4>Step 01:</h4><p>As the first step I have created a class called <strong>“Rank”.</strong> Within this class I have defined 3 fields named as “performance”, “health”, and “rank.” Also, I have declared a method named as <strong>“rankGenerator()”</strong> that responsible for generating the player rank based on performance and health state. <em>Refer the following gist.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19c1cb6e325a6822e1e7271381fab26b/href">https://medium.com/media/19c1cb6e325a6822e1e7271381fab26b/href</a></iframe><p>Also, I have created an Enum to hold the health state types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8af8e26507f9c802a30878b137e5e5/href">https://medium.com/media/0f8af8e26507f9c802a30878b137e5e5/href</a></iframe><h4>Step 02:</h4><p>As the second step, I have created the <strong>“Player” class as the Originator </strong>and <strong>“RankMemento” class as the Memento.</strong> Within the “Player” class I have implemented a method called <strong>“addRank()”</strong> to add the rank details of players to an Array List. Then I have implemented a method called <strong>“getRankList()” </strong>to return a cloned object from the Array List. The reason for using “clone()” method is, to prevent the referring to original object.</p><p>In this application, the Memento class (RankMemento) is implemented within the Originator class (Player). But if you want, you can implement those two classes separately. Moreover, within the same Originator class I have created two specific methods named as <strong>“saveRank()”</strong> and <strong>“revertRank()”.</strong></p><p>The “saveRank()” method is responsible for giving the state of the player to the <strong>Caretaker (RankHistory). </strong>Therefore, it return an instance of “RankMemento” by passing a cloned object from the Array List.</p><p>The “revertRank()” method is responsible for reverting the current state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93d6acac9796411cf5ea223cbb06d549/href">https://medium.com/media/93d6acac9796411cf5ea223cbb06d549/href</a></iframe><h4>Step 03:</h4><p>Now I have implemented the <strong>“RankHistory” class as the Caretaker.</strong> This class is responsible for keep track on “RankMemento” class. Within the “RankHistory” class, I have created a Stack to store objects of “RankMemento” class as Last In, First Out (LIFO) order. So, when we use “reverRank()” method, we can have the last object save within the Stack. <em>Refer the following gist.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff013f886d9e6424dd0b651f472bd158/href">https://medium.com/media/ff013f886d9e6424dd0b651f472bd158/href</a></iframe><h4>Step 04:</h4><p>At last we can run our application to check the output. <em>Refer the following gist.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6800e3477eb5dcfec2b2c36f19b130df/href">https://medium.com/media/6800e3477eb5dcfec2b2c36f19b130df/href</a></iframe><p>Output:</p><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}, Rank{, rank=&#39;Poor&#39;}]}</pre><p>As you can see on the gist, the coach has added 2 training session details (Line 9 &amp; 10) and save those using the “saveRank()” method (Line 13). Assume there were 2 training session on that week. Within the next week there was another session and he has to add those details too (Line 16). Again he uses “saveRank()” method and repeat the same thing for another week.</p><p>As you can see on the output, player ranked generated according to the passed arguments and system is working as expected so far. Now lets see how we can revert those using “revertRank()” method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9290f8afddead93f5f72512667de9d69/href">https://medium.com/media/9290f8afddead93f5f72512667de9d69/href</a></iframe><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}, Rank{, rank=&#39;Poor&#39;}]}</pre><pre><strong>------------------Start Reverting------------------</strong></pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}, Rank{, rank=&#39;Poor&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}, Rank{, rank=&#39;Very Poor&#39;}]}</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}]}</pre><pre>Nothing left to Undo</pre><pre>Player{rankList=[Rank{, rank=&#39;Excellent&#39;}, Rank{, rank=&#39;Good&#39;}]}</pre><p>As you can see on the output, even we called the “revertRank()” method, it looks like it doesn’t affect at first. However, other method-calls worked as expected. So, what’s wrong with the first method call?</p><p>What happen here is, we add a new rank to the player and gave it to the Caretaker. After that, we called the “revertRanked()” method on Line 28. That means we are asking from Caretaker to give us the previous rank details of a player. So, what Caretaker does is, it will give us the last saved rank details, since the “revertRanked()” method return it from the Stack. So, this returned object (rank details) is none other than the last object we saved before calling our revert method. That’s the reason, why we see this result in the above output. Therefore, we need to <strong>remove the “saveRank()” method-call on line 23</strong>, and it will work as expected.</p><p>Moreover, if you confused about why the output prints <strong>“Nothing left to Undo”</strong> even though it has 2 more items (rankings). It simply because it has nothing to do with a single item, but instead with the version/set. If you pass those to the Caretaker one by one, those will be reverted one by one. But if you save several items (rankings) at a time, those will be reverted as a single version/set.</p><p>If you are interested, you can use the following GitHub link to see my complete implementation of Memento Design Pattern.</p><p><a href="https://github.com/nisal-kumara/krish-lp-training/tree/master/Design%20Patterns/Memento">nisal-kumara/krish-lp-training</a></p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPwm-jrG2ZVA%3Fstart%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPwm-jrG2ZVA&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FPwm-jrG2ZVA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/48bb0aa1e3a5498079989fda1a5fcf47/href">https://medium.com/media/48bb0aa1e3a5498079989fda1a5fcf47/href</a></iframe><p><a href="https://howtodoinjava.com/design-patterns/behavioral/memento-design-pattern/">Memento Design Pattern - Memento Pattern in Java - HowToDoInJava</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c4f09be639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding The Chain of Responsibility Pattern]]></title>
            <link>https://medium.com/geekculture/understanding-the-chain-of-responsibility-pattern-d729ef84621c?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/d729ef84621c</guid>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[behavioral-design-pattern]]></category>
            <category><![CDATA[java-development]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Wed, 26 May 2021 12:19:25 GMT</pubDate>
            <atom:updated>2021-05-26T13:02:21.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NV6bysmEzk1Ry_7V" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Chain of responsibility pattern is a behavioral design pattern that we use to achieve loose coupling in our software design, where a request from the client is passed to a chain of objects to process them. The request will receive through a handler and the objects in the chain will decide themselves who will going to process that request. Each of these objects contain certain type of commands to handle that request. If a particular object cannot handle that request, it will pass the request to the next object in that chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqHGES91TwX_KazIOB8fAg.png" /><figcaption>Image: Chain of responsibility pattern concept (educative.io)</figcaption></figure><p>So, the main purpose of this pattern is avoiding the coupling. As an example, when sending messages to a receiver, sender do not know who the receiver is, and receiver do not know who the sender is. As a result, receiver can perform its task without knowing who send the message and same goes with the sender as well. That means we can <strong>decouple</strong> <strong>sender and receiver</strong> through this design pattern.</p><h4>Structure of the Chain of Responsibility Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*cgS_U86kK-ToUoI-F5BSeQ.png" /><figcaption>Image: UML Representation (programmergirl.com)</figcaption></figure><p>As you can see on the UML diagram, it has 3 type of components named as, Client, Handler, and Concrete-Handler.</p><p><strong>Handler:</strong> It defines an interface for handling the requests. Also, this can be an abstract class which will primarily receive the request and forward the request to chain of handlers.</p><p><strong>Concrete handlers:</strong> These are responsible for handle the requests they receive. If a particular handler cannot handle the request, it sends the request to its successor.</p><p><strong>Client:</strong> Sends requests to the first object in the chain that may handle the command.</p><blockquote>Note: The request can be sent to any handler in the chain, but it doesn’t have to be the first one.</blockquote><h3>Use case of Chain of Responsibility Pattern</h3><p>In this chapter, I will explain how to apply Chain of Responsibility Pattern with a real-world example using Java. Assume, there is company that provide a system for employees to request leave, based on several facts. So, the company will consider those facts before approving their leave. For example, those might be <strong>number of days</strong>, <strong>employee tier (level)</strong>, and <strong>reason</strong> for the leave. Based on these facts, the leave request will forward to a specific person (leave handler), who can handle those requests. The person might be a <strong>Team Leader, Project Leader, HR, or Manager.</strong> If an employee requests a leave for 7 days or less, the Team Leader will handle that request. But before approving the leave request Team Leader checks the employee’s tier. If the employee tier is within the acceptable range, then the Team Leader will approve the leave request.</p><p>If an employee requests a leave for 14 days or less, the Team leader cannot handle that request, since he only has authority to approve a leave up to 7 days. In that case the request will be pass to the Project Leader, who have authority to handle that request. Then, he will begin the approval process and its same as the previous one.</p><p>However, in the above scenarios they don’t check the reason for requesting a leave. But when it comes to the HR and Manager level, they will check the reason for requesting a leave. If an employee request up to 21 days, the HR will handle that and if its more than 21 days, the Manager will handle that. When they are handling the request, they will check if the reason is a <strong>regular, critical, </strong>or<strong> special</strong> one. Then they will approve or deny the request based on those facts.</p><p>Now let’s see the implementation of this example.</p><h4>Step 01</h4><p>As the first step, I have implemented the <strong>“Leave”</strong> class. Within the “Leave” class I have defined fields like<strong> “numberOfDays”, “empTier”, and “reason.”</strong> Those are the facts, that the company going to consider before approving the leave request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2e68f365172ff4e6f4fe5a79942acf8/href">https://medium.com/media/d2e68f365172ff4e6f4fe5a79942acf8/href</a></iframe><h4>Step 02</h4><p>As the second step, we have to create the handler class. According to the scenario, I have created an abstract class named as <strong>“LeaveHandler.”</strong> Then I have created the “LeaveHandler” object within the class, because the handler should know about its successor.</p><p>Also, I have created an abstract method that accepts “Leave” class object. As a result, every class that going to extend “LeaveHandler” class must implement this method within their class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a13da5954c9d4b2378d8416db9f6643/href">https://medium.com/media/3a13da5954c9d4b2378d8416db9f6643/href</a></iframe><h4>Step 03</h4><p>Now we have to implement a separate class for each request approver (Concrete Handlers) in this company. As a result, I have created a separate class for Team Leader, Project Leader, HR, and Manager. All these classes extend the “LeaveHandler” class and implement the <strong>“applyLeave”</strong> method within them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31e71810b41dcded76663ae818498565/href">https://medium.com/media/31e71810b41dcded76663ae818498565/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7e8fb33e939ac38eddbfb5850fa12af/href">https://medium.com/media/b7e8fb33e939ac38eddbfb5850fa12af/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f75e645cf361db2d7f4ec46f444ffd5/href">https://medium.com/media/6f75e645cf361db2d7f4ec46f444ffd5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e3bbfc0bfc51fdf42606dd8bd149c68/href">https://medium.com/media/3e3bbfc0bfc51fdf42606dd8bd149c68/href</a></iframe><p>Also, I have created an Enum to hold the reason types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4a7938ae79bc06579e645cc24cdc5e/href">https://medium.com/media/3d4a7938ae79bc06579e645cc24cdc5e/href</a></iframe><p>As you can see, the “applyLeave” method contains the core logic of these classes. So, whenever a leave request receives to the handler, it will pass to the Team Leader. If the Team Leader has authority to take action on that request, he will process the and give the result (approved/ denied). If he does not have the authority, he will pass it to the next person (Project Leader) in the chain. If no one has authority to take action on a request (<em>if an employee request more than 21 days and reason is “Special”</em>), then it will be passed to the Manager (end of the chain), and he will give the response for that request.</p><h4>Step 04</h4><p>At last we can run the application</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac6a62066370b815c8ee5c667ca9ba1/href">https://medium.com/media/fac6a62066370b815c8ee5c667ca9ba1/href</a></iframe><p>Output:</p><pre>Your leave days has been APPROVED by TeamLeader<br>Your employee Tier level is too low for request 5 days<br>Your leave days has been APPROVED by Project Leader<br>Your leave days has been APPROVED by HR<br>Your leave request has been DENIED by HR<br>Your leave days has been APPROVED by Manager</pre><p>If you are interested, you can use the following GitHub link to see my complete implementation of Chain of Responsibility pattern.</p><p><a href="https://github.com/nisal-kumara/krish-lp-training/tree/master/Design%20Patterns/ChainOfResponsibility">nisal-kumara/krish-lp-training</a></p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiOOnctEDp84%3Fstart%3D7&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiOOnctEDp84&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FiOOnctEDp84%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/28e54c2b3f3e40ce04efa3566e134fa6/href">https://medium.com/media/28e54c2b3f3e40ce04efa3566e134fa6/href</a></iframe><p><a href="https://www.geeksforgeeks.org/chain-responsibility-design-pattern/">Chain of Responsibility Design Pattern - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d729ef84621c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/understanding-the-chain-of-responsibility-pattern-d729ef84621c">Understanding The Chain of Responsibility Pattern</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Builder Design Pattern]]></title>
            <link>https://nisal-pubudu.medium.com/understanding-builder-design-pattern-ce48a29b79?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce48a29b79</guid>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Tue, 25 May 2021 07:09:51 GMT</pubDate>
            <atom:updated>2021-05-26T00:39:31.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P7qedShSkyIKoGu_" /><figcaption>Photo by <a href="https://unsplash.com/@danist07?utm_source=medium&amp;utm_medium=referral">贝莉儿 DANIST</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Builder is a Creational design pattern, and as the name suggests, it is used to build objects. If we are developing complex application, usually we have to deal with complex objects. Those objects can be dependent on several sub-objects and also may require an elaborate construction process. This is where Builder Design Pattern comes to save our day. Therefore, the main purpose of using Builder pattern is to divide the construction of a complex object from its representation, so that the same construction process can create different representations.</p><p>Let’s take an example to make things more clear. Assume that, there is a hotel reservation website that we can use to search hotels based on our interests. When we want to reserve a hotel, we can choose different options such as, room type, how many nights you are going to stay, gym and bar access, attending tours (organized by the hotel), and so on. But the thing is everyone do not want all these options. Someone may only need to attend tours and he/she doesn’t want the gym and bar access. There might be another person that only interested in gym and bar access and vice versa. However, room type and the nights options are must for everyone, because whenever you are booking a hotel, room type and nights must be clarified.</p><p>Based on this scenario, if we use traditional approach to develop this application, we have to create multiple constructors based on each case. Because there should be a separate constructor to represent each case. As a result, the code will get more complicated. Therefore, we can use the Builder design pattern to prevent such result.</p><h3>Use case of Builder Design Pattern</h3><p>In this chapter, I will explain how to apply Builder Design Pattern with a real-world example using <strong><em>JavaScript</em></strong>. In fact, I will use above scenario to implement this application.</p><h4>Regular implementation</h4><p>As I described above there are several ways to implement this application. Whatever the language is there is always a traditional way to implement and same goes with JavaScript as well. So, Let’s see how we can achieve this in the traditional way and after that, we can move to the design pattern approach in JavaScript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a5508e9effc4890dbc44f25e3efdee/href">https://medium.com/media/d1a5508e9effc4890dbc44f25e3efdee/href</a></iframe><p>Output Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*uK4IlZUsDYCHAexLvVZdWw.png" /></figure><p>As you can see, I have created 2 classes named as <strong>“HotelBooking” </strong>and <strong>“Tour”.</strong> The “HotelBooking” class is responsible to create object whenever an user reserve a hotel. Also, the “Tour” class will be used to create object whenever user choose tour as an option while booking the hotel.</p><p>So, this is the regular way of implementing above scenario in JavaScript. But what is the issue with this implementation since it works without a problem according to the output result. Because if you want to select <strong>“tours”</strong> as an option while ignoring other options, still you must pass default value (<strong>undefined</strong>) for every parameter in the constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16c555f7931856f875e5bb8073034405/href">https://medium.com/media/16c555f7931856f875e5bb8073034405/href</a></iframe><p>Output Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*bVyLMTRAYckW57LJxEIOkg.png" /></figure><p>As you can see, you have to pass 2 undefined values as result of choosing “tour” option. So, this is not a good practice at all. Therefore, we can implement this scenario using Builder Pattern.</p><h4>Classic Builder Pattern approach</h4><p>In Builder pattern, there are 2 different ways that we can use it. The first approach is classic way of implementing Builder pattern in JavaScript, while other one is more JavaScript focus approach. So, let’s see how the implementation looks like in the classic builder pattern approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eb5348763d8b39cf31759fac1059c75/href">https://medium.com/media/6eb5348763d8b39cf31759fac1059c75/href</a></iframe><p>Output Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*t_v36Z3apMJY_-KCFhyPOw.png" /></figure><p>In this approach, I have created a class called <strong>“HotelBuilder”</strong>, that take all the parameters we required to create the <strong>“HotelBooking”</strong> object. In our case <strong>“roomType”</strong> and <strong>“nights”</strong>. So, in this approach we going to use this “HotelBuilder” class to create the object instead of “HotelBooking” class.</p><p>After that we need to create separate methods for each parameter within that class. Each of these methods return <strong>“this” </strong>keyword to return the builder object back. As a result, it will allow us to chain these methods together. Therefore, we only need to pass the parameters that we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08028a95da5e1be9db302891619c0b0b/href">https://medium.com/media/08028a95da5e1be9db302891619c0b0b/href</a></iframe><p>Output Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*E8sm7xVdmmKR9GnMR_A_Pg.png" /></figure><p>As you can see, if you want choose tour, you only need to pass the parameter for that one. Because JavaScript engine will assign <strong>“undefined”</strong> as the default value for other parameters. Therefore, if users want different options, we can chain these methods to pass the parameters that necessary.</p><p>So, Builder pattern makes this application more robust and effective one than the previous approach. Because you only need to pass necessary parameters. But still there is a more advanced and cleaner way to implement Builder pattern in JavaScript. Let’s see how we can implement that in following example.</p><h4>Best Builder Pattern approach</h4><p>As I mentioned above this is more advanced and cleaner way to implement Builder pattern in JavaScript. In this case we don’t use a builder class as the previous approach. Instead we can use the <strong>“HotelBooking”</strong> class directly and pass those optional parameters as a single <strong>JSON object.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2af7f12b4ab445ef1a27e9f3530e242/href">https://medium.com/media/e2af7f12b4ab445ef1a27e9f3530e242/href</a></iframe><p>Output Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*M0XARDVTc3pcUCpI0LWO3Q.png" /></figure><p>As you can see, the newer Builder Pattern approach is way cleaner and easier implement compared to previous implements. As a result, this approach is recognized as the best way to implement Builder Pattern in JavaScript. Also, in this approach we can <strong>assign</strong> <strong>custom default value for parameters other than “undefined”.</strong></p><p>If you are interested, you can use the following GitHub link to see my complete implementation of Builder Design Pattern.</p><p><a href="https://github.com/nisal-kumara/krish-lp-training/tree/master/Design%20Patterns/Builder">nisal-kumara/krish-lp-training</a></p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FubG_5_QnbkE%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DubG_5_QnbkE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FubG_5_QnbkE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44c43783a1066fcea274f0a3721a1bc/href">https://medium.com/media/e44c43783a1066fcea274f0a3721a1bc/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM7Xi1yO_s8E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM7Xi1yO_s8E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM7Xi1yO_s8E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/306c55fe204da47270fe12970cf21591/href">https://medium.com/media/306c55fe204da47270fe12970cf21591/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce48a29b79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Prototype Design Pattern]]></title>
            <link>https://nisal-pubudu.medium.com/understanding-prototype-design-pattern-5242b4e1c088?source=rss-91049dca2089------2</link>
            <guid isPermaLink="false">https://medium.com/p/5242b4e1c088</guid>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[prototype-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nisal Pubudu]]></dc:creator>
            <pubDate>Mon, 24 May 2021 05:35:32 GMT</pubDate>
            <atom:updated>2021-05-26T11:55:27.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QRT46dhwYtvPkI38" /><figcaption>Photo by <a href="https://unsplash.com/@amayli?utm_source=medium&amp;utm_medium=referral">Amélie Mourichon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Prototype is a Creational design pattern, that lets you clone existing objects without making newer objects from the same classes. The main reason for that, some object creations may be very costly (time and resource consuming), so instead of making those objects from the scratch we can clone them from existing objects when we need one. Therefore, the existing object acts as a prototype and contains the state of the object. However, we can change properties of that newly cloned object whenever it required. Because of that, the Prototype approach will save you processing time and resources of your program.</p><p>As I mentioned above, the Prototype pattern mostly used when we need to create several instances of a class and each instance exactly same to each other or has minor differences. In the implementation process we used a method named as <strong>“clone()”</strong> and it’s the simplest approach to implement the Prototype pattern. However, based on your use case you can implement your own clone() method.</p><p>When you implement the Prototype pattern you must be aware about the copy of object you need, whether it’s a <strong>Shallow copy</strong> or a <strong>Deep copy.</strong></p><p>In shallow copy, only attributes of primitive data type are copied from an object, without its reference. However, in the deep copy, it will copy each and everything from the object including its references.</p><h3>Use case of Prototype Design Pattern</h3><p>In this chapter, I will explain how to apply Prototype Design Pattern with a real-world example using Java.</p><p>The following application is built for a tour company, that offer different tour packages such as, Tour Sigiriya, Honeymoon, Hill Country tour, and so on. Assume if we don’t use Prototype Design Pattern, we may need to create new object (a Tour object) each time when it needs to create these type packages with few differences. But since we use Prototype Design Pattern in this application it’s not necessary.</p><p>The following illustrate will give you a general overview of this implementation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*zdUxQueqrowlwS7ToIr3Pg.png" /><figcaption>Image: General overview of the implementation</figcaption></figure><p>As the first step I have created an abstract class named as <strong>“Tour”</strong> that contains 3 attributes with getters and setters for each one. Inside the “Tour” class I have implemented the <strong>“clone()”</strong> method as a result of implementing <strong>“Cloneable” </strong>interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce1313589c4f1a3900ea62ade66780f/href">https://medium.com/media/8ce1313589c4f1a3900ea62ade66780f/href</a></iframe><p>Then I have created 2 classes named as <strong>“TourSigiriya</strong>” and <strong>“HoneyMoon”</strong> that extends the “Tour” class. As a result, those classes will inherit all getters and setters from the “Tour” class. Additionally, these two classes also contain 2 attributes, that specific to each class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def79a71279b59fe1ba4b16aaa5d598e/href">https://medium.com/media/def79a71279b59fe1ba4b16aaa5d598e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52c43604c8896ac43b58e730d15078cb/href">https://medium.com/media/52c43604c8896ac43b58e730d15078cb/href</a></iframe><p>After that I have created the <strong>“TourReg”</strong> class. In this class I have implemented a constructor, and whenever we create the instance of this class it will invoke the <strong>“initializingTours()”</strong> method.</p><p>When that method gets invoked, it will create separate instances from both of those classes (TourSigiriya and HoneyMoon). Moreover, I have used a HashMap to keep those instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba1271e37e9bae529733a9e23fb1c74/href">https://medium.com/media/dba1271e37e9bae529733a9e23fb1c74/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9368d9c801c35e6ead167f2e9b3d49b3/href">https://medium.com/media/9368d9c801c35e6ead167f2e9b3d49b3/href</a></iframe><p>At last I have created the <strong>“TourApplication”</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04dbd571cd76d10117b31a302957e73e/href">https://medium.com/media/04dbd571cd76d10117b31a302957e73e/href</a></iframe><p>Output:</p><pre>TourSigiriya{destination=&#39;Sigiriya&#39;, accommodation=true}<br>TourSigiriya{destination=&#39;Sigiriya&#39;, accommodation=false}<br>TourSigiriya{destination=&#39;Sigiriya&#39;, accommodation=true}</pre><p>If you are interested, you can use the following GitHub link to see my complete implementation of Prototype Design Pattern.</p><p><a href="https://github.com/nisal-kumara/krish-lp-training/tree/master/Design%20Patterns/Prototype">nisal-kumara/krish-lp-training</a></p><p>So, this is the end of my article and I hope you enjoyed it. Happy Coding👨‍💻.</p><h4>References</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fzw8kbrEbYxU%3Fstart%3D6%26feature%3Doembed%26start%3D6&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dzw8kbrEbYxU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fzw8kbrEbYxU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a37a54163fabf04e9730b095be55412/href">https://medium.com/media/7a37a54163fabf04e9730b095be55412/href</a></iframe><p><a href="https://www.geeksforgeeks.org/prototype-design-pattern/">Prototype Design Pattern - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5242b4e1c088" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>