<?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 Monis Yousuf on Medium]]></title>
        <description><![CDATA[Stories by Monis Yousuf on Medium]]></description>
        <link>https://medium.com/@monisyousuf?source=rss-db5229015c92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RtVf2BPL6N66XDlJV-ADbQ.png</url>
            <title>Stories by Monis Yousuf on Medium</title>
            <link>https://medium.com/@monisyousuf?source=rss-db5229015c92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:49:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monisyousuf/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[You Passed the System Design. You Still Got Rejected. Here’s Why.]]></title>
            <link>https://monisyousuf.medium.com/you-passed-the-system-design-you-still-got-rejected-heres-why-bf587b349e56?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf587b349e56</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 12:57:58 GMT</pubDate>
            <atom:updated>2026-06-16T12:58:13.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ded_rpZ09ApJIaqXGkJY1Q.png" /></figure><p>You designed a clean distributed system. You explained consistency trade-offs, sharding strategies, and failure modes without breaking a sweat. Your code was solid. Your interviewer nodded through every round. You left feeling like you’d earned it.</p><p>Then: silence. Then: the email.</p><p>“<em>We’ve decided to move forward with another candidate</em>.”</p><p>No elaboration. No specifics. Just the quiet implication that something was missing — and you have no idea what.</p><p>Here’s what was missing: not your system design skills. Not your coding. Something most interview prep guides completely ignore.</p><h3>Some Background</h3><p>A few years ago, I was heading a department that needed to hire a Senior Software Engineer for a newly formed team. The stakes were real. We had seven months to deliver a fully functional product, and the kind of product that requires buy-ins and integrations from multiple teams across the org. That’s never just a technical challenge. It’s a coordination challenge, a priorities challenge, and an alignment challenge all at once.</p><p>We interviewed a lot of candidates. Most didn’t make it past the technical screens. But two candidates, let’s call them A and B — stood out. Both cleared every stage with flying colours: HR screening, technical screening, logic tests, and coding interviews (medium-difficulty LeetCode, as expected for a Senior role). Both handled their system design rounds well. Different interviewers across rounds to prevent bias. Clean process.</p><p>The choice started to become clearer in the behavioural round — the kind some companies label “Leadership Interview,” “Culture Fit,” or “Bar Raiser Round.” Same idea: assessing how you think, not just what you know.</p><p>The question was simple: <em>“Tell me about a time you were dissatisfied with the current state of things and you took initiative to change it.”</em></p><p>Two candidates. Same question. Very different answers.</p><h3>Candidate A</h3><p>A talked about migrating a service from Java to Kotlin.</p><p>To be clear: this is not a trivial thing. A full service migration means touching tests, pipelines, deployments — and keeping production stable throughout. There are real ways it can go wrong. It takes discipline, attention to detail, and technical confidence to pull off.</p><p>A was clearly proud of it. And they should be.</p><p>But then they were asked: <em>“Why did you do it?”</em></p><p>The answer: <em>“Because we can do X, Y, and Z better in Kotlin than Java.”</em> Followed by a fairly passionate case for Kotlin over Java — features, syntax, null safety, whatever the argument was. Maybe it was right. Maybe Kotlin really was better for that codebase. That’s not the issue.</p><p>The issue is: <em>better for what?</em></p><p>When pressed for the business outcome, i.e. what actually changed for the team, for the product, for the company — the answer got hazy. Usage was about the same. Performance wasn’t measurably different. Velocity hadn’t improved in any documented way. The outcome was, at best, unclear. At worst, satisfying to the engineer and invisible to everyone else.</p><h3>Candidate B</h3><p>B’s story was less technically impressive on the surface.</p><p>The team had a requirement to send data to a central data lake so the analytics team could pick it up. Standard stuff — you build the integration, you ship it, you move on. B did exactly that.</p><p>But then B noticed something.</p><p>Looking around the org, B realised that a lot of other teams probably needed to build this same integration. Each one would start from scratch, spend time figuring out the same edge cases, and eventually arrive at roughly the same solution. That’s duplicated effort, multiplied across teams.</p><p>Nobody asked B to do anything about this. There was no ticket, no manager directive, no “nice to have” in the sprint backlog.</p><p>B open-sourced the integration internally — cleaned it up, made it plug-and-play, created a proper repo, and shared it on Slack. Then went back to regular sprint work.</p><p>Today, that repository is <em>the</em> standard for that integration across that org.</p><p>Not “technically” groundbreaking. Decent engineering. But an outcome that’s measurable: teams saved weeks they would have otherwise spent reinventing the same wheel. That time went to shipping actual features. The impact?</p><p><em>Weeks of saved engineering time, compounded across teams.</em></p><p>Time saved = engineering cost saved = real money.</p><h3>What actually separated them</h3><p>This is the part that most people miss.</p><p>A’s work was technically more complex. B’s was operationally more impactful. And when you’re hiring for a Senior position on a team with a seven-month runway that depends on cross-team buy-in, you need the person who thinks in terms of <em>business impact &amp; organisational leverage</em> — not just technical elegance.</p><p>The difference isn’t that A was a bad engineer. A was a good engineer. The difference is in the mental model each candidate brought to “initiative.”</p><p><strong>A’s mental model:</strong> “What can I improve technically?” → Migration, because they think Kotlin is better.</p><p><strong>B’s mental model:</strong> “What problem exists in this system — and who else has the same problem? How can I have an organisational impact with a task that I am already doing?” → An integration that every team will need to rebuild independently. Fix it once, benefit everyone.</p><p>That second mental model is what senior engineering actually looks like.</p><h3>The uncomfortable truth: companies buy ROI, not resume.</h3><p>The thing nobody in interview prep or in the org says plainly enough:</p><p><strong><em>Companies hire you so you can earn them money. Period.</em></strong></p><p>Not out of charity. Not because you deserve it. Not because your system design was textbook-perfect. They have a problem, or an opportunity, or a gap in their org — and they need someone who can close it in a way that justifies the salary, the benefits, the equity, and the lost productivity of onboarding.</p><p>Every senior engineer costs a company north of $100–300K all-in per year, depending on the market. That’s not a trivial investment. The hiring manager sitting across from you is not just evaluating whether you can code. They’re evaluating: <em>if I put this person on a real problem with ambiguity and stakes, do they know what actually matters?</em></p><p>“<em>I migrated to Kotlin because Kotlin is better</em>” doesn’t answer that question. It tells the interviewer you have opinions about technology. That’s fine, you actually should! But it’s not the filter at this level.</p><p>“<em>I noticed a problem that affected every team, fixed it once, and shared it — now it’s the standard</em>” answers that question. It tells the interviewer you understand that your job is to move the org forward, not just your own codebase.</p><h3>So, what to do about it?</h3><p>Passing the system design round means you’re technically competent. That’s table stakes at the senior level — it gets you in the room, but it doesn’t close the deal.</p><p>The deal gets closed in the behavioural round, and here is how you can think about it:</p><ol><li><strong>Audit your Stories</strong>: Go through every project you’re proud of and write down the business outcome, not just the technical one. If you can’t write it down, you’ll struggle to say it under pressure.</li><li><strong>Reframe “initiative” around pain, not preference</strong>: The best behavioural stories aren’t about doing something because you wanted to try a new technology or follow a best practice. They’re about noticing a real pain — whether it’s your team’s pain, another team’s pain, or the customer’s pain — and doing something about it without being asked.</li><li><strong>Scope your impact correctly</strong>: Candidate B’s integration wasn’t technically impressive. But its scope was org-wide. Scope of impact matters more than depth of implementation when you’re being evaluated for senior leadership potential.</li><li><strong>Prepare the <em>“why”</em> as carefully as the <em>“what”</em></strong>: Most candidates can explain <em>what</em> they built. The ones who get solid offers can explain <em>why it mattered</em> — in terms of time, cost, reliability, or revenue. Practice saying that out loud before you walk into the room.</li></ol><blockquote>Candidate B got the offer. Not because the work was harder. Because the thinking was better.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf587b349e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding, Hashing & Encryption — what’s the difference?]]></title>
            <link>https://monisyousuf.medium.com/encoding-hashing-encryption-whats-the-difference-ff5689d7e0ac?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5689d7e0ac</guid>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 09:57:32 GMT</pubDate>
            <atom:updated>2025-08-08T09:57:32.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>Encoding, Hashing &amp; Encryption — what’s the difference?</h3><p><em>When you convert data from one form to another — what do you call it? Is it Encoding? Is it Hashing? Or is it Encryption? All these concepts indeed transform the data, but do they mean the same thing?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCQenfdBRv_cKm7weh2-JA.png" /><figcaption>Hashing vs Encoding vs Encryption</figcaption></figure><p><em>Even the most experienced engineers find these concepts annoyingly conflated.</em></p><p><em>So let’s unpack each of these transformations and understand what they really do, when are they used, and how do they differ from each other so that we can lay this confusion to rest once and for all.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz5lpHsl8qQ4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz5lpHsl8qQ4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz5lpHsl8qQ4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/daed03f8584020340398571a0dce9a39/href">https://medium.com/media/daed03f8584020340398571a0dce9a39/href</a></iframe><h3>Encoding</h3><p>Think back to the last time you were searching something on Google. If you notice your browser bar — you might see something like this:</p><pre>https://www.google.com/search?q=what%20is%20encoding%3F</pre><p>If we look carefully, we can see that the <em>spaces</em> are actually replaced by %20 and <em>?</em> is replaced %3F. The browser somehow transformed our query into something different.</p><p>Why? because URLs are allowed to have only a limited number of characters. And in that character set, characters like space, are not valid. But it still needs to be sent, and therefore it is <em>converted </em>into something that belongs to the allowed character set. This type of transformation of data from one form to another for the purpose of storage or transmission is called <strong>Encoding</strong>.</p><p>Similar to this, the data can be encoded to other forms as well. For example, The text <strong>hello </strong>can be converted into many different forms.</p><pre>Binary: 01101000 01100101 01101100 01101100 01101111<br>Hexadecimal: 68 65 6C 6C 6F<br>Base64: aGVsbG8=</pre><p>The encoding is not only limited to transmitting data, but has other uses as well. For example, if you work on the frontend with CSS, you might’ve seen the color codes which have the RGB values — those values are usually written in hexadecimal (e.g. <strong>6cffb2</strong>) for its compact nature. In decimal, the same value look like this <strong><em>rgb(108, 255, 178)</em></strong>.</p><p>Similarly, in HTML, you may have seen the image tag to add images to your page which refer to the URL where the image resides.</p><pre>&lt;img src=&quot;http://some-website/some-image.png&quot;&gt;</pre><p>While this is fine for larger images, the lighter images can be directly embedded in the base64 format via HTML or CSS to save a network call.</p><pre>&lt;img src=&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...&quot;&gt;</pre><pre>.background {<br>  background-image: url(https://medium.com/&quot;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...&quot;);<br>}</pre><blockquote><strong>The key point to understand here is that</strong> <strong>encoding is reversible.</strong></blockquote><p>For example, anyone who sees %20 can decode it back to a space. It’s about <strong>data</strong> <strong>representation</strong>, <strong>not security</strong>. Speaking of security, let’s talk a bit about hashing.</p><h3>Hashing</h3><p>Whenever you create an account online, your <strong>password</strong> is usually never stored in plain text. Instead, it’s converted into a fixed-length string of characters which could look like this:</p><pre>$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36zCG5...</pre><p>From this string, it is impossible to construct the original password again. And this type of transformation is possible by a process called <strong>Hashing</strong>.</p><blockquote>Hashing is a process where you convert data into another irreversible form by the use of a <strong>Hashing Algorithm </strong>— which does some complex math behind the scenes to achieve this.</blockquote><p>So, when you login, the password that you enter is hashed again and compared with the hash that exists in the system. If they are same, the login is successful.</p><p>Hashing is defined by three features:</p><ul><li><strong>Irreversible:</strong> Hashing is one-way only. You can’t reverse a hash to retrieve the original input.</li><li><strong>Deterministic:</strong> The same input always produces the same hash.</li><li><strong>Fixed Length:</strong> No matter how long your password is, the hash has a consistent size. All hashes from the same algorithm are of the same length.</li></ul><p>Hashing is not only used in passwords, but has other applications as well. For example, in file downloads. If the downloaded file is corrupt, its hash would be different from the original file. Whereas, if the downloaded file is intact, its hash would be the same as the original file.</p><blockquote><em>If you’re intrigued by hashing, check out my deep-dive video on </em>What is Hashing? to learn about different Hashing Algorithms and Hash Collisions</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpMM9cIAFAug%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpMM9cIAFAug&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpMM9cIAFAug%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/788fb707c1f6115d1ba2bc5e95c913fa/href">https://medium.com/media/788fb707c1f6115d1ba2bc5e95c913fa/href</a></iframe><h4>Now, what if you need that “one-way” transformation to be <strong>two-way</strong>, but only for some selected people or systems?</h4><h4>That’s where <strong>encryption</strong> steps in.</h4><h3>Encryption</h3><p>Imagine you have a <strong>top-secret document</strong> on your computer. Anyone with access to your machine can open and read it.</p><h4>Encryption provides a way to transform your document or data into a form can can only be reversed by the use of a key.</h4><p>So, whoever holds the key, can access the data. If someone tries to open it without that key, they’ll only see gibberish:</p><pre>U2FsdGVkX1+7vWz2po4+hsn2F...</pre><p>Let’s take a simple example of encryption — one that dates back over 2000 years.</p><p>Julius Caesar used a basic encryption technique to protect messages of military importance. It’s now famously known as <strong>Caesar’s Cipher</strong> or the <strong>Shift Cipher</strong>. The idea? Shift each letter of the message by a fixed number of positions in the alphabet — let’s say, 3.</p><p>So, if we take the word hello, and shift each letter by 3:</p><ul><li><strong>h</strong> becomes <strong>k</strong></li><li><strong>e</strong> becomes <strong>h</strong></li><li><strong>l</strong> becomes <strong>o</strong></li><li><strong>next l</strong> also becomes <strong>o</strong></li><li>and <strong>o</strong> becomes <strong>r</strong></li></ul><p>That gives us: khoor</p><p>To anyone who intercepts this message without knowing the shift, it looks like gibberish. But if the recipient knows that each letter was shifted by 3, they can just reverse the shift — and decrypt the message back to hello.</p><p>Now of course, this kind of encryption is laughably easy to crack today — especially with modern computers — but it beautifully illustrates the core idea:</p><blockquote>The message is only readable to someone who has the key.</blockquote><p>Modern encryption is, let’s just say, <em>a bit</em> more advanced. Instead of letter shifts, we now use complex mathematical algorithms that are designed to be unbreakable by brute force — at least with current computers. (Quantum computing might change that… but that’s a topic for another video)</p><p>Take WhatsApp for example: every message you send is encrypted <strong><em>on your device</em></strong> before it even leaves your phone. If someone tries to snoop on the network, all they’ll see is garbled nonsense. Only the person you’re messaging — with the matching decryption key — can turn that noise back into your actual words.</p><h4>That’s encryption: locking your data in such a way that only the right key can unlock it.</h4><h3>To bring it all together,</h3><ul><li><strong>Encoding</strong> is like translating data into another format so computers can store or transmit it properly. It’s <em>not</em> about secrecy — it’s about structure and readability. And it’s completely reversible. Some examples are UTF-8, binary, hexadecimal and base64.</li><li><strong>Hashing</strong> takes your data and runs it through a special formula to create a unique, fixed-length code. This code doesn’t reveal the original data, and <em>you can’t convert it back</em>. That’s why it’s perfect for safely storing passwords or checking if a file has been tampered with — if the data changes, the hash changes too. Examples, SHA-256, BCrypt, Argon2</li><li><strong>Encryption</strong> is all about <strong>confidentiality</strong>. It transforms your data into something unreadable — <em>but</em> only temporarily. Because unlike hashing, encryption is reversible <em>if</em> (and only if) you have the right key. That’s how secure messaging apps like WhatsApp protect your conversations, even from their own servers.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5689d7e0ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Machine Learning? For Beginners]]></title>
            <link>https://monisyousuf.medium.com/what-is-machine-learning-for-beginners-0f8654560857?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f8654560857</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Wed, 21 May 2025 14:11:16 GMT</pubDate>
            <atom:updated>2025-05-21T14:11:16.684Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Have you ever wondered how Netflix knows exactly what you want to watch next? Or how Google finishes your sentence before you even finish typing? It’s almost like magic… but it’s not. It’s called </em><strong><em>Machine Learning</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNBeMT4fQND-uToNEDPtEw.png" /><figcaption>What is Machine Learning? For Beginners</figcaption></figure><p><em>‘</em><strong><em>Machine Learning</em></strong>’ sounds like a buzzword, and you’ve probably heard it thrown around a hundred times. Maybe it feels intimidating, like something only PhD researchers or data scientists understand. But trust me, it’s not as complicated as it sounds. So let’s try to understand it step by step.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg7H4TqGs5fw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg7H4TqGs5fw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg7H4TqGs5fw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4dfa901feadf8614cce3751cb7129e1/href">https://medium.com/media/e4dfa901feadf8614cce3751cb7129e1/href</a></iframe><h3>Deterministic Programming vs Machine Learning</h3><p>Let me start with something you already know — a calculator. When you ask a calculator to add 2 and 3, it gives you 5 every single time. That’s a deterministic result.</p><p>Similarly, most computer programs we use are designed with explicit rules. For example, if you’re writing code to check if a number is even or odd, you simply divide by 2 and check the remainder. If the remainder is 0, its even — otherwise its odd. It’s predictable and follows rules we define.</p><p>But what happens when the problem isn’t so clear? For instance, your friend asks you to recommend some cool movies. Its your friend, so you already know what kind of movies they like. Based on this information, you can recommend them some movies or tv series. For example, if they like “Gladiator”, “Troy” and “Lord of the Rings” — it’s likely that they would enjoy “Game of Thrones” as well. Similarly, if another friend enjoys movies like “The Terminator” or “Rambo” — they would enjoy similar action movies like “Commando” as well. So, you kind of take a “calculated guess” or “predict” what your friend might like.</p><p>But if a computer program were to do the same thing i.e. recommend a movie based on user’s taste — what rules would you write for that? It’s not as simple as saying</p><p>‘If a person likes Gladiator, recommend Game of Thrones”</p><p>Every person’s taste is unique and is shaped by many factors. So, it is pretty much impossible to write a generic set of rules which a program can use to find movie recommendations.</p><p>This is where <strong>Machine Learning</strong> comes in. Instead of manually writing rules, we feed the computer a lot of data — like which movies each person has watched, how they rated them, and what genres they prefer. Using this data, the computer learns patterns for every user. Once it has learned the patterns, we can ask the computer to “predict” what a user might like. Let’s say that in our case, the computer predicts “Game of Thrones” and some other shows. Based on what the user watches from those given recommendations, this data is again fed back into the systems to make the predictions more and more accurate for that particular user.</p><p>In a nutshell,</p><blockquote>Classical coding based on algorithms are based on specific rules (for example, rules to find whether a number was even or odd) whereas machine learning is not based on specific rules. Rather — it takes a bunch of data, finds patterns in that data and tries to figure out the rules itself. And based on these patterns, it predicts an outcome that you request. For example, movie recommendations.</blockquote><h3>“Ways” a machine can learn</h3><p>Now that you understand the basics of Machine Learning, let’s take a closer look at how it works. Broadly, there are three main ways* a machine can ‘learn’:</p><ol><li><strong>Supervised Learning</strong></li><li><strong>Unsupervised Learning</strong></li><li><strong>Reinforcement Learning</strong></li></ol><p>Let’s break these down one by one”</p><p>*<em>There are other flavours as well, but these should give you enough information to get started.</em></p><h3>Supervised Learning</h3><p>Think back to when you were in kindergarten. Remember those picture books that taught you shapes? They’d show you a circle, a square, rectangle and a triangle, and then you’d see pictures of everyday objects made from those shapes — like a house made of rectangles and triangles or a balloon that’s just a circle. Then came the fun part: the teacher would give you a new picture, like an ice cream cone, and ask, <em>What shapes do you see?</em> You’d figure out that the cone is a triangle, and the scoop of ice cream is a circle.</p><p>That’s exactly what supervised learning is! The teacher as the supervisor gave you a bunch of shapes, taught you the names of those shapes. Once you know the shapes, your teacher would give you some real examples of everyday objects and explain you how to find different shapes in those objects. So when you were presented with an ice-cream cone which was not in the examples, you we able to use your knowledge of shapes and learnings from some examples to predict the shapes present in the ice-cream cone.</p><p>Similarly, we can use the same approach to train a system to understand the ‘basic features’ of a movie — things like its director, actors, genre, and more — much like identifying basic shapes. Then, we feed the system with examples of movies a person has watched, rated, or shown interest in. Once the system is trained, it can predict new recommendations — just like a child identifying shapes in an ice cream cone.</p><h3>Unsupervised Learning</h3><p>Now, let’s go back to kindergarten again, but this time the teacher gives you a bunch of blocks in different colors, shapes, and sizes. Instead of telling you what each block is, the teacher just asks you to <em>sort them</em> in groups. You might group them by color — putting all the red blocks together, the blue ones in another pile, and so on. Or, you might group them by shape — circles in one pile, triangles in another. You’re figuring out the groups on your own without anyone giving you examples.</p><p>That’s unsupervised learning! The kids didn’t know the names of shapes or colors, but they could still organise the objects into different clusters.</p><p>In real life, if you’ve used Google Photos, you might have come across the ‘Face Grouping’ feature. When you enable this, Google analyzes all the photos on your device and groups images of the same individual together. If you have this feature enabled, you can even visit <a href="http://photos.google.com/people"><strong>photos.google.com/people</strong></a> to see distinct face clusters that Google has identified from your photos. Clicking on any of these faces will show you all the pictures containing that person. Here’s the cool part: Google doesn’t know who these people are and it hasn’t been told what to look for. Instead, it identifies patterns and similarities in the facial features all on its own. This is a great example of unsupervised learning in action!</p><h3>Reinforcement Learning</h3><p>Now, think back to when you were a child learning how to ride a bike. At first, you might wobble, fall, or even crash. But over time, through <strong>trial and error</strong>, you learned how to keep your balance and avoid falling so you could finally enjoy the ride.</p><p>Reinforcement learning works in much the same way — it’s all about <strong>learning from mistakes</strong>. Every bad move (like falling off the bike) results in a penalty, and every smooth ride earns a reward. Over time, these rewards and penalties help shape better decisions.</p><p>A real-life example of reinforcement learning is how Netflix keeps you hooked by the “Up Next” feature. Once you’ve finished watching a Movie, as soon as the credits start — it suggests you another show to watch based on the current context. The context may include: the video you just finished, watch history in the last hour, time you have available (e.g. its middle of the day OR 15 minutes before bed) etc. The recommendation engine chooses one video from its large catalog to play next. If you click play within a few seconds and watch it for a decent amount of time, its a <strong>positive reinforcemen</strong>t and if you abandon the show after watching for ~10 seconds OR click “back to browse” — its <strong>negative reinforcement</strong>. After collecting a lot of this data, Netflix tunes itself better, so that it can give you recommendations which yield more click rates and longer watch times.</p><p><em>That’s reinforcement learning in action — constant trial, feedback and improvement.</em></p><p>So that’s all folks — if you would like to deep dive into how these things actually work, stay tuned for my next articles &amp; videos on Machine Learning &amp; be ready to roll up your sleeves, because we’re going to get our hands dirty with some actual code.</p><p>Bis Dann!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f8654560857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Hashing? Hashing Algorithm, Functions and Collisions]]></title>
            <link>https://monisyousuf.medium.com/what-is-hashing-hashing-algorithm-functions-and-collisions-2f83e66602d1?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f83e66602d1</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 15:18:19 GMT</pubDate>
            <atom:updated>2025-01-29T15:18:19.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Hashing is a concept that lays the foundation of many important computer science topics. Be it cryptography, system design topics like consistent hashing or something even as trendy as blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_L5hnNaFwmtB349Jf9IUQ.png" /><figcaption>The foundation of Hashing.</figcaption></figure><p>In this article, we will unravel some foundational concepts of hashing even if you’ve never even heard of this term. So let’s get started!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpMM9cIAFAug%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpMM9cIAFAug&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpMM9cIAFAug%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bc48a1c9dcaae608c18ac0331e6cd84/href">https://medium.com/media/6bc48a1c9dcaae608c18ac0331e6cd84/href</a></iframe><h3>What is Hashing / Hash Function?</h3><p>If you are familiar with any programming language you must know obviously know about <em>functions</em>, or as they call in some object oriented languages — <em>methods</em>.</p><p>Some functions take inputs to generate an output, while others may not take an input and may not even return anything.</p><p>For the purpose of this article, when we say a <strong><em>function</em></strong> — we mean a function which takes some input and generates an output. More often than not, the input almost always has something to do with the output. Let’s take an example of a function which takes two numbers and returns its sum.</p><pre>public int add(int a, int b) {<br> return a + b;<br>}</pre><p>Here, the output is always dependent on the input. If we change the input — the output always changes. If we send, 1 and 2; the output is 3. If we send 200 and 300 — the output is 500.</p><p>Now, a hash function is a special kind of function in which we have to abide by<strong> three rules</strong>:</p><ol><li><em>It must be deterministic, i.e. same input must ALWAYS have the same output</em></li><li><em>The output for all possible inputs should be of a fixed length.</em></li><li><em>The output MUST be irreversible</em></li></ol><p>So, in our <strong>add</strong> method, no matter how many times we pass 1 and 2 into the function; the output will always be 3. It means — that the same input always has the same output. So, we have satisfied at least one rule.</p><pre>add(1,2) = 3 // single digit output. length = 1</pre><p>Now, if we pass 200 and 300 to the function; the output will be 500. No matter how many times we pass these two values the output will always be 500.</p><pre>add(200,300) = 500 //triple digit output. length = 3</pre><p>However, the <em>length of the output does change depending on different inputs</em>. In the first case, the output was 3. Which is only 1 digit. So the length is 1. But in the second case, the output was 500. Which are 3 digits. So the length is 3.</p><blockquote>So — the add function is not a hash function — because it broke the second rule.</blockquote><p>Let us still try to see if it abides by Rule#3.</p><p>For the inputs 1 and 2, the output was 3. From the number 3 alone we cannot make out the input. That is — we cannot tell which two numbers were provided as an input to produce the output 3. There can be huge number of possibilities to yield the output 3. For example -1 and 4, -12 and and 15 , 1022 and -1025 all can yield 3. So there is no way to conclusively determine the input from reverse engineering the output. <strong><em>This means, that the output is irreversible.</em></strong></p><p>Now if we were to take a method, which takes an integer, adds 1 and returns the value:</p><pre>public int someFunction(int a) {<br> return a + 1;<br>}</pre><p>It would be possible to reconstruct the input from the output. For example, if we tried passing the input 1, we would get 2. We try 2 and we would get 3. We try 100 and we get 101. Therefore, if we subtracted 1 from the output — we would be able to re-construct the input. In this case, it would break Rule#3 as well. <strong><em>Meaning, the output becomes reversible</em></strong>.</p><p>So, let’s try to write a cool function called hashify(), which abides by all 3 rules. The job of this function is to <em>add two numbers and then return its last digit</em>. This would look somewhat like this:</p><pre>public int hashify(int a, int b) {<br> int sum = a + b;<br> return sum%10;<br>}</pre><p>So now, let’s try to see if it abides by all the rules.</p><p>So — if we pass 1 and 2; just like last time. the sum becomes 3. Since this is a single digit; it is returned as-is. Therefore, the output is 3. Similarly, if we pass 200 and 300; the sum becomes 500. The last digit of 500 is 0 which is returned as the output. Now, no matter how many times we pass 1 and 2, the output will always be 3. Similarly, if we pass 200 and 300, the output will always be 0.</p><blockquote>So rule number — 1 is satisfied i.e. the same input always returns the same output.</blockquote><p>In addition to this, we can clearly observe that nomatter how large the input is, the output will always be a single digit. Which means that the length of the output is always 1. Therefore,</p><blockquote>Rule #2 — is also satisfied because this function will always return a single digit i.e. an output of fixed length.</blockquote><p>Now, from the output alone, we cannot figure which two numbers were provided as an input. Therefore,</p><blockquote>Rule #3 — also stands satisfied because the output is irreversible i.e. we cannot figure the two numbers which were provided as an input to the function.</blockquote><p>So we can clearly see that this function satisfies all 3 rules we discussed before and therefore we can call it a valid hash function. Talking a bit about terminology -</p><blockquote><strong>The output of a hash function is simply called </strong>hash<strong>. And the process of converting an input (or a KEY) into a hash is called “hashing”.</strong></blockquote><h3>Hash Collisions</h3><p>Now, let’s try to create another hash function which satisfies all these rules.</p><pre>public char hashify(String string) {<br> int lastIndex = string.length() - 1;<br> return string.charAt(lastIndex);<br>}</pre><p>The job of this function is to return the last character of a string. So — if we pass confringo to the function, It will always return o. Which means Rule#1 satisfied. Since it will always return a single character, no matter how large is the input is, it satisfies Rule#2. And finally, it is impossible to reconstruct a string back from a single character — so Rule#3 is also satisfied.</p><p>Now, an important point to be noted about this hash function is that there could be a lot of possible inputs which could yield the output “o”.</p><pre>confringo =&gt; o<br>protego   =&gt; o<br>accio     =&gt; o<br>ascendio  =&gt; o</pre><p>It means all the strings ending with o will have the same output i.e. o</p><blockquote>When two or more inputs into a hash function result in the same output, it is called <strong>hash collision</strong>.</blockquote><p>A good hash function tries to minimise hash collisions. Subsequently, a perfect hash function is the one which has no hash collisions at all. <em>If a function satisfies all the rules of a hash function, but has a lot of hash collisions — it is still a hash function, but not a very good one</em>.</p><p>Now — hash collisions can be detrimental in a lot of cases.</p><h3>When are hash collisions bad?</h3><p>If we take a real life example of passwords. Companies don’t store your passwords in cleartext. They rather hash it and then store it. The hashed password could look somewhat like this.</p><pre>64b574ed4370267521b323bed85d10ead7ace392eee6c938aa25a4227f6a059b</pre><p>So with this hash — it is impossible for the developers to reverse engineer the actual password.</p><p>So when you login, the password is hashed again using the same hash function. Which means, it should return the same output as what was stored in database. If they match, the login is successful. Now, if we were using a very <strong>bad hash function like the one that we created before</strong> and your password was 123confringo. The hash which would be generated and stored in the database would simply be lowercase o.</p><p>So, when someone tries to login into your account and enters any random string which ends with lowercase o like 999Ascendio<em>,</em> it’s hash, which would also be lowercase o would match the database value and the impersonator would successfully be able to login. So, if a hash function has a lot of collisions, it is likely that many different inputs can yield the same hash which substantially increases the likelihood of malicious login. This is the reason, why hash functions try to minimise hash collisions.</p><p>Now, you might be thinking that how do we write a hash function which abides by all three rules and also minimises or completely removes the possibility of hash collisions? Well, the good news is — most likely, you don’t need to. There are a lot of computer scientists who have spent a lot of time and research in developing algorithms which qualify as near perfect hash functions like<em> SHA256, bcrypt, argon2</em> and such.</p><p>I have created some <a href="https://github.com/monisyousuf/youtube-tutorials/tree/main/CD_006_hashing">code examples</a> for you to test out different hashing algorithms and test yourself if they abide by the 3 rules of hash functions.</p><p>Stay tuned for my next articles — where I will explain the real life use cases of Hashing and how interviewers sneakily test your knowledge of hashing concepts. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f83e66602d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is docker? Docker File, Images and Containers — with code examples.]]></title>
            <link>https://monisyousuf.medium.com/what-is-docker-docker-file-images-and-containers-with-code-examples-6d81d426b3a0?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d81d426b3a0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 15:37:47 GMT</pubDate>
            <atom:updated>2025-01-28T15:38:16.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is docker? Docker File, Images and Containers — with code examples.</h3><figure><img alt="Don’t understand docker? Read on!" src="https://cdn-images-1.medium.com/max/1024/1*_5awwmjNWlEG2XN7v2bkKA.png" /></figure><p>When your colleagues have a conversation about docker — do you just nod along hoping they don’t ask you something about it? Well — if the answer is yes — read on!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fk29FmUcihSA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dk29FmUcihSA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fk29FmUcihSA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c88c4a8b866cd0c513942c5fdb8c0b57/href">https://medium.com/media/c88c4a8b866cd0c513942c5fdb8c0b57/href</a></iframe><h3>Before Docker..</h3><p>A long time ago, before anyone even knew the word docker; the development in software companies used to happen in a very different way than today.</p><p>Let’s say that you were building a web application in java. In order to start development on your computer; you first need to setup the application on your personal computer so that you can work on it. This involved a bunch of steps like: Installing Java, Web Servers, Libraries, database, insert data into the database, download code and Copy some configuration files in 10 different mysterious locations on your computer.</p><p><strong>And after doing all of this, your application still won’t start.</strong> Then, you would ask a senior developer who has been in the company since before the time of the pyramids who adds that 1 line of code to a configuration file and voila! everything works!</p><p>Now, all these steps need to be very well documented so that new developers or a person coming back from their honeymoon could update their computers to make the application run. Even if one small configuration is missed, it could get problematic for everyone. And let’s face it, the guy who has been in the company since 3000 BC may leave at any time. This is also a bit of a trouble when different developers have different computers &amp; OS. For example, most of the people use mac and linux while the new guy has sworn to use windows for his entire life.</p><p>On a bit of a serious note, local machines are still fine — even if everything is not running a 100%; we can find ways to tweak it because its our computer. But things get tricky, when we want to make an application live. We still need to follow all those steps to make our application run on an external server and host it on the internet.</p><p>This was a cause for concern…</p><h3>Introducing Docker</h3><p>In order to solve these problems, <strong>Docker</strong> came into the picture. It came up with the idea of separating your infrastructure and your application. Your application is simply the APIs, business logic and the underlying code to support this. Simply put, its just a bunch of code and some libraries.</p><p>And on the other hand, your infrastructure is a bunch of things like a physical computer where everything will run such as your database, installed software, system configuration, environment variables and these type of things. All the manual steps that we discussed before, were basically to setup this infrastructure.</p><p>Now docker allows all of these steps to be managed automatically instead of a person following a sequence of steps manually which basically sets up your infrastructure. Not only that, docker is also able to build your application code, deploy it on that infrastructure and even run it. And all of this happens in a platform independent way, so that the same infrastructure commands can run on different operating systems, like linux, mac and windows. So let’s see how it is done.</p><h3>Dockerfile &amp; Docker Images</h3><p>If we try to understand the core of programming in general, the code that we write is just a set of instructions given to the computer. Similarly, the steps for setting up infrastructure can also be written as instructions. But the question is — where do we write those instructions? And how do we run them? Docker allows us to write these instructions in a specific format in something called a Dockerfile</p><p>Just like you have syntax for java, python and C++ to provide instructions to your computer; `Dockerfile` also has its own syntax. The difference is; in programming languages you automate business logic and in Dockerfile you automate infrastructure commands.</p><p>On similar lines, just like you need a java or python environment installed on your computer to run the java or python code; you need to have a docker environment installed on your computer to run the Dockerfile which contains your infrastructure commands.</p><p>Now, let’s imagine we have a very basic application with a few html pages. And these HTML pages are in a git repository. Our goal is to simply host these HTML pages on our local computer, which has doesn’t have any software installed on it except for two things:</p><ol><li>One is the git client (so that we can clone the repository)</li><li>Second is the docker desktop (so that we can run the docker infrastructure commands)</li></ol><p>So let’s clone our repository. Our repository looks something like this:</p><pre>git clone https://github.com/monisyousuf/youtube-tutorials<br>cd CD_007_docker<br><br>CD_007_docker<br>  |<br>  |____index.html<br>  |____services.html<br>  |____about-us.html<br>  |____contact-us.html<br>  |____style.css<br>  |____README.md<br>  |____app.Dockerfile</pre><p>This is just a bunch of html pages, a css and a `.Dockerfile` to contain the infrastructure commands.</p><p>Now, in order to host these html files on our computer, we need to follow some steps:</p><ol><li>First, we need to install a web server like nginx.</li><li>Next, we need to copy our HTML files into an nginx directory from where nginx hosts it. According to the nginx documentation, that directory is: /usr/share/nginx/html</li><li>Finally, we need to start the application</li></ol><p>So far - it sounds clear, now let’s try to see how we can automate these instructions using our .Dockerfile. The first line in our Dockerfile signifies what environment we would like to use in our application. It is prefixed with the word FROM followed by the name of the “image” we would like to use for our application.</p><pre>FROM nginx</pre><p>At this moment, you can consider an <strong>image as a lightweight version of linux with nginx installed on it</strong> along with some other software and security packages to make everything work nicely. A lot of organisations and open source communities maintain different images for java, python, c++, postgres database and such. These are pretty basic but stable images which provide an environment for you to run your commands. All these images are present on hub.docker.com. So when we write something like From nginx in our .Dockerfile, then there must be an image named <strong>nginx</strong> on the docker hub.</p><p>Now, that we’ve got our environment sorted, we need to copy our html and css to the nginx directory so that it can read it. Nginx specifies this directory in its documentation. So, whatever goes in this directory, is served by nginx.</p><pre>FROM nginx<br>COPY *.html /usr/share/nginx/html <br>COPY *.css /usr/share/nginx/html</pre><p>Once this is done, we have to create our own image out of this Dockerfile. To do that, we can run this command.</p><pre>docker build -f app.Dockerfile -t docker_nginx_image .</pre><p>In this command, after the docker build , we have a few parameters. Let’s try to understand them.</p><ol><li>The first parameter is prefixed with -f followed by the name of the Dockerfile. In our case, the name of the dockerfile is app.Dockerfile. You can name it anything with the extension .Dockerfile</li><li>Next parameter is -t followed by the our very own custom image name which has all these files that we copied. In our case, we would like to name it docker_nginx_image</li><li>Finally, we specify the PATH. This specifies where to find our files &amp; directories. For example, in our app.Dockerfile we asked docker to copy all html and css files to the nginx location. PATH is the place where docker is expected to find these files. Since this command was being run from the directory where the files were present, . was specified to denote the current directory.</li></ol><p>Now, when this command is executed, the docker system will try to find the latest version of the nginx image and load it onto our computer. If this process was successful, it will execute the remaining commands to copy the html and css to the nginx directory. When all of the commands are successfully executed, a new image will be created which is based on the nginx image but has some extra stuff that we added. So, in a way it becomes our very own custom image and resides on our computer.</p><p>This can be checked by executing this command</p><pre>docker image ls</pre><p>This should list the new image with the name docker_nginx_image as we specified in our previous commands.</p><blockquote><strong>To summarise all of this, at first — we had a Dockerfile which contained some instructions, and we used the docker build command to convert these instructions into an image.</strong></blockquote><h3>Docker Containers</h3><p>At this point, we have got ourselves a very well defined image which contains everything we need including our code to run our app. And now, we also know the difference between a Dockerfile and a Docker Image.</p><p>Now, the next step is to run this image with the docker run command. <strong><em>A running version of an image is called a container.</em></strong></p><p>Here is a basic command to spawn a container based on an image:</p><pre>docker run -p 80:80 docker_nginx_image</pre><p>In this docker run command, we have specified two parameters. The first parameter is prefixed with -p. Which refers to “port”.</p><p>Now, nginx, by default runs on port number 80. But this port resides within the docker container and is accessible only within the docker container. It means, if you were to access this application from your browser — which is outside of docker, this port will not be accessible. Therefore, we need to forward the traffic from our computer’s port#80 to the docker’s port#80. So that docker can pass our requests to nginx which in turn, can process our requests.</p><p>This is made possible by using the -p parameter. The left port is the port of the host system i.e. your computer and the port on the right is the nginx port within docker. This will allow the traffic from the host system to flow into the docker’s nginx.</p><p>Next parameter is the name of the image that we built before; using the docker build command, so that docker knows which image it needs to run because you may have a lot of other images in your system as well.</p><p>Let’s run this command and then try to access our application through the curl command:</p><pre>curl -v localhost:80</pre><p>We would clearly be able see the page code along Server header which tells us, that this page is indeed coming from nginx. Similarly, we can access the nginx app also from the browser to see the response.</p><p>If we go to our Docker Desktop and select Containers on the left panel, we should clearly be able to see our container running in green. We can see the image name and the forwarded ports as well.</p><p>To practice and play around with this setup, you can download all of this code from my <a href="https://github.com/monisyousuf/youtube-tutorials/tree/main">public repository</a>.</p><h3>Finally, to summarise all of this —</h3><p><strong><em>Docker is basically a technology which decouples the application code from infrastructure.</em></strong></p><p><strong>We write </strong><strong>.Dockerfile to write instructions on how to setup our infrastructure</strong>. This is usually based on another image like java, python, c++ or could be as simple as nginx. These core images are maintained by different organisations and open source communities. With our dockerfiles we use the images and customise them.</p><p>Then we build these dockerfiles into new custom images.<strong> The build process executes the commands within the Dockerfile and in turn creates a new custom image</strong> which has everything we need to run our application. This image resides on our computer.</p><p>Next, we simply run our image to see our application. <strong>A running image is basically called a container</strong>. Following the same lingo,</p><blockquote>When an application is packed into one or more docker containers — this process is usually called “<strong>containerization</strong>”.</blockquote><p>Throughout this whole process, the application developers never had to install nginx on their own system. Rather, they can just write the code — change the html, build a new image and run the container without worrying about the infrastructure. Even if there was any secret configuration — it would be present in the Dockerfile.</p><p>I hope that the fundamentals of docker are clearer to you now, but there are some questions which are still left unanswered. This was a very basic application that we made, but how do we make more complex applications? Like an application with database and messaging system. Do we need multiple docker images and containers? How will they interact with each other? Is there any difference between how docker works locally and how it works on live servers?</p><p>Hang tight for my next article on docker which will clarify all of these things so that you have a complete overview on how docker works. See you there, <strong>Bis dann!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d81d426b3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Queue by only using stacks!]]></title>
            <link>https://monisyousuf.medium.com/create-a-queue-by-only-using-stacks-bd275c4cc59d?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd275c4cc59d</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 19:47:56 GMT</pubDate>
            <atom:updated>2020-11-12T20:08:28.785Z</atom:updated>
            <content:encoded><![CDATA[<p>A very popular algorithm related question is asked during many programming interviews — “<em>Write a program to create a queue by only using stack”. </em>This question usually leaves even an experienced programmer confused about how to approach this question. The solution, however, is quite simple.</p><p>First, let’s understand the very basics of stacks and queues:</p><p><strong>Stack</strong>: A stack is a data structure, which follows the policy of <em>LIFO (Last In, First Out). </em>Imagine a stack of plates placed on top of each other. If you were to retrieve a plate, you will take out the topmost plate first, right? This is exactly what happens in a stack. The element, which was inserted in the end, is retrieved first, while the element which was inserted first is retrieved last. From an implementation perspective, this data structure allows the following operations:</p><ol><li><strong>push(element) </strong>— This method allows to add an element on <strong>top</strong> of stack.</li><li><strong>pop()</strong> — This element removes the <strong>top</strong> element from the stack.</li><li><strong>peek()</strong> — This element views the <strong>top</strong> element of the stack, but does not remove it.</li><li><strong>empty()</strong> — Checks if stack is empty. If stack has no elements, this should return true.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8jfasvFZ0AaWF5UL.png" /></figure><p>The above diagram represent a stack shown in the form of elements on top of each other. The element “5” was the first to come (and hence at the bottom). The element “6” was added LAST. Since the elements can only be removed from top, “6” will be the first to go. Therefore, it represents <em>Last-In-First-Out (LIFO) </em>policy.</p><p><strong>Queue</strong>: A queue is a data structure, which follows the policy of FIFO (First In First Out). Imagine that you are in a queue for buying tickets for a popular movie. A person who came first, will buy the ticket first and will be out of the queue first. However, if a new person is joining the queue, he must go to the end of the queue and wait for his turn. Speaking in programmatic terms, in queue, we can insert elements in the end (or <em>tail</em>), and remove them from the beginning (<em>head</em>) of the queue. There are different types of queues which allow more operations than the ones stated above, but; for the sake of simplicity, we will just go ahead with the basic queue. Operations of a queue include:</p><ol><li><strong>offer(element) </strong>— adds an element to the <strong>tail </strong>of the list</li><li><strong>poll()</strong> — removes the element at the <strong>head </strong>of the list</li><li><strong>peek() </strong>— views the element at the <strong>head </strong>of the list</li><li><strong>isEmpty()</strong> — checks if there are no elements in the queue</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0cuk1OjvH-lc1IrgqcvHg.png" /></figure><p>The above diagram represents a queue, we see that elements are added to the tail and removed from the head. Which means, the element “6” was the FIRST to arrive and “5” was the last to arrive. Since the elements can only be removed from the head, therefore “6” which came FIRST, will be the FIRST to go out. Therefore, it follows the policy of <em>First-In-First-Out (FIFO).</em></p><h3>The Logic of using stacks to form a Queue</h3><p>In order to create a data structure behave like a queue, we will have to make use of two stacks., each of which has its own purpose. Let’s call them <em>pushStack </em>and <em>popStack.</em></p><ol><li><strong>pushStack</strong>: Any new elements coming in, will be inserted into this stack. Therefore, for the <strong>offer(e) </strong>method of our queue, we will actually do a <strong>push(e) </strong>into the <strong><em>pushStack</em>.</strong></li><li><strong>popStack: </strong>Any elements which are being removed or peeked from the queue, will be <em>popped/peeked </em>from this stack. Therefore, the <strong>poll()<em> </em></strong>method of our queue will internally <strong>pop() </strong>from this stack. Also, the <strong>peek() </strong>method of the queue, will internally call <strong>peek() </strong>of this stack.</li></ol><p><em>Now, the question arises, that we are inserting the elements in one stack, but removing from another. How will this </em><strong><em>popStack</em></strong><em> have elements inside it? Also — why are we using two stacks?</em></p><p>In the beginning, the <strong>popStack </strong>will be empty. Let’s say that the elements are being inserted into the <strong>pushStack.</strong> The moment <strong>poll() </strong>operation is called, it will internally call the <strong>pop() </strong>method of the <strong>popStack. </strong>But, <strong>popStack </strong>does not have any elements inside it. In this case, we will pop all the elements of the <strong>pushStack </strong>one-by-one and insert then in the <strong>popStack.</strong></p><blockquote>Doing this, will reverse the order of the inserted elements. On reversal of inserted elements, the bottom-most element of the stack now becomes the top-most element of the <strong>popStack</strong>. i.e. the element which was “inserted” first, can now be removed “first”, which is the whole concept of a queue.</blockquote><p>It will be a bit more clear by the below graphical representation:</p><h3>Step#1: In the beginning, both stacks are empty</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*V_JBbbC2zFRwYVSmoEqCig.png" /></figure><p>At first, both: <strong>pushStack</strong> and <strong>popStack </strong>are empty. No elements have been inserted. At this point, if the <strong>poll() </strong>method is called, and we have no elements to return, the system should show an error message conveying the user that the stack is empty OR should return null.</p><h3>Step#<strong>2: Elements added to the queue</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Mi1V9oIu8cs2EE29qOkkKQ.png" /></figure><p>In this step, we insert some elements to the queue. All the elements inserted into the queue, always go to the <strong>pushStack</strong>.</p><p>For example:</p><pre>offer(5);<br>offer(8);<br>offer(10);</pre><p>These methods, internally call the push(element) method on the <strong>pushStack</strong>.</p><p>Therefore, the elements are inserted from the top. “5” is inserted first and goes at the bottom. “8” is inserted next, so its in the middle. “10” is inserted at last, and hence is on the top.</p><h3>Step#3: <strong>Poll (remove) the element from the queue</strong></h3><p>When we <strong>poll() </strong>an element from a queue, it is removed from the head of the list. Right now, we have a stack in which, the <strong><em>“first-in”</em></strong> element (i.e. “5”) is at the bottom. According to the queue policy, the element coming-in first, should be the first to go out. However, stack only allows removal of the element from the top (in this case “10”). To counter this problem, we start popping all the elements one-by-one from the <strong>pushStack </strong>and then insert them into <strong>popStack.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*D_9eVLaUreal_FISpM2hoQ.png" /></figure><p>Therefore,</p><pre>&quot;10&quot; is popped and inserted in <strong>popStack</strong><br>_______________<br>Next, &quot;8&quot; is popped and inserted on top of &quot;10&quot; in <strong>popStack</strong><br>_______________<br>Next, &quot;5&quot; is popped and inserted on top of &quot;8&quot; in <strong>popStack.</strong></pre><p>As we can see, the order of the elements is reversed. In this context, the elements are now arranged in the form of first-in-first-out. “5” was first to come, and is on the top. “8” was second, and “10” was third. Therefore, if the <strong>poll()</strong> method of the queue is called and there are no elements in the <strong>popStack</strong>, we move all the elements of the <strong>pushStack</strong> to <strong>popStack</strong>. When this is done, then we can pop the topmost element of the <strong>popStack</strong>. In this case “5” will be popped. If the <strong>poll()</strong> method of queue is called again, then <strong>popStack</strong> still has some elements, and they can be popped. We can repeatedly call the <strong>pop() </strong>method of <strong>popStack</strong> until it is empty. The moment it becomes empty, we move the elements from the <strong>pushStack to popStack</strong> and again repeat the operation.</p><h3>Step#4: Subsequent Insertion</h3><p>In the above step, let’s assume “5” was polled from the queue (popped from popStack). At this moment, <strong>popStack </strong>still has some items, while <strong>pushStack</strong> is empty (we moved all the elements in previous step)</p><p>Let’s say that immediately after <strong>poll()</strong> method, <strong>offer(e)</strong> was called to insert some elements. In this case, we simply push the element into <strong>pushStack</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*QxlpK5Ks53zRbWq1gneeJg.png" /></figure><p>Since, the element “5” was popped from <strong>popStack, </strong>it has elements [8,10].</p><pre>offer(12);<br>offer(7);<br>offer(9);</pre><p>After adding 3 elements, they are inserted into the <strong>pushStack</strong>.</p><p>We can continue to follow steps 1 through 4 by following these basic principles</p><ol><li>Always add elements to the <strong>pushStack.</strong></li><li>Always remove elements from the <strong>popStack.</strong></li><li>If <strong>popStack </strong>is empty &amp;&amp; <strong>pushStack</strong> is empty | It means that the queue is empty</li><li>If <strong>popStack </strong>is empty &amp;&amp; <strong>pushStack</strong> is not empty | move the elements to the <strong>popStack</strong></li></ol><p>This way, we can ensure that our data structure behaves like a queue.</p><p>Now, that we know what we have to implement, let’s see the code implementation.</p><h3>Code Implementation</h3><pre>import java.util.Stack;</pre><pre>public class Queue&lt;T&gt; {<br>    private Stack&lt;T&gt; pushStack;<br>    private Stack&lt;T&gt; popStack;</pre><pre>    public Queue() {<br>        this.pushStack = new Stack&lt;&gt;();<br>        this.popStack = new Stack&lt;&gt;();<br>    }</pre><pre>    public void offer(T element) {<br>        //Always add to the pushStack.<br>        pushStack.push(element);<br>    }</pre><pre>    public T poll() {<br>        T element = peek();<br>        if (element != null) {<br>            //if element is not null, <br>            //then popStack has some values and we pop it.<br>            popStack.pop();<br>        }<br>        return element;<br>    }</pre><pre>    public T peek() {<br>        if (popStack.size() == 0 &amp;&amp; pushStack.size() &gt; 0) {<br>            //if popstack is empty, but pushStack has data, <br>            //then transfer the data to popStack<br>            while (pushStack.size() != 0) {<br>                //POP from pushStack and <br>                //PUSH that element in the popStack<br>                popStack.push(pushStack.pop());<br>            }<br>        }<br>        //If popStack still has no values, then return null, <br>        //otherwise, peek and display<br>        return popStack.size() &gt; 0 ? popStack.peek() : null;<br>    }</pre><pre>}</pre><h3>Runtime Complexity Analysis</h3><p><strong>Complexity of offer(e)</strong>: It is a straightforward addition to the top of a stack. Therefore, it happens in O(1) time (constant time).</p><p><strong>Complexity of poll()/peek() </strong>: If we have some elements in the <strong>popStack</strong>, and we are removing an element from the top, it is constant time. However, when <strong>popStack </strong>is empty, we have to pop() all the elements from the <strong>pushStack</strong> in O(n) time. This operation happens once in a while when the popStack is empty, therefore, we can say that the complexity is O(1) in amortized time.</p><blockquote><em>Questions? Comments? Feel free to put-in your thoughts in the comments section : )</em></blockquote><blockquote><strong>More on </strong><a href="https://monisyousuf.com/blog"><strong>https://monisyousuf.com/blog</strong></a></blockquote><p><em>Originally published at </em><a href="https://www.monisyousuf.com/post/create-a-queue-by-only-using-stacks"><em>https://www.monisyousuf.com</em></a><em> on November 12, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd275c4cc59d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anagram Substring Search — Find all anagrams in a string]]></title>
            <link>https://monisyousuf.medium.com/anagram-substring-search-find-all-anagrams-in-a-string-5a1d97ea71a6?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1d97ea71a6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[substring-search]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Sun, 25 Oct 2020 11:33:30 GMT</pubDate>
            <atom:updated>2020-10-25T11:33:30.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Anagram Substring Search — Find all anagrams in a string</h3><p>Given a string, find all anagrams of a pattern in the given string.</p><p>For example:</p><pre><strong>INPUT </strong>: string = “abczzbcabcadeb”, pattern = “abc”<br><strong>OUTPUT</strong>: [0,5,6,7,8]</pre><p>An anagram is defined as a word which is formed by re-arranging letters of a given word. For example, the words LISTEN and SILENT are anagrams of each other. Therefore, when we have to find ALL anagrams of a pattern, it means all possible combinations of a pattern by rearranging the letters of a given word. Therefore, if we are given a pattern “abc”, then all of its anagrams will be</p><p><strong>[“abc”, “acb”, “bac”, “bca”, “cab”, “cba”]</strong></p><p>The goal of this problem is to find the all the indices, where any anagram of a given pattern is found in a string. The following diagram will make things a bit clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qu0W5CFd913mP-TcFLLTrA.png" /></figure><p>In the above diagram, at index 0, “abc” is found, then at index 5, “bca” is found, at index 6, “cab” is found, at index 7, “abc” is found and finally at index 8, “bca” is found. Therefore, the result becomes: <strong>[0,5,6,7,8]</strong></p><p>Now that we’ve got our goal sorted, let’s understand how we can translate it into a program.</p><p>One way to do it is to find all the combinations of the pattern, and then run a loop through the string and try to check if each <em>substring(from i to i+patternLength)</em> is equal to any combination of the pattern.</p><p>However, the biggest problem with this approach is that the number of combinations of a string depends on the number of characters in the string. A pattern of length ‘m’, can have ‘m!’ combinations. As we saw above with the pattern “abc”, there are 3 characters with<strong><em> [3! = 3 * 2 * 1 = 6]</em></strong> combinations. If the pattern becomes larger, the combinations too, significantly increase.</p><p>When we run the loop from 0 to (<em>stringLength-patternLength-1</em>). In each iteration, we check for the equality of each substring with each combination. If string is of length ’n’, then the runtime complexity of this approach becomes:</p><pre>O((n-m-1) * m!)<br>Now, n&gt;m (stringLength &gt; patternLength)<br>So we leave out the less dominant terms (-m &amp; -1), we get:<br><strong>O(n * m!)</strong></pre><p>This runtime complexity is huge, and therefore non-pragmatic.</p><blockquote>The bottleneck with the approach is the <strong>m! </strong>combinations that we have to iterate through. In order to optimize the runtime, we have to find a way to do this without calculating (and iterating through) all the combinations of the pattern.</blockquote><p>Let’s analyze how we can do this:</p><h3>Map-based Sliding Window Approach</h3><p>In this approach, we take two “windows”,</p><p>1We create a <em>window</em> for the pattern. In this window, we create a map of all the characters present in the pattern as keys and the number of times each character occurs in the window (counts) as values. The following diagram shows how your <strong><em>patternMap</em></strong> would look like for different patterns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knkrMW-TUUoej0yYulOQsw.png" /><figcaption>Window for the pattern (<strong>patternMap</strong>)</figcaption></figure><p>2Next, we create another window (<strong><em>substringMap</em></strong>) which is the size of the pattern. We compare this substring window (<strong><em>substringMap</em></strong>) with the pattern window (<strong><em>patternMap</em></strong>) and check whether the two windows have same characters with exact same count.</p><p>The reason we are using characters and their counts, is that the key-value pairs of a map for any string would be the same for any combination. For example,</p><blockquote>Given the pattern: “<strong>abc</strong>”, the map <strong>{a=1, b=1, c=1}</strong>, will be same for any combination of “abc” i.e [“abc”, “acb”, “bac”, “bca”, “cab”, “cba”]. Therefore, it removes the biggest bottleneck of finding and iterating through combinations.</blockquote><p>In the given example of the string <strong><em>abczzbcabcadeb</em></strong>, let’s see how the windows of this string will look like while iterating through the string. Please note that the pattern window will always be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bN95G9kKpDtvxAmWMD4zjQ.png" /><figcaption>Sliding Window anagram search with <strong>HashMap</strong></figcaption></figure><p>Now that we’ve got the visualization of this algorithm, let’s transform this into an actual program.</p><pre>List&lt;Integer&gt; <strong>findAnagramsOfPatternInString</strong>(String string, String pattern) {<br>    if(isEmpty(string) || isEmpty(pattern)){<br>        System.<em>out</em>.println(&quot;Invalid string or pattern&quot;);<br>        return null;<br>    }<br>    if(pattern.length() &gt; string.length()) {<br>        System.<em>out</em>.println(&quot;Pattern is larger than the string&quot;);<br>        return null;<br>    }<br><br>    Map&lt;Character, Integer&gt; patternMap= new HashMap&lt;&gt;();<br>    Map&lt;Character, Integer&gt; substringMap = new HashMap&lt;&gt;();<br>    List&lt;Integer&gt; foundIndices = new ArrayList&lt;&gt;();<br>    //we create two windows - one for pattern and other for the  <br>    //first substring    <br>    for(int i=0; i&lt;pattern.length(); i++) {<br>        <strong><em>addCharToWindow</em></strong>(pattern.charAt(i), patternMap);<br>        <strong><em>addCharToWindow</em></strong>(string.charAt(i), substringMap);<br>    }<br>    //start at the end of the first window<br>    for(int windowRightBound = pattern.length(); windowRightBound &lt; string.length(); windowRightBound++) {<br>        if(<strong><em>compare</em></strong>(patternMap, substringMap)) {<br>            //add to list if maps are equal<br>            foundIndices.add(windowRightBound - pattern.length());<br>        }<br>        //1. Remove the first character in the window<br>        int windowBegin_oldIndex = (windowRightBound -  <br>                                               pattern.length());<br>        Character staleCharacter =  <br>                              string.charAt(windowBegin_oldIndex);<br>        Integer staleCharacterCount = <br>                               substringMap.get(staleCharacter);<br>        if(staleCharacterCount == 1) {<br>            substringMap.remove(staleCharacter);<br>        } else {<br>            staleCharacterCount--;<br>            substringMap.put(staleCharacter, staleCharacterCount);<br>        }<br><br>        //2. Add the new character in the window<br>        <strong><em>addCharToWindow</em></strong>(string.charAt(windowRightBound), <br>                                                    substringMap);<br>    }<br><br>    //at this point, the last comparison window still remains, <br>    //so we still compare one last time<br>    if(<strong><em>compare</em></strong>(patternMap, substringMap)) {<br>        foundIndices.add(string.length() - pattern.length());<br>    }<br><br>    return foundIndices;<br>}</pre><pre>//method which returns true if a string is empty<br>boolean <strong><em>isEmpty</em></strong>(String string) {<br>  <strong>return </strong>string == null || pattern == null || <br>         string.length() == 0 || pattern.length() == 0;<br>}</pre><pre>//adds a character to the window. The window map is the argument<br>void <strong><em>addCharToWindow</em></strong>(Character character, Map&lt;Character, Integer&gt; map)  {<br>    Integer count = map.get(character);<br>    if(count == null) {<br>        count = 0;<br>    }<br>    count++;<br>    map.put(character, count);<br>}</pre><pre>//compare maps<br>boolean <strong><em>compare</em></strong>(Map&lt;Character, Integer&gt; patternMap, Map&lt;Character, Integer&gt; substringMap) {<br>    for(Map.Entry&lt;Character, Integer&gt; eachEntry: <br>                                      patternCounts.entrySet()) {<br>        Character eachCharacter = eachEntry.getKey();<br>        Integer eachCount = eachEntry.getValue();<br>        if(substringMap.get(eachCharacter) == null || <br>               substringMap.get(eachCharacter) != eachCount) {<br>            return false;<br>        }<br>    }<br>    return true;<br>}</pre><p>Now, let’s analyze the runtime complexity of this solution. Considering ‘<strong>m</strong>’ as the size of the pattern and ’<strong>n</strong>’ the size of the string.</p><pre>First, we create the maps of pattern and first substring (size m)<br>i.e. O(m) complexity</pre><pre>Next, we iterate through the string of size &#39;n&#39;<br>i.e. O(n) complexity</pre><pre>=&gt; O(m+n)complexity. <br>Here, m &lt; n; so we leave out the less dominant term (i.e. m)</pre><pre>=&gt; <strong>O(n) runtime complexity</strong></pre><p>A question may arise, that in each iteration through string, we are comparing two maps, which have their own loops. Why is that complexity not considered?</p><p>The answer is simple: The characters present in the string will always come from a unique set of characters. For example, if this problem comes with a constraint that the string can contain English alphanumeric characters, then the number of unique characters will be:</p><pre>a-z | 26 characters<br>A-Z | 26 characters<br>0-9 | 10 characters<br>i.e. total of 26 + 26 + 10 = <strong>62</strong> characters</pre><p>Therefore, the <strong><em>compare()</em></strong> method will have at most 62 characters to compare, which is a constant number. And if we are looping (for comparison) upto a constant iterations (i.e. 62 in this case), the runtime complexity of comparison will be in <strong>O(1) </strong>time (or constant time). Therefore, the comparison can be considered a constant time operation and the final runtime complexity will be as calculated: <strong>O(n): <em>where n is the length of the string</em>.</strong></p><p><em>Questions? Comments? Please feel free to write through the comments : )</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1d97ea71a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transaction handling in Microservices Architecture]]></title>
            <link>https://monisyousuf.medium.com/transaction-handling-in-microservices-architecture-e7ae13434fbb?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7ae13434fbb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 15:15:42 GMT</pubDate>
            <atom:updated>2020-10-05T15:15:42.585Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are familiar with how microservices architecture functions, then you must be familiar with the problems this architecture encompasses. The most dreaded one being <strong><em>Transaction Handling</em></strong><em>.</em></p><p>Ideally, a microservices architecture should be designed in such a way, that the transaction should not span across different services. Although in some situations this is unavoidable. Let’s take an example of a huge microservices based eCommerce architecture. Let’s say one microservice handles placing orders, and another microservice manages inventory. In such a situation, if an order succeeds, then you have to decrease the inventory (or stock) of the items which the user ordered. If the order failed, then the decrease inventory operation should NOT take place. Or, we can say that we want to ensure <strong><em>Atomicity</em></strong> for the whole operation. Either the order placement and decrease inventory — both should be successful, OR both should fail.</p><p>There are some design level patterns which can ensure a <strong><em>Distributed Transaction</em></strong> among different microservices. Let’s take them one by one</p><h3>Two-Phase Commit (2pc)</h3><p>As the name suggests, the process is divided into two phases and is handled by an instance called <strong><em>Transaction Coordinator.</em></strong> The main job of this <strong><em>coordinator</em></strong> is to coordinate or <strong>synchronize </strong>the status of the different microservices in a distributed environment. The process starts with the <em>prepare phase.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVgc0JGpANL2HyR9tmTBnA.png" /><figcaption><strong>Prepare Phase for Two-Phase Commit (2pc)</strong></figcaption></figure><ol><li><strong>Prepare Phase:</strong><em> </em>The transaction coordinator asks all the microservices which are involved in a transaction to <strong><em>prepare for a data change</em></strong>. Once all the microservices respond “<strong><em>Ready</em></strong>”, the operation moves on to the second phase. If any of the microservices are unresponsive due to any reason (like request timed out, or a non ready response), the prepare phase fails and henceforth, the transaction fails with a <strong><em>Rollback</em></strong>. At this point, a graceful message to the user is sent, usually with a <strong><em>retry</em></strong> option.</li><li><strong>Commit Phase: </strong>Once all the services respond <strong><em>ready</em></strong>, the microservices are said to be <strong><em>prepared</em></strong> for the changes. At this point, the actual data changes are then applied in the commit phase.</li></ol><p>Although the Two-Phase commit (2pc) ensures consistency and atomicity, it has its own <strong><em>disadvantages </em></strong>like:</p><ol><li><strong>Object Locking</strong>: 2pc commit protocol is based on synchronous locking mechanism. In case there are multiple data changes involved across multiple microservices, it can lock the objects until the whole transaction either succeeds or fails. In above example, If a user buys 5 quantities of some item, then 5 quantities of that item will be blocked for other users as well. This is usually not optimal especially in case of eCommerce applications where only limited stock per item is available.</li><li><strong>High Latency and Delays</strong>: In case where the number of microservices involved in a transaction are many, and some microservice transactions take longer (for example one microservice involves payments handled by a third party), then the latency could be huge and they can cause a performance bottleneck for the entire application.</li><li><strong>Deadlocks</strong>: In some cases, two transactions can mutually lock each other. This can happen when two transactions are holding one object each, and both require the object which is held by the other transaction.</li></ol><h3>Saga Pattern</h3><p>As we saw above, the 2pc is synchronous in nature and has its own set of drawbacks.</p><blockquote>The Saga pattern handles the transactions by communicating with asynchronous events through all the microservices involved in a transaction. The data changes happen locally on each microservice and the success/failure of a change on each microservice is transmitted through asynchronous event bus.</blockquote><p>In the example of an eCommerce transaction discussed above, the saga pattern would work in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReylaT1jHLU-3VvrNAqomQ.png" /><figcaption><strong>Saga Pattern in Microservices</strong></figcaption></figure><p>As we can see in the above diagram, If order is successful, an event is fired to the inventory microservice. On receiving the event, it starts the inventory update process. Once the inventory update succeeds, a success event is sent to other microservices involved. If no other microservices are involved, the transaction is complete. In this scenario, each microservice commits the transaction locally and communicates with other transactions through asynchronous events. In case any process in the microservice event chain fails, a failure event is sent back to ALL the microservices which were a part of the transaction before the failure, and the changes are rolled back.</p><p>In order to manage all these events efficiently, an <strong><em>orchestrator </em></strong>(or a process manager) is added to manage and coordinate all these events.</p><blockquote>This process overcomes the shortcomings of the two-phase commit (2pc) pattern. There are no object locks because the transactions take place locally on each service. The performance impact is also reduced significantly because all the local transactions can also be configured to run in parallel.</blockquote><p>From a performance perspective, this pattern is the go-to approach, but it is not without its <strong><em>disadvantages</em></strong>:</p><ol><li><strong>Hard to debug</strong>: If the number of microservices involved in a transaction are too many, it becomes difficult to debug. This can, however, be minimized by adding a unique trace ID to all the requests at the point of origin. The trace ID for each request is passed on through all the microservices for a request. This could possibly give us the point of error if a request is failing at any node.</li><li><strong>Difficulties with read isolation</strong>: Since there are no locks on any object, the user could possibly see stale data in some situations. For example, a transaction completed locally on a particular microservice. After this local commit succeeds, another user tries to see this data. The user sees the updated data. So far so good? However, after the write on one microservice, some other microservice in the event chain may fail and send a failure event which leads to rollback of the write-transaction. In such a case, the reader has seen data which actually does not exist anymore (or is stale or old).</li></ol><p>Each approach has its own shortcomings and advantages. There is no right or wrong in considering any approach. Having said that, each architecture &amp; their requirements are different. Design patterns have to be tailored according to needs. While these patterns explore the possibilities of transactions in distributed microservices architecture, your needs may require you to develop a monolith architecture. It all depends on what you’re building :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7ae13434fbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Design Principles and how to use them in Java?]]></title>
            <link>https://monisyousuf.medium.com/solid-design-principles-and-how-to-use-them-in-java-cfaaf5ea0f75?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfaaf5ea0f75</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 13:06:35 GMT</pubDate>
            <atom:updated>2020-09-24T13:06:35.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNQnXstyOoUpgMHqfiUMQQ.png" /></figure><p>We have often come across the acronym S.O.L.I.D in the field of object oriented programming. In fact, these 5 principles form the foundation of any object oriented code design. But before we jump onto a clear understanding of these principles and learn how to use them, let us get revise some basic concepts of object-oriented design/programming.</p><h3>What is object-oriented design?</h3><p>Object-oriented design is a programming model which is based on basic building blocks called <strong><em>Objects</em></strong><em>. </em>Each object has two features: <strong><em>attributes(data) &amp; behavior (methods/functions).</em></strong> The attributes hold actual data of a <strong><em>type</em></strong> (e.g. a String, Integer, Floating point value or reference of another object). A method, on the other hand is responsible for changing the state of these attribute(s). Therefore, a method or a function is actually the <strong><em>behavior</em></strong> of an object, as it defines how the data <strong><em>behaves</em></strong> when a certain method is called.</p><p>Before the objects are used, a blueprint of a certain type of objects is to be defined. The definition of an object consists of <strong><em>type of attributes &amp; function definition (behavior definition)</em></strong><em>. </em>These are defined into an entity called a <strong><em>Class</em></strong><em>.</em></p><p>Let us get a refresher on how a class and its objects look in Java:</p><pre><strong>class </strong><em>Employee</em><strong> </strong>{<br>   <strong>String</strong> <em>employeeId</em>;<br>   <strong>String </strong><em>name</em>;<br>   <strong>int </strong><em>age</em>;<br>   <strong>double </strong><em>salary</em>;</pre><pre>   public <strong>promoteEmployee</strong>(<strong>double </strong><em>percentIncrement</em>) {<br>     salary += (salary * percentIncrement)/100;<br>   }</pre><pre>}</pre><p>The above class <em>Employee</em> has defined few attributes like employeeId, name, age and salary. Each employee (or each object) will have its own set of values for this class. Also, a method <strong><em>promoteEmployee</em></strong> is defined, which changes the state of the object (and increases its salary by a certain percentage). This method defines the behavior of the attribute <strong><em>salary.</em></strong></p><p>Now that the basic concepts of object oriented programming are refreshed in our minds, let’s revisit some basic terminology which will be used to define the S.O.L.I.D fundamentals.</p><h3>Loose Coupling</h3><p>Two classes are said to be loosely coupled, when their association is defined on abstraction instead of actual objects.</p><p>Let’s see a Java 8+ based code example to make everything clearer:</p><pre>public interface <strong>AuthenticationService</strong>{<br>  public <strong>User </strong>login(<strong>String </strong>username, <strong>String </strong>password);<br>  default <strong>void </strong>logout(<strong>User</strong> user) {<br>     <em>// code to clear the session<br>     // and log the user out</em><br>  }<br>}</pre><p>The above example shows an interface <strong><em>AuthenticationService</em> </strong>with an abstract method to <em>login </em>a user using username and password. It also shows a default implementation of the <em>logout</em> functionality for a user (<em>as we already know that Java 8 now allows default implementation of methods in interfaces </em>😎<em> &amp; we don’t need to implement them. Although, we can if we wish</em>)</p><p>Now, let’s say an application has two different implementations for handling the user authentication. One for general users, and other for admin users.</p><p>Let’s say, we define two classes which implement this interface: <em>UserAuthenticationService &amp; AdminAuthentication service.</em> The code for these classes would look like.</p><pre>class <strong>UserAuthenticationService </strong>implements <strong><em>AuthenticationService</em></strong>{<br>   public <strong>User </strong>login(<strong>String </strong>username, <strong>String </strong>password) {<br><em>      //general user specific code to login</em><br>   }<br>}</pre><pre>class <strong>AdminAuthenticationService </strong>implements <strong><em>AuthenticationService</em></strong> {<br>   public <strong>User </strong>login(<strong>String</strong> username, <strong>String </strong>password) {<br>     <em> //admin user specific code to login<br>      //this code may connect to a different table<br>      //which holds only admin users</em><br>   }<br>}</pre><p>Now we have two service classes which implement one interface and have their own implementations for the <em>login. </em>Now, there should also be a class (A controller class), which would call login method by passing a username and password taken from the user.</p><pre>public class <strong>LoginController </strong>{<br>   <br>   @Inject<br>   public <strong>AuthenticationService</strong> authService;</pre><pre>   public <strong>ResponseEntity </strong>loginUser (<strong>UserData </strong>userData) {<br>      authService.login(userData.getUsername(),userData.getPwd());<br>      <em>// some other code to return the response</em><br>   }<br>}</pre><p>The above controller snippet has injected the <em>AuthenticationService</em> interface and not the actual implementing class. The framework figures out at which implementation to use at runtime. (<em>It requires some very basic additional configuration, which is beyond the scope of this article</em>).</p><blockquote>This association is defined by abstraction instead of the actual implementation. This is called loose coupling<em>.</em></blockquote><p>If the actual implementation was wired, it would be called <em>tight coupling, </em>which is NOT a good design pattern.</p><h3>High Cohesion</h3><p>A class is said to be highly cohesive when it performs logically similar operations. Conversely, a class is said to have low cohesion if it does a lot of operations which are not logically similar.</p><p>For example, in an application, if a class is defined in such a way that it contains operations for login, logout, sending email, subscribe to newsletter all wrapped in a single class — it has low cohesion. It is bad design because the operations in the class are not logically similar.</p><p>A good design would be to split the class into multiple classes, such as one class <em>AuthenticationService</em> which takes care of <em>login, logout, manage user data, </em>another class called <em>EmailService </em>which is responsible for sending all emails like <em>welcome email for new account, order summary email for a new order </em>and such. In this case, each class performs its own set of operations. If a class needs to do some other operation outside of its domain, it uses the object of another class which has that functionality. This is called <em>high cohesion</em>. This design is widely accepted, as it improves readability of code, makes it easy to maintain &amp; individual components can be re-used and injected into other services.</p><p>Now that the concepts are rushing back into the mind, let’s understand the 5 S.O.L.I.D. principles in object oriented design.</p><h3>The 5 pillars of object oriented design</h3><p>S — <strong>Single Responsibility Principle</strong>: Each class should have a single responsibility.</p><p>O — <strong>Open/Closed Principle</strong>: A class should be open for extension, but closed for modification.</p><p>L — <strong>Liskov’s Substitution Principle</strong>: Objects of a subclasses should be able to replace objects of a superclass.</p><p>I — <strong>Interface Segregation Principle</strong>: Multiple client facing interfaces should be created instead of one general purpose interface.</p><p>D — <strong>Dependency Inversion Principle</strong>: A class using an object of another class by association, should be coupled at runtime (loose coupling)</p><p>Let us deep-dive into these principles one-by-one:</p><h3>Single Responsibility Principle</h3><p>There is a famous quote by Steve Jobs:</p><blockquote>Do not try to do everything, Do one thing well .</blockquote><p>Single responsibility principle emphasizes on designing classes in such a way, that each class has its very own responsibility. If a class has multiple responsibilities, it has to be broken down into separate classes, each conforming to the <em>Single Responsibility principle.</em></p><p>Let’s see the following code snippet, which creates an account and send a welcome email to the user when the account is successfully created.</p><pre>class <strong>AccountService</strong> {<br>    public <strong>User </strong>login(String username, String password) {<br><em>      //some code to login</em><br>    }<br>    public <strong>void </strong>logout(<strong>User</strong> user) {<br><em>      //some code to log the user out</em><br>    }<br>    public <strong>void</strong> createAccount(<strong>String</strong>... someParameters) {<br>     <em>//code to take information and persist in the database</em><br>     <strong><em>sendEmail</em></strong>(name, email);<br>     <strong><em>sendSMS</em></strong>(name, phoneNumber);<br>   }<br>   public <strong>void</strong> sendEmail(<strong>String </strong>name, <strong>String </strong>email) {<br>     String message = &quot;Hi &quot; + <strong><em>name</em></strong> + &quot;, thanks for creating an&quot;<br>                         + &quot;account on our website&quot;;<br>  <em>   //code to connect to the SMTP server and send the email <br>     //with the above message</em><br>   }<br>}</pre><p>The above code is fully capable of creating an account and sending an email, but there are a few problems. There could be numerous places in the application, where an email is required to be sent to a user. For example, a forgot password email, an order summary email, notification email etc.</p><p>For each of these scenarios, it is not optimal to write a <strong><em>sendEmail </em></strong>method with the same code to connect to SMTP server and send a mail. The only variables that will change in an email, would be the message, subject and the email ID. The process of connection to SMTP server — its address, port and other details would remain the same. The above design would lead to a lot of code duplication. Copy-pasting the same code at every place also has its disadvantages. For example, if you switch to a new SMTP provider and have to change the way data goes to the SMTP server, you would have to change it in ALL the places, where the duplicate code is present. All this happens because the design of the application does not have classes, which have Single Responsibility.</p><p><strong><em>How can we do it better? Let’s see</em></strong></p><p>First, we create a class <strong><em>EmailService</em></strong>, for which the sole responsibility it to send an email to the recipients, with three variables: <strong><em>email</em></strong> (the recipient to which email is sent), <strong><em>subject &amp; body</em></strong> (HTML content of the email, which may contain HTML text and images). This EmailService class can be used by any other services to send emails (like forgot password or notifications).</p><pre>class <strong>EmailService </strong>{<br>  public <strong>void</strong> sendEmail(<strong>String </strong>email, <strong>String </strong>subject, <strong>String </strong>body) {<br>     //code to connect to SMTP Server and send email<br>  }<br>  <em>// the class could have other helper methods too, but only the   <br>  // responsibilities related to sending email.</em><br>}</pre><p>Next, we refactor the class <strong><em>AccountService </em></strong>to get rid of the email functionality, and hold the functionality only related to accounts. Since this class needs to send emails on the event of account creation, we INJECT the <strong><em>EmailService </em></strong>and use the <strong><em>sendEmail </em></strong>method as follows.</p><pre>class <strong>AccountService</strong> {</pre><pre>    @Inject<br>    private <strong>EmailService </strong>emailService;</pre><pre>    public <strong>User </strong>login(String username, String password) {<br><em>      //some code to login</em><br>    }<br>    public <strong>void </strong>logout(<strong>User</strong> user) {<br><em>      //some code to log the user out</em><br>    }<br>    public <strong>void</strong> createAccount(<strong>String</strong>... someParameters) {<br>      String body= //some code to create email message    <br>      String subject = &quot;Welcome &quot;+name;      <br>      emailService.sendEmail(email, subject, body);<br>   }<br> <br>}</pre><p>This way, we get two classes, each with their own responsibilities, easy to maintain, highly cohesive, loosely coupled and re-usable!</p><h3>Open-Closed Principle</h3><p>Open-Closed principle is quite simple. A class should be open for extension, but closed for modification. Let us see an example, to see what it means and WHY this principle is cool!</p><p>Let’s see the following code snippet, which shows an example of a code while generates a report in CSV &amp; XML Format respectively.</p><pre>class <strong>ReportGenerator</strong>{<br>    public <strong>File </strong>generateReport(<strong>String </strong>reportType) {<br>       if(reportType.equalsIgnoreCase(&quot;<strong><em>CSV</em></strong>&quot;)) { <br><em>          //Code for generating CSV Report</em><br>       } else if(reportType.equalsIgnoreCase(&quot;<strong><em>XML</em></strong>&quot;)) {<br><em>          //Code for generating XML report</em><br>       } else {<br>          <em>//Invalid Input</em><br>       }<br>}</pre><p>In the above class, if we would like to add a new report generation mechanism (say, an PDF file), we will have to modify the original file and add a new condition for <em>PDF </em>files in the same class.</p><p>Usually it is not a problem and it should work, but what if this class is to be exposed as a service package? In such a case, the implementing client will not have any code for this class and hence, will not be able to modify it. Therefore, the class become inextensible.</p><p>While considering open-closed principle, we redesign the class in the following way.</p><pre>public interface <strong>ReportGenerator </strong>{<br>   public <strong>File </strong>generateReport();<br>}</pre><pre>class <strong>CSVReportGenerator</strong> implements <strong>ReportGenerator</strong> {<br><em>  @Override</em><br>  public File generateReport() {<br><em>    // code for generating CSV Report</em><br>  }<br>}</pre><pre>class <strong>XMLReportGenerator </strong>implements <strong>ReportGenerator </strong>{<br><em>  @Override</em><br>  public File generateReport() {<br><em>    // code for generating XML Report</em><br>  }<br>}</pre><p>In the above scenario, the interface <em>ReportGenerator </em>exposes a function <em>generateReport()</em> which is implemented by <em>Specialized</em> classes created for generating a type of report such as <em>CSVReportGenerator &amp; XMLReportGenerator.</em> If we need to add a PDF type of report generator, we do not need to change any of the existing classes above.</p><p>We can simply implement the public interface and write our own code for PDF report generation. Example:</p><pre>public class <strong>PDFReportGenerator </strong>implements <strong>ReportGenerator </strong>{<br><em>   @Override<br></em>   public <strong>File </strong>generateReport() {<br>    <em>  //code for generating PDF report</em><br>   }<br>}</pre><h3>Liskov’s Substitution principle</h3><p>Liskov’s substitution principle states that an object of a <strong><em>Superclass </em></strong>must be substitutable by objects of its <strong><em>Subclass.</em></strong></p><p>For example, there is a class called <strong><em>Super </em></strong>which has a subtype <strong><em>Sub,</em></strong><em> </em>then objects of Super should be able to be replaced by objects of Sub. For example,</p><pre><strong>Super </strong>referenceVariable = new <strong>Sub</strong>();</pre><p>In java, because of type safety, you cannot assign a random object to the reference variable of a class. It throws a compile-time error!</p><p>For example, <strong><em>Test</em></strong> is nowhere in the hierarchy of <strong><em>Super. </em></strong>Therefore, since the below statement violates Liskov’s substitution principle, it is a compile time error.</p><pre>Super referenceVariable = new Test();</pre><p>Interestingly, Liskov’s substitution principle does not end here. There are programming concerns which can violate this principle at a design level.</p><blockquote>This principle is not just about type safety, but it also implies that the <strong>behavior of the subclass should also be similar as the behavior of the superclass.</strong></blockquote><p>Let’s see the following class structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDnp17enChUVcx43W4oquA.png" /><figcaption>Violation of Liskov’s Substituition Principle (Bad Design)</figcaption></figure><p>Having a look at above structure, there is an Interface <strong><em>Card</em></strong> which defines certain operations. The classes <strong><em>CreditCard</em></strong> and <strong><em>DebitCard</em></strong> implement this interface, with their own implementation of <strong><em>validate(), authorize() and debit()</em></strong> methods. The odd one out is <strong><em>RewardsCard</em></strong> implementation. It does not require the <strong><em>authorize() </em></strong>method which is specific only to credit and debit cards. What to do in such a case? — We either leave the implementation blank OR throw an exception in the method.</p><p>Next, it adds a new public method <strong><em>addPoints() </em></strong>which adds points to the <strong><em>RewardsCard</em></strong> whenever a user shops. This method was not initially a part of the interface. Now, one method in the contract is unimplemented (and useless) and on the other hand, a new public method is exposed for use. While these class structures would compile, we would run into issues when we try to do:</p><pre><strong>Card </strong>card = new <strong>RewardsCard</strong>(.. some params ..); <em>//compiles</em><br>card.validate(); <em>//compiles</em><br>card.authorize();<em>//compiles but changes expected behavior. </em><strong><em>Violation<br></em></strong>card.addPoints(10); <em>//compilation FAILS!</em></pre><p>See line 4 &amp; 5 in the above code. Although the hierarchy is correct and compiles, we run into issues when we call the non-used implementation at line (4) and use the superclass variable to call a method which was not in the interface contract at line (5). Both of these statements violate the Liskov’s principle.</p><p>In such a case, we redesign the classes in another way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HB_c-3ZhujtHiGmbL6-tRA.png" /></figure><p>On redesigning the classes, we break the interface <strong><em>Card </em></strong>into two interfaces <strong><em>AuthorizableCard</em></strong> which requires authorization &amp; re-uses <strong><em>Card </em></strong>interface’s basic <strong><em>validation and debit </em></strong>methods. The new contract for the <strong><em>CreditCard and DebitCard</em></strong> is now with <strong><em>AuthorizableCard</em></strong>. In this case, all the methods are properly implemented and no new public methods are added.</p><pre><strong>AuthorizableCard </strong>card = new <strong>CreditCard</strong>(... params ...);<br>card.validate(); <em>//compiles &amp; implemented</em><br>card.authorize(amount); <em>//compiles and implemented</em><br>card.debit(amount); <em>//compiles and properly implemented</em></pre><p>Similarly, <strong><em>PointsCard </em></strong>interface also extends the basic functionality of <strong><em>Card. </em></strong>The <strong><em>RewardsCard </em></strong>class now has a contract with <strong><em>PointsCard</em></strong>, which holds the <strong><em>addPoints </em></strong>method. It fulfills the contract and retains the <strong><em>behavior of the PointsCard. </em></strong>It is also good for extensibility, as If we need to customize and add new types of <strong><em>PointsCard </em></strong>classes (like <strong><em>BronzePointsCard</em></strong>, <strong><em>SilverPointsCard </em></strong>and <strong><em>GoldPointsCard</em></strong>), we just implement the <strong><em>PointsCard</em></strong> interface, and update the implementation of the <strong><em>addPoints()</em></strong> in these classes. The behavior overall, remains the same: on calling addPoints(), some points are added to the card.</p><h3>Interface Segregation Principle</h3><p>Interface segregation principle states that <em>a client should not be forced to depend on methods which are optional for implementation. Instead, multiple interfaces should be created for use.</em></p><p>This principle is pretty much straightforward. For example, you can have a look at the above Liskov’s substituition principle and how the <strong><em>Card </em></strong>Interface was split into <strong><em>RewardsCard and AuthorizableCard.</em></strong></p><h3>Dependency Inversion Principle</h3><blockquote>A class using an object of another class by association, should be coupled at runtime.</blockquote><p>We are already aware of the concept of loose coupling (revisit the example of loose coupling mentioned above before proceeding), let’s see an example of how loose coupling is done in the context of Dependency Inversion:</p><pre><em>@Controller<br>@RequestMapping(&quot;/admin&quot;)</em><br>public class <strong>AdminLoginController </strong>{<br><em>   @Inject</em><br>   private AuthenticationService authService;</pre><pre><em>@PostMapping(&quot;/login&quot;)</em><br>public void loginAdminUser(<strong>UserDetails </strong>userDetails) {<br> authService.login(userDetails.getUsername(), userDetails.getPwd());<br> //return response<br>}</pre><p>In the above case, we wrote a controller, which takes the username and password from a user request whenever a <strong>POST </strong>request is made to <strong><em>/admin/login</em></strong>. The <em>AuthenticationService</em> bean is resolved to <strong><em>AdminAuthenticationService.</em></strong></p><p>Similarly, when a POST request is made to <strong><em>/user/login </em></strong>with username and password, the same bean is resolved to <strong><em>UserAuthenticationService.</em></strong></p><pre><em>@Controller<br>@RequestMapping(&quot;/user&quot;)</em><br>public class <strong>UserAccountController </strong>{<br><em>   @Inject</em><br>   private AuthenticationService authService;</pre><pre><em>@PostMapping(&quot;/login&quot;)</em><br>public void loginAdminUser(<strong>UserDetails </strong>userDetails) {<br> authService.login(userDetails.getUsername(), userDetails.getPwd());<br> //return response<br>}</pre><p>The question is, how do we configure which bean implementation is to be loaded at runtime and when? One of the many ways to do this is by using <strong><em>@ConditionalOnProperty </em></strong>annotation<strong><em>.</em></strong></p><p>Let’s say you have a spring application, which runs in two production modes: <em>admin &amp; user</em><strong>. </strong>If the <strong><em>admin </em></strong>profile is running, you want to initialize the <strong><em>AdminAuthenticationService </em></strong>and if <strong><em>user </em></strong>profile is running you want to initialize the <strong><em>UserAuthenticationService</em></strong>. The spring property which corresponds with the running user profile is <strong><em>spring.profile.active</em></strong>.</p><p>Therefore, in the class <strong><em>AdminAuthenticationService, </em></strong>we define</p><pre><em>@Service <br>@ConditionalOnBean(prefix=&quot;spring.profiles&quot; name=&quot;active&quot; havingValue=&quot;</em><strong><em>admin</em></strong><em>&quot;)<br></em>class <strong>AdminAuthenticationService </strong>{<br>   ..... code ....<br>}</pre><p>and in <strong><em>UserAuthenticationService</em></strong>, we define:</p><pre><em>@Service <br>@ConditionalOnBean(prefix=&quot;spring.profiles&quot; name=&quot;active&quot; havingValue=&quot;</em><strong><em>user</em></strong><em>&quot;)<br></em>class <strong>UserAuthenticationService </strong>{<br>   ..... code ....<br>}</pre><p>There are numerous ways to conditionally initialize beans with minimal code and configuration. And this is how you invert the dependencies and provide them at runtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfaaf5ea0f75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Microservices? Simplified]]></title>
            <link>https://monisyousuf.medium.com/what-are-microservices-simplified-c4db729d56bc?source=rss-db5229015c92------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4db729d56bc</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <dc:creator><![CDATA[Monis Yousuf]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 09:40:48 GMT</pubDate>
            <atom:updated>2024-01-03T11:22:51.710Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNNF0utP9IjQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNNF0utP9IjQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNNF0utP9IjQ%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/b11b0752cc57e039f637ee8f0cab512a/href">https://medium.com/media/b11b0752cc57e039f637ee8f0cab512a/href</a></iframe><p>Imagine a scenario, where the President of a country is the only person who handles law, finance, international defense, education, transport and all other things?</p><p>Imagine, a CEO of a big fortune 500 company like Amazon, who takes care of the of technology, human resources, employment, marketing, operations and finance?</p><p>Sounds crazy, right? If only, there was a better way….</p><p>The “<em>better way” </em>is obvious, a President has a cabinet of ministers who handle their own domain and have completely responsibility of that area. A fortune 500 company has executives who head their respective departments. In both these cases, there are different people — who have expertise and specialization in their own domain. If they need help from another department, they simply seek help from an executive of another department.</p><p>Makes sense, right? This is the underlying concept of Microservices…</p><p><strong><em>Confused? Read on…</em></strong></p><p>Consider a large scale eCommerce application such as Amazon. Amazon has various underlying operations like authentication, profile management, product management, browse and shopping experience, inventory management, payments, order management, frontend and such. Let’s say that all these services are packed into one HUGE application. Now, this application is responsible for all the operations executed as a result of user interaction, just like the CEO who does everything! This kind of application architecture is called <strong><em>Monolithic architecture</em></strong>.</p><h3>Breakdown of Monolithic architecture</h3><p>Let us have a look in detail of what a very basic Monolithic architecture looks like:</p><figure><img alt="Monolithic architecture diagram" src="https://cdn-images-1.medium.com/max/1024/1*9AOz5_EF3LAtzzTEcBgrBg.png" /></figure><ol><li>In the above diagram, an end user is connected to the internet and accesses an application. The request from the client (browser) navigates to the hosted website through the internet.</li><li>A<strong> <em>Load Balancer</em></strong><em> </em>is usually configured as a first point of contact between the incoming request and the physical servers (<em>in the diagram, one physical server is shown. Depending on the load of an application, more servers can be added and registered with the Load Balancer</em>).</li><li>A load balancer makes sure that the incoming requests (possibly coming from thousands or millions of users) are spread evenly among the physical servers.</li><li>Each physical machine has single or multiple instances of the application which actually processes the user requests.</li><li>The components and services inside the application (like Inventory, Profile Management, Browsing, Shopping, Payment etc.) are tightly connected to each other. The interact with each other and generate a response to that request and send it back to the client.</li></ol><h3>What is wrong with a Monolithic architecture?</h3><p>While the rights and wrongs of choosing an architecture is usually requirement based, but there are some general concerns while developing into this architecture:</p><ol><li><strong>Scalability</strong>: The biggest concern with a monolithic architecture is scalability. A huge application having everything compiled into a single chunk is difficult to scale. If new servers need to be added, the whole application has to be deployed to every server.</li><li><strong>Large Codebase</strong>: Requires maintenance of a large codebase. This may not be a concern in early stages, but as the application features increase, changes have to be made in different services and the frontend.</li><li><strong>Small Change, Big deployment</strong>: For the smallest changes, the whole code has to be compiled, encapsuled and deployed again on all servers. Even if it is a small layout change, such as shifting a button from left to right!</li><li><strong>Tightly coupled: </strong>The whole application is tightly intertwined. All the services and components MUST be available for the application to be compiled. A re-deployment is necessary even if one component does not directly affect another (for example, refactoring the UI into a new layout would require building and deployment of the backend services, although there are no changes in the backend)</li></ol><h3>The solution? Microservices!</h3><blockquote>A microservices architecture breaks down an application into loosely-coupled logically separate services, each of which holds a “<strong>Single Responsibility</strong>”. These services interact with each other with the help of <strong>synchronous </strong>(HTTP REST APIs) and <strong>asynchronous</strong> (Kafka, RabbitMQ) communication.</blockquote><p>In the example of eCommerce application we discussed above, it could be divided into multiple microservices, each having their own life cycle. For example, a separate module for each of the services of Profile Management, Inventory Management, Cart, Payment etc. could be deployed.</p><p>When a user adds an item to cart and completes the payment, an asynchronous push message (via Kafka or RabbitMQ) can be sent to the Inventory Management microservice, to reduce the inventory items in the database. Similarly, when a user goes to see previous orders in the profile, a REST API call to Order Management microservices can be made to fetch the order history and the latest state of the orders (processing, in delivery, delivered etc.)</p><h3>Breakdown of Microservices Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRB6guDBb2QmF9oZu7AQ6Q.png" /></figure><p>The above diagram shows a very basic representation of an eCommerce based microservices application. Let’s see how the flow works:</p><ol><li>A client can access the application by a<strong><em> native mobile app (android or iOS) </em></strong>which interacts with the application through the internet.</li><li>A client can access the application by <strong><em>a browser (web app) on a computer or a mobile phone</em></strong> via the internet.</li><li>Certain features of the application can also be accessed through an <strong><em>Admin Console</em></strong> which is used by the company employees to <em>add new products, update existing products &amp; updating inventory of products (which recently came in stock).</em></li><li>The request from the client (from either [1], [2] or [3]) goes to an <strong><em>API Gateway, </em></strong>which figures out the microservice to be called based on the incoming request.</li><li>If the request is coming from an Admin Console to update the inventory of a product (for new stock of that item), then the call goes to the<strong><em> Inventory microservice </em></strong>to update the stock of a current product. The update inventory call (for new stock) is usually done with an <em>authentication &amp; authorization</em> mechanism, so that only authorized users can update the inventory (and not the end users).</li><li>If a Native Mobile App or a Web App is accessing the application for browsing the products, then the <strong><em>API Gateway</em></strong> passes on the incoming request to the <em>Shopping &amp; Browsing</em> microservice, which can hold a lot of different APIs like getting the products in a category (like <strong><em>Men’s Trousers</em></strong>) OR getting the detail (like size, material, color, description, washing instructions, reviews) and pricing of a single product (e.g. <strong><em>Lacoste White Sneakers</em></strong>).</li><li>There could be other microservices in the application which perform other tasks. For example, a <strong><em>Cart Operations </em></strong>microservice which has APIs to add/remove a product to/from the cart, to update the quantity of the items in the cart. Or a <strong><em>Checkout Operations</em></strong><em> </em>microservice which takes the shipping address, billing address, delivery instructions, gifting wrap instructions to complete a checkout process.</li><li>Ultimately, when the user passes through these microservices, the user pays for their items. The <strong><em>Payments </em></strong>microservice is solely responsible for handling payments through multiple means like <em>Credit Card, Bank Account Debit, Paypal </em>and such.</li><li>The <strong><em>Payments</em></strong> service, in turn may pass the request to other microservices on successful order like sending an asynchronous KAFKA message to the <strong><em>Email</em></strong> microservice which sends an email to the end user with a summary of the order AND/OR to the <strong><em>Inventory </em></strong>microservice to reduce the inventory of purchased item(s) in the order.</li></ol><blockquote>There may be cases where one microservice receives a lot more load than the other microservices. For example, a product browsing microservice will receive much more requests compared to an Account Management microservice. In such a case, multiple servers for the <strong>Browsing &amp; Shopping</strong> microservice can be setup which can managed by their very own <strong>Load Balancer</strong>.</blockquote><h3>Advantages of using Microservices architecture</h3><ol><li><strong>Modular Changes: </strong>Changes in one service does not require deployment of all the services. For example, once a user successfully places an order, an email has to be sent to the regional delivery manager. This change requires changes only in the Order Management microservice, while the other services remain unchanged.</li><li><strong>Easy to maintain</strong>: Since each microservice is decoupled from another and has a different codebase, different teams can work on their individual modules without impacting other modules. One of the biggest examples of such a case is the separation of backend and frontend. Frontend changes which do not revolve around the APIs (like layout changes, CSS changes, javascript changes) can be deployed separately. In fact, frontend releases can be entirely decoupled from backend releases in many cases.</li><li><strong>Scalability</strong>: Some microservices can be heavily used (like product browsing API), while other microservices are less frequently used (e.g. Profile Management). These heavy microservices can be easily upscaled, while the other ones can run on low resources. Thus, optimizing the cost of the overall architecture.</li><li><strong>Fault Isolation</strong>: If one of the services is down, the whole application does not go down. For example, if inventory management is down, the whole application does not have to be unavailable. Instead, a robust and graceful error message can be shown in such a case.</li></ol><h3>Concerns in using Microservices Architecture</h3><p>So far, it sounds great to employ microservices architecture for a new application, but it also comes at a cost. In some cases, it may be a pain to use this paradigm.</p><ol><li><strong>Latency</strong>: Since there are different microservices which interact with each other, there may be delays due to communication overhead.</li><li><strong>Transaction Management: </strong>Transaction management across different services is a pain. Although there are strategies to manage that, it causes additional latency.</li><li><strong>Integration Testing</strong>: Integration testing becomes difficult and hard to manage. Extra configuration needed to setup testing infrastructure.</li><li><strong>Server Resources</strong>: Since each microservice requires its own container, it adds up additional cost.</li></ol><h3>When to use Monolithic architecture?</h3><p>A monolithic architecture is recommended, when there is limited time and resources to build an application. A monolithic application can significantly reduce the development time and can be cost-optimized in primitive stages of a product OR a POC project OR an MVP (Minimum Viable Product).</p><p><em>Still have questions? Drop them in the comments section… :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4db729d56bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>