<?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 Himasha Silva on Medium]]></title>
        <description><![CDATA[Stories by Himasha Silva on Medium]]></description>
        <link>https://medium.com/@himashasilva?source=rss-1da9afa4c9b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z1BK_JBO5nilALLGJ_hB8Q.jpeg</url>
            <title>Stories by Himasha Silva on Medium</title>
            <link>https://medium.com/@himashasilva?source=rss-1da9afa4c9b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:47:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@himashasilva/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[How to Setup Pyppeteer Proxy For Scraping?]]></title>
            <link>https://medium.com/@himashasilva/how-to-setup-pyppeteer-proxy-for-scraping-3f95469d579c?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f95469d579c</guid>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Sun, 24 May 2026 05:04:32 GMT</pubDate>
            <atom:updated>2026-05-24T05:04:32.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*fAo2n5MLj2oJfURc.jpeg" /></figure><p>Web scraping is a useful technique for extracting valuable insights from the internet. Python is a top choice for web scraping tasks , with its versatility and various libraries. It can retrieve data from websites, automate browser interactions, and parse HTML/XML documents,making it more simpler.</p><p>When scraping websites, it is often necessary to use a proxy to avoid being detected and blocked. This is because websites can detect and block scrapers by looking at their IP addresses. A proxy allows you to route your traffic through a different IP address, making it appear as if you are from a different location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_hm5Kuc4hWrob-MK.jpeg" /><figcaption>Scraping process using proxy server</figcaption></figure><blockquote><strong><em>Pyppeteer is a Python library that provides a high-level API for controlling headless Chrome or Chromium browsers using the Chrome DevTools Protocol which can be used mainly in web scraping.</em></strong></blockquote><p>This article highlights on three main types of proxies that you can use with Pyppeteer, how to setup and more advanced tips for more successful scraping with Pyppeteer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*boE2dbGtm6DcMQZ5.png" /><figcaption>Main types of proxies and use cases</figcaption></figure><h3>How to set up a proxy on Pyppeteer?</h3><p>Let’s start with the simple type of proxy, static 1 IP proxy configuration. This provides a single IP address that you can use for all of your scraping requests. This type of proxy is most suitable for scraping websites that are not very aggressive about blocking scrapers that means low-volume scraping.</p><p>Here’s how to set up a proxy in Pyppeteer. To set up a static 1 IP proxy on Pyppeteer, you need to know the IP address and port number of your proxy server. You can then pass this information to the ‘<strong><em>args’</em></strong> parameter of the<em> </em><strong><em>launch()</em></strong> method.For example, the following code shows how to set up a static 1 IP proxy on Pyppeteer using a proxy server with the IP address <em>192.168.1.1</em> and the port number <em>8080 :</em></p><pre>import asyncio<br>import pyppeteer<br><br>async def main():<br>    browser = await pyppeteer.launch(args=[&#39;--proxy-server=http://192.168.1.1:8080&#39;])<br>    page = await browser.newPage()<br>    await page.goto(&#39;https://google.com&#39;)<br>    print(await page.content())<br><br>asyncio.run(main())</pre><h3>How to set up a rotating proxy on Pyppeteer?</h3><p>Rotating proxy provides a pool of IP addresses that you can rotate through. This ensures that it is more difficult for websites to detect and block your scraping activity. Rotating proxies are suitable for high-volume scraping or for avoiding IP bans and rate limits on websites that track and restrict web scraping activities.</p><p>Basically there are two ways that Pyppeteer allows to setup :</p><ul><li>Rotating proxy endpoint method</li><li>Rotating proxy list method</li></ul><h3>Rotating proxy list method</h3><p>Rotating proxy list method involves having a list of proxy servers and rotating through them at regular intervals.To set up on Pyppeteer using a proxy server list, you need to create a list of proxy servers. Then you can pass this list to the proxy parameter of the<strong><em> launch()</em></strong> method. Here’s the example code :</p><pre>import asyncio<br>import pyppeteer<br><br>async def main():<br><br>    # Create a list of proxy servers<br>    proxies = [<br>        &#39;http://192.168.1.1:8080&#39;,<br>        &#39;http://192.168.1.2:8080&#39;,<br>        &#39;http://192.168.1.3:8080&#39;,<br>    ]<br><br>    browser = await pyppeteer.launch(proxy=proxies)<br>    page = await browser.newPage()<br>    await page.goto(&#39;https://google.com&#39;)<br>    print(await page.content())<br>    await browser.close()<br><br>asyncio.run(main())</pre><h3>Rotating proxy endpoint method</h3><p>To set up a rotating proxy on Pyppeteer using a rotating proxy endpoint, you need to know the URL of the endpoint. You can then pass the URL to the proxy parameter of the<strong><em> launch()</em></strong> method.</p><p>For example, the below code shows how to set up a rotating proxy on Pyppeteer using a rotating proxy endpoint with the URL <a href="https://example.com/proxy"><em>https://example.com/proxy</em></a><em> </em>:</p><pre>import asyncio<br>import pyppeteer<br><br>async def main():<br><br>    browser = await pyppeteer.launch(proxy=&#39;https://example.com/proxy&#39;)<br>    page = await browser.newPage()<br>    await page.goto(&#39;https://google.com&#39;)<br>    print(await page.content())<br><br>asyncio.run(main())</pre><h3>How to set up a residential proxy on Pyppeteer?</h3><p>Residential proxies are IP s assigned to real residential addresses, so that they appear like regular users. This makes it the most challenging type of proxy for websites to detect and block. Residential proxies are most suitable for scraping websites that are very sensitive to scraping activity, such as e-commerce websites and social media platforms.</p><p>Here’s an example for setup :</p><pre>import asyncio<br>import pyppeteer<br><br># Get the residential proxy IP address and port number<br>proxy_ip = &quot;192.168.1.1&quot;<br>proxy_port = 8080<br><br># Create a residential proxy URL<br>proxy_url = f&quot;http://{proxy_ip}:{proxy_port}&quot;<br><br># Launch a Pyppeteer browser using the residential proxy<br>browser = await pyppeteer.launch(proxy=proxy_url)</pre><p>In the above example, ‘<strong><em>browser’</em></strong> is a Pyppeteer browser that is configured to use the residential proxy server. ‘<strong><em>proxy_ip’</em></strong> and ‘<strong><em>proxy_port’</em></strong> are the IP address and port number of the residential proxy server. ‘<strong><em>proxy_url’</em></strong> is the URL of the residential proxy server.</p><p>As some residential proxy providers require authentication, you can pass your username and password to the <strong><em>auth</em></strong> parameter of the <strong><em>launch()</em></strong> method to autenticate.</p><pre>import asyncio<br>import pyppeteer<br><br># Get the residential proxy IP address and port number<br>proxy_ip = &quot;192.168.1.1&quot;<br>proxy_port = 8080<br><br># Get the residential proxy username and password<br>proxy_username = &quot;username&quot;<br>proxy_password = &quot;password&quot;<br><br># Create a residential proxy URL<br>proxy_url = f&quot;http://{proxy_ip}:{proxy_port}&quot;<br><br># Launch a Pyppeteer browser using the residential proxy and authentication<br>browser = await pyppeteer.launch(proxy=proxy_url, auth=(proxy_username, proxy_password))</pre><p><em>Learn more about proxy setup : </em><a href="https://www.webshare.io/blog/puppeteer-proxy"><em>https://www.webshare.io/blog/puppeteer-proxy</em></a></p><h3>Advanced tips for more successful scraping with Pyppeteer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*27slWXUTxMs7hSo0" /></figure><ol><li><strong>Manage Cookies</strong></li></ol><p>Pyppeteer automatically manages cookies for you, but you may need to manually manage cookies in certain cases. For example, you may need to clear cookies before each scraping request to avoid getting blocked.(<strong><em>page.deleteCookie()</em></strong>). Explore more about managing cookies: <a href="http://www.webshare.io/blog/puppeteer-cookies">http://www.webshare.io/blog/puppeteer-cookies</a></p><p><strong>2. HTTP headers</strong></p><p>HTTP headers are significant components of the HTTP protocol, which are used to transfer information and instructions between clients and servers. They enable authentication, content negotiation, caching, security, and session management while playing an important role in web scraping by replicating actual user behavior through headers like User-Agent and Cookie.</p><p><strong>3. Use a user agent</strong></p><p>Websites often recognize scraping by analyzing the User-Agent header. You can change the User-Agent using the <strong><em>page.setUserAgent</em></strong> function to act like different browsers and devices.Pyppeteer uses a default user agent, but to avoid getting blocked you may want to use a different user agent. For example, you can use a mobile user agent to scrape mobile websites.Learn more about user agents: <a href="https://www.webshare.io/blog/puppeteer-user-agent">https://www.webshare.io/blog/puppeteer-user-agent</a></p><p><strong>4. Create more natural browsing patterns</strong></p><p>To avoid detection, you can simulate browsing patterns like humans do. Use random delays between requests, click on links, and scroll the pages using Pyppeteer’s functions.</p><h3>Conclusion</h3><p>In this article, we’ve explored several methods for setting up proxies in Pyppeteer to enhance the web scraping capabilities. Whether you need a simple static proxy or a sophisticated residential proxy, Pyppeteer offers the flexibility to cater to your scraping requirements. So by considering specific use case and requirements you can select best methods and techniques for improved web scraping.</p><p>Stay tuned for more useful articles. Happy scraping!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f95469d579c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prolog Data Types: Exploring Atoms, Variables, and Terms]]></title>
            <link>https://medium.com/@himashasilva/prolog-data-types-exploring-atoms-variables-and-terms-52a4339d8b30?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a4339d8b30</guid>
            <category><![CDATA[swi-prolog]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[atom]]></category>
            <category><![CDATA[facts]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 18:16:48 GMT</pubDate>
            <atom:updated>2023-10-17T18:16:48.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*96jUhwJ0NESIeJh7.jpg" /></figure><h3><strong>Introduction</strong></h3><p>Welcome back to our Prolog journey! In our previous article, “A Beginner’s Guide to Prolog: Unlocking the Power of Logic Programming,” we introduced you to the world of Prolog, its declarative nature, and how it’s used in logical reasoning. Now, we’re going to delve deeper and explore Prolog’s fundamental data types: atoms, variables, and terms.</p><h3>Characters in Prolog</h3><p>In Prolog, a character is a single symbol or letter from the character set that means any printable character, including letters, digits, punctuation marks, and special characters. Also, sometimes it can be non-printing character such as blank space,new line,beeping sound etc.</p><h3>Constants</h3><p>Constants can be numbers or atoms.</p><h4><strong>Atoms</strong></h4><p>In Prolog, atoms are the simplest and most basic data type. They are used to represent constants or names. Atoms in Prolog are case-sensitive, meaning that uppercase and lowercase letters are treated as distinct. Typically, atoms begin with a lowercase letter and contains both letters and digits. Signs such as -+ , / \ also considered as atoms. Here are some examples of atoms:</p><pre>pizza.<br>john.<br>likes.</pre><p>In the examples above, “pizza,” “john,” and “likes” are all atoms. Atoms are used to represent objects, concepts, or constants within the Prolog knowledge base.</p><p>If we have the word begin in an uppercase letter it will consider as a variable(not a constant or atom).</p><p><strong><em>Ex: Dev</em></strong></p><p>But when a word begins with a uppercase letter is surrounded by single quotation marks they are also considered as atoms.</p><p><strong><em>Ex : ‘Dev’ is an atom.</em></strong></p><h3><strong>Variables in Prolog</strong></h3><p>Variables in Prolog are placeholders for values that can vary. Prolog variables are also case-sensitive and typically start with an uppercase letter or an underscore. Variables are a fundamental part of making queries and finding values that satisfy specific conditions. Let’s explore variable examples.</p><pre>X.<br>_Y.<br>Person.</pre><p>In these examples, “X,” “_Y,” and “Person” are Prolog variables. They are used to represent unknown values, which can be determined through queries and unification with other terms.</p><h4>Anonymous Variables → ???</h4><p>Let’s learn them in future lessons…</p><h3><strong>Terms(Facts) in Prolog</strong></h3><p>Prolog’s terms are a way of combining atoms and variables to create more complex data structures. Terms can be as simple as a single atom or as complex as a combination of atoms, variables, and other terms. A term can be considered a fundamental unit in Prolog. Here are some examples of Prolog terms:</p><pre>loves(john, mary).<br>likes(pizza, X).<br>food(john, pizza, apple).</pre><p>In the first example, we have a term representing a “loves” relationship between John and Mary. The term combines the atoms “loves,” “john,” and “mary.” In the second example, the term “likes(pizza, X)” expresses that someone likes pizza, but the identity of that someone is represented by the variable X. The third example is a more complex term representing John&#39;s preference for a combination of pizza and apples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*_5dpl5M0--1DMAMLx3Qc0A.png" /><figcaption>Prolog editor and Query section</figcaption></figure><h3><strong>Using Prolog Data Types in Simple Programs</strong></h3><p>Let’s put our knowledge of Prolog data types to use by creating a simple Prolog program (you can type these facts in editor section):</p><pre>% Facts<br>likes(john, pizza).<br>likes(john, spaghetti).<br>likes(john, burger).<br>likes(mary, pizza).<br>likes(bob, burger).</pre><p>In this program, we define a set of facts about what different people like. These facts use atoms and variables to express preferences.</p><p>But writing these facts for each and every food separately is a difficult task. So as a solution we can easily define rules.For example :</p><pre>likes(john, X):- food(X).<br>foodie(X) :- likes(X, pizza), likes(X, spaghetti).</pre><p>In second rule, foodie(X), which states that someone is a foodie if they like both pizza and spaghetti. This rule uses variables to represent the someone we are referring to. Here, in that rule we have used “<strong>conjunction”</strong> that means combination of 2 or more facts using ‘comma’</p><blockquote><strong>Some important tips to remember:</strong></blockquote><blockquote>Sometimes facts and rules may be contradictory to real world scenarios.</blockquote><blockquote>Don’t forget to put fullstop at the end of each statement.</blockquote><h4><strong>Queries in Prolog</strong></h4><p>In Prolog, we can use queries to interact with the system and find answers based on the available data and rules. Here are some example queries:</p><ul><li>To find out who likes pizza:</li></ul><pre>?- likes(X, pizza).</pre><p>When you run this query, Prolog will respond with a list of people who like pizza, using the information from the facts.</p><ul><li>To find out who is a foodie:</li></ul><pre>?- foodie(X).</pre><blockquote>Now let’s learn how to run a simple program in prolog.</blockquote><h4><strong>First follow these steps :</strong></h4><ol><li>Open SWI Prolog.</li><li>Click on ‘file’ -&gt; ‘new’.</li><li>Put the file name as ‘FirstCode.pl’ and put ‘Save as type’ as ‘Prolog source’</li><li>Save the file and then prolog editor will be open.</li><li>You can type your knowledge base ( collection of facts ) here.</li><li>After typing the facts and rules you can click on ‘compile’ -&gt; ‘compile buffer’ -&gt; ‘ok’ to compile your knowledge base. ( <strong><em>shortcut</em></strong> → <strong>ctrl + c</strong> , <strong>ctrl + b</strong>)</li><li>Then in query section you can type queries in order to get outputs/results.</li></ol><h3>First Prolog Code</h3><p><strong>First enter the knowledge base in the editor:</strong></p><pre>valuable(gold).<br>male(john).<br>owns(john,gold).<br>mother(mary,john).<br>gives(mary,book,john).</pre><p><strong>In query section:</strong></p><pre>?- valuable(gold).<br>?- valuable(silver).<br>?- mother(jane,john).</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*T8Qtq3f0ZtN2awdoM3AkcQ.png" /><figcaption>output for code</figcaption></figure><h3><strong>Conclusion</strong></h3><p>In this article, we’ve taken a closer look at Prolog’s fundamental data types: atoms, variables, and terms. These elements are the foundation for creating complex Prolog programs and representing and working with data in the language.</p><p>As you explore Prolog further, you’ll find that these data types, combined with rules, facts, and queries, enable you to solve a wide range of problems and represent knowledge in a logical and declarative manner.</p><p>In our next article, we’ll continue our journey into Prolog by diving into more advanced concepts, exploring how to work with lists and recursion, and providing practical examples to solidify your understanding. Stay tuned as we unlock more of the potential of Prolog! 🤖</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a4339d8b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Prolog: Unlocking the Power of Logic Programming]]></title>
            <link>https://medium.com/@himashasilva/a-beginners-guide-to-prolog-unlocking-the-power-of-logic-programming-c9ef3cc7cf47?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ef3cc7cf47</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[logic-programming]]></category>
            <category><![CDATA[swi-prolog]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 19:41:47 GMT</pubDate>
            <atom:updated>2023-10-14T19:41:47.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bsd_aaIb6AwezfEL" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Logical Programming vs. Functional Programming</strong></h3><p>At this point, you might be wondering how Prolog differs from functional programming, a paradigm you might be more familiar with. In functional programming, you specify how to compute a result using functions and transformations, while in Prolog, you specify what you want to achieve through logical rules and relationships.</p><p>The key difference lies in the declarative nature of Prolog, which allows it to express problems in a way that closely resembles human reasoning. Functional programming, on the other hand, emphasizes immutability, higher-order functions, and a focus on “how” to achieve a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ugWA5NEchhBUu9OuyRxF3g.png" /><figcaption>Comparison between Logical Programming and Functional Programming</figcaption></figure><p>Prolog, short for “Programming in Logic,” is a unique and powerful programming language that’s based on the principles of formal logic. In the world of computer science, Prolog stands out for its ability to tackle problems that involve complex rules, knowledge representation, and intricate relationships. Whether you’re a novice or an experienced programmer, this guide will help you grasp the basics of Prolog and set the stage for your journey into the world of logic programming.</p><h3>What is Prolog?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*r-u4WUezGTngXolP.jpg" /></figure><p>At its core, Prolog is a declarative, rule-based language. Unlike imperative languages like Python or C++, which specify “how” a task should be done, Prolog focuses on “what” you want to accomplish. It enables you to define a set of rules and facts, and then it automatically infers answers to questions based on those rules and facts. In other words, Prolog is about logical reasoning and problem-solving.</p><figure><img alt="Example" src="https://cdn-images-1.medium.com/max/218/1*oK-0rCmOtGVPKxpuz_srqA.png" /></figure><p>Such types of relationship problems can be solved by using logic programming(Prolog).</p><h3>The Building Blocks of Prolog</h3><h3>1. Facts and Rules</h3><p>In Prolog, everything revolves around facts and rules. Facts are simple statements that express something as true. For instance, you might define a fact like this:</p><pre>is_human(john).</pre><p>This fact states that John is a human.</p><p>Rules, on the other hand, are more complex and involve logical relationships between facts. Here’s an example:</p><pre>intelligent(X) :- is_human(X).</pre><p>This rule says that if X is a human (as per the is_human fact), then X is intelligent.</p><h3>2. Queries</h3><p>In Prolog, you can pose questions to the system by using queries. For example, you can ask whether John is intelligent:</p><pre>?- intelligent(john).</pre><p>Prolog will evaluate this query and determine if John is intelligent based on the rules and facts you’ve defined.</p><h3>3. Variables</h3><p>Variables in Prolog are placeholders for values. You can use them in queries to find possible values that satisfy your conditions. For example:</p><pre>?- intelligent(X).</pre><p>Prolog will find all values of X that are intelligent based on your defined rules and facts.</p><h3>How Prolog is Used</h3><p>Prolog finds its applications in various domains:</p><ul><li><strong>Expert Systems</strong>: Prolog is often used to build expert systems that can make decisions and provide expert-level knowledge in specific domains.</li><li><strong>Natural Language Processing (NLP)</strong>: Prolog’s declarative nature makes it suitable for parsing and processing natural language. Many NLP applications use Prolog for language understanding.</li><li><strong>Puzzle Solving</strong>: Prolog’s logical reasoning capabilities make it great for solving puzzles, from Sudoku to crossword puzzles.</li><li><strong>Knowledge Representation</strong>: It’s used for representing and reasoning over complex knowledge structures.</li></ul><h3>Getting Started with Prolog</h3><blockquote>To start coding in Prolog, you’ll need a Prolog interpreter or system like SWI-Prolog.You can download SWI Prolog through the below link:</blockquote><blockquote><a href="https://www.swi-prolog.org/download/stable"><strong><em>SWI-Prolog downloads</em></strong></a></blockquote><blockquote>Install it on your system, and you’re ready to go.</blockquote><p>In the next article in this series, we’ll dive deeper into creating your first Prolog program, understanding more complex rules, and exploring how to use Prolog for practical problem-solving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*4HUALdqchTyK8rUhWxwLMg.png" /></figure><p>Stay tuned and get ready to unlock the full potential of Prolog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ef3cc7cf47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DRY Principle: Keeping Your Codebase Clean and Efficient]]></title>
            <link>https://medium.com/@himashasilva/dry-principle-keeping-your-codebase-clean-and-efficient-6b44a258a360?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b44a258a360</guid>
            <category><![CDATA[example]]></category>
            <category><![CDATA[software-engineerin]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[dry-principle]]></category>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 16:22:31 GMT</pubDate>
            <atom:updated>2023-10-05T16:22:31.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9Hweui67MNkOJfcF4V1EA.png" /></figure><p>In the world of software development, one guiding principle stands as a beacon of good coding practice: DRY, which stands for “Don’t Repeat Yourself.” DRY is more than just a catchy acronym; it’s a fundamental principle that can greatly impact the quality, maintainability, and efficiency of your code. In this article, we’ll explore what the DRY principle is, why it’s important, and how to apply it effectively in your projects.</p><h3>What Is the DRY Principle?</h3><p>At its core, the DRY principle is a software development guideline that encourages developers to avoid duplicating code. In other words, when you find yourself writing the same code or logic in multiple places, it’s time to refactor and extract that common code into a reusable component. The goal is to have a single source of truth for any given piece of knowledge or functionality in your codebase.</p><p>The DRY principle is often associated with the idea that “every piece of knowledge or logic should have a single, unambiguous representation.” When you adhere to DRY, you reduce redundancy, minimize the risk of inconsistencies, and make your codebase more maintainable.</p><p>Let’s take a simple example to illustrate the DRY (Don’t Repeat Yourself) principle. Suppose you want to calculate the area of various geometric shapes: rectangles and circles. Here’s a piece of code that doesn’t adhere to the DRY principle:</p><p><strong>Code Without DRY:</strong></p><pre># Calculate area of a rectangle<br>def calculate_rectangle_area(length, width):<br>    return length * width<br><br># Calculate area of a circle<br>def calculate_circle_area(radius):<br>    return 3.14159265359 * radius * radius<br><br># Calculate area of a triangle<br>def calculate_triangle_area(base, height):<br>    return 0.5 * base * height<br><br># Calculate area of a square<br>def calculate_square_area(side):<br>    return side * side<br><br># Calculate area of an ellipse<br>def calculate_ellipse_area(major_axis, minor_axis):<br>    return 3.14159265359 * major_axis * minor_axis</pre><p>In the code above, you have separate functions for calculating the area of different geometric shapes. While this code works, it violates the DRY principle because the mathematical constant 3.14159265359 is repeated in every area calculation.</p><p>Now, let’s refactor the code to adhere to the DRY principle by creating a single function for calculating the area of any geometric shape:</p><p><strong>Code Following DRY:</strong></p><pre>import math<br><br># Calculate area of a geometric shape<br>def calculate_area(shape, *args):<br>    if shape == &#39;rectangle&#39;:<br>        length, width = args<br>        return length * width<br>    elif shape == &#39;circle&#39;:<br>        radius = args[0]<br>        return math.pi * radius * radius<br>    elif shape == &#39;triangle&#39;:<br>        base, height = args<br>        return 0.5 * base * height<br>    elif shape == &#39;square&#39;:<br>        side = args[0]<br>        return side * side<br>    elif shape == &#39;ellipse&#39;:<br>        major_axis, minor_axis = args<br>        return math.pi * major_axis * minor_axis<br>    else:<br>        raise ValueError(&quot;Invalid shape provided&quot;)<br><br># Example usage:<br>rectangle_area = calculate_area(&#39;rectangle&#39;, 5, 8)<br>circle_area = calculate_area(&#39;circle&#39;, 3)<br>triangle_area = calculate_area(&#39;triangle&#39;, 4, 6)<br>square_area = calculate_area(&#39;square&#39;, 5)<br>ellipse_area = calculate_area(&#39;ellipse&#39;, 4, 3)</pre><p>In the refactored code, we have a single calculate_area function that takes the shape as a parameter and a variable number of arguments. This function can calculate the area of different shapes based on the provided parameters. The mathematical constant math.pi is used instead of the repeated value 3.14159265359. This approach adheres to the DRY principle by eliminating code duplication and improving maintainability.</p><h3>Why Is the DRY Principle Important?</h3><h3>1. Maintenance and Debugging</h3><p>When code is duplicated across different parts of your project, any changes or bug fixes become cumbersome. You must remember to update every occurrence of that code, increasing the likelihood of missing something or introducing new issues.</p><h3>2. Readability and Understanding</h3><p>Repeating code can make your codebase harder to read and understand. Developers (including your future self) may struggle to grasp why similar code exists in different places or how changes in one place affect the entire system.</p><h3>3. Efficiency</h3><p>Duplication is inefficient. Repeating code consumes more space, increases the complexity of your project, and can negatively impact performance. By eliminating redundancy, you make your code more efficient.</p><h3>How to Apply the DRY Principle</h3><p>Applying the DRY principle effectively requires a combination of awareness, planning, and good coding practices. Here are some strategies to help you adhere to DRY:</p><h3>1. Identify Duplication</h3><p>Begin by actively looking for code that appears in multiple places. It might be identical or exhibit similar behavior with slight variations. This could involve functions, algorithms, database queries, or even user interface elements.</p><h3>2. Create Reusable Components</h3><p>Once you’ve identified duplicated code, refactor it into reusable components. These can take the form of functions, classes, libraries, or modules, depending on the programming language and context.</p><h3>3. Use Functions and Abstraction</h3><p>Functions are a powerful tool for encapsulating logic. Write functions for common tasks, and call them wherever needed. This way, you centralize the logic and make it easier to maintain and modify.</p><h3>4. Leverage Inheritance and Polymorphism</h3><p>In object-oriented programming, inheritance and polymorphism can help you adhere to DRY. Create base classes with shared functionality and subclass them to customize behavior as needed.</p><h3>5. Database Abstraction and ORM</h3><p>In database-driven applications, consider using Object-Relational Mapping (ORM) frameworks or database abstraction layers to avoid writing repetitive SQL queries.</p><h3>6. Configuration Files and Constants</h3><p>Store configuration settings, constants, and shared values in a centralized location. This prevents duplication of configuration information and ensures consistency.</p><h3>7. Version Control</h3><p>Use version control systems like Git to track changes and easily identify duplicated code. Version control can help you identify and merge similar code fragments.</p><h3>Conclusion</h3><p>The DRY principle is not just a suggestion; it’s a fundamental guideline for writing clean, efficient, and maintainable code. By adhering to DRY, you not only reduce redundancy but also improve the readability and efficiency of your codebase. Your future self and fellow developers will thank you for making the codebase easier to work with and understand.</p><p>Remember that DRY is not about blindly eliminating every instance of code repetition. It’s about finding the right balance between abstraction and simplicity, ensuring that code is reusable without overcomplicating your project. So, the next time you spot duplicated code in your codebase, take a moment to refactor and keep your code DRY — it’s a practice that pays off in the long run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b44a258a360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Annotations in Spring Boot: A Comprehensive Guide]]></title>
            <link>https://medium.com/@himashasilva/demystifying-annotations-in-spring-boot-a-comprehensive-guide-82a7e58479d5?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a7e58479d5</guid>
            <category><![CDATA[popular-annotations]]></category>
            <category><![CDATA[customized-annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 10:39:44 GMT</pubDate>
            <atom:updated>2023-09-20T10:39:44.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*g8XTExpnhaRtLgsLGMy13A.png" /></figure><p><strong>Spring Boot: Revolutionizing Java Application Development</strong></p><p>Spring Boot, an extension of the Spring Framework, has become synonymous with building production-ready Java applications with minimal effort. It provides a comprehensive ecosystem of tools, libraries, and conventions that streamline the development process. Gone are the days of XML configurations and complex setup rituals. Spring Boot has ushered in an era where developers can focus on solving business problems rather than wrestling with infrastructure concerns.</p><blockquote>At the heart of Spring Boot’s magic are annotations — little nuggets of information that instruct the framework on how to manage components, handle HTTP requests, and configure the application context.</blockquote><p>So, fasten your seatbelts as we embark on a journey to demystify annotations in Spring Boot. By the end of this guide, you’ll have a clear understanding of these essential building blocks, empowering you to write cleaner, more maintainable code and accelerate your Java application development.</p><p><strong>What Are Annotations in Spring Boot?</strong></p><blockquote><strong>Spring Annotations</strong> are a form of metadata that provides data about a program which are used to provide supplemental information about a program.</blockquote><p>Annotations are a powerful feature in both Java and, more specifically, in the Spring Boot framework.They serve as hints to the underlying system on how to process and handle specific classes, methods, or fields.</p><p>In Java, annotations are introduced with the @ symbol and placed just above the element they are associated with. Spring Boot leverages Java annotations to make it easier for developers to configure and manage their applications without the need for extensive XML or programmatic configurations.</p><p>One of the primary reasons annotations are essential in Spring Boot projects is their ability to simplify configuration and reduce boilerplate code. Traditional Java applications often required verbose XML or property files to configure various aspects of the application, such as defining beans, specifying routing rules, or setting up database connections. These configurations were not only cumbersome but also prone to errors.</p><p>With annotations, Spring Boot adopts a more “code over configuration” approach. Instead of external configuration files, developers can use annotations directly in their code, right where the application components are defined. This approach not only streamlines the configuration process but also makes the codebase more readable and maintainable. Annotations allow developers to express their intentions concisely, which the framework can then interpret to set up the application as desired.</p><p><strong>Popular Annotations in Spring Boot</strong></p><ol><li><strong>@SpringBootApplication</strong>:</li></ol><p>This annotation is often placed on the main class of a Spring Boot application. It combines three other annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. It signifies that this class is the entry point of the Spring Boot application.</p><p>By using @SpringBootApplication, you enable Spring Boot&#39;s auto-configuration features, which automatically configure various beans and settings based on your project&#39;s dependencies. It also scans for components (like controllers, services, and repositories) in the package where the main class is located and its sub-packages.</p><p><strong>Example:</strong></p><pre>@SpringBootApplication<br>public class MySpringBootApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MySpringBootApplication.class, args);<br>    }<br>}</pre><p><strong>2. @Controller, @RestController, and @RequestMapping:</strong></p><p>These annotations are used to create web controllers in a Spring Boot application.</p><ul><li>@Controller marks a class as a controller and is typically used for traditional MVC applications.</li><li>@RestController is a specialized version of @Controller that&#39;s used for building RESTful APIs. It automatically serializes return values to JSON.</li><li>@RequestMapping is used at the method level to map HTTP requests to specific controller methods.</li></ul><p>These annotations are essential for handling incoming HTTP requests and defining the endpoints of your application.</p><p><strong>Example:</strong></p><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class MyController {<br>    @GetMapping(&quot;/hello&quot;)<br>    public String sayHello() {<br>        return &quot;Hello, World!&quot;;<br>    }<br>}</pre><p><strong>3. @Service:</strong></p><p>The @Service annotation is used to declare a class as a service component in a Spring Boot application. Service components contain the business logic of an application and are typically used for processing data or performing operations.</p><p>By annotating a class with @Service, you allow Spring Boot to discover and manage it as a Spring bean, making it available for dependency injection.</p><p><strong>Example:</strong></p><pre>@Service<br>public class MyService {<br>    public String performSomeAction() {<br>        // Business logic here<br>    }<br>}</pre><p><strong>4. @Repository</strong>:</p><p>The @Repository annotation is used to declare a class as a repository for data access operations. It&#39;s commonly used in conjunction with <a href="https://spring.io/projects/spring-data-jpa">Spring Data JPA</a> to interact with databases.</p><p>By annotating a class with @Repository, you indicate to Spring Boot that this class is responsible for database operations. Spring Boot then provides exceptions translation for database-specific exceptions and performs other necessary configurations.</p><p><strong>Example:</strong></p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    // Data access methods defined here<br>}</pre><p><strong>5. @Autowired</strong>:</p><p>@Autowired is an annotation used for automatic dependency injection, which means that Spring Boot automatically provides the necessary dependencies (beans) to your classes, so you don’t have to create instances manually.When applied to a field, constructor, or setter method, it tells Spring Boot to inject a bean of the corresponding type into the annotated component.</p><p>This annotation simplifies the process of wiring up components, eliminating the need to manually create and configure beans.</p><p><strong>Example:</strong></p><pre>@Service<br>public class MyService {<br>    private final MyRepository repository;<br><br>    @Autowired<br>    public MyService(MyRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p><strong>6. @Value</strong>:</p><p>The @Value annotation in Spring Boot is a versatile tool for injecting values from properties files, environment variables, or other sources into Spring beans. It allows you to externalize configuration and customize your application without modifying code.</p><p><strong>Example:</strong></p><pre>@Service<br>public class MyService {<br>    @Value(&quot;${myapp.api.url}&quot;)<br>    private String apiUrl;<br>}</pre><p><strong>7. @Configuration</strong> and <strong>@Bean</strong>:</p><p>The @Configuration and @Bean annotations in Spring Boot are used together to define custom configurations and create Spring beans explicitly. They allow you to configure and customize your application&#39;s components, often in cases where Spring Boot&#39;s auto-configuration is insufficient or when you need to create beans with specific configurations.</p><p><strong><em>@Configuration Annotation:</em></strong></p><ul><li>The @Configuration annotation is used to indicate that a class contains one or more bean definitions and should be processed by the Spring container to generate Spring beans.</li><li>This annotation is typically applied to a Java class, and it signifies that the class plays a role in configuring the application context.</li></ul><p><strong><em>@Bean Annotation:</em></strong></p><ul><li>The @Bean annotation is used within @Configuration classes to define methods that produce Spring beans. Each method annotated with @Bean is responsible for creating and configuring a bean.</li><li>When Spring Boot’s application context is initialized, it calls these @Bean methods to create the beans, and the resulting objects are managed by the Spring container.</li></ul><p><a href="https://www.tutorialspoint.com/spring/spring_bean_definition.htm">Spring - Bean Definition</a></p><p>Here’s a simple example of how @Configuration and @Bean work together:</p><pre>@Configuration<br>public class MyConfiguration {<br><br>    @Bean<br>    public DataSource dataSource() {<br>        // Create and configure a data source bean<br>        DataSource dataSource = new DataSource();<br>        dataSource.setUrl(&quot;jdbc:mysql://localhost/mydb&quot;);<br>        dataSource.setUsername(&quot;username&quot;);<br>        dataSource.setPassword(&quot;password&quot;);<br>        return dataSource;<br>    }<br><br>    @Bean<br>    public MyService myService() {<br>        // Create a MyService bean with a dependency on the dataSource bean<br>        return new MyService(dataSource());<br>    }<br>}</pre><p>In this example, the MyConfiguration class is annotated with @Configuration, indicating that it contains bean definitions. Two @Bean methods are defined to create and configure beans for DataSource and MyService. The myService method injects the dataSource bean as a dependency.</p><p><strong>How to create Custom Annotations in Spring Boot?</strong></p><p>In Spring Boot, you can create your own custom annotations to add specific behaviors or metadata to your classes or methods.</p><ol><li><strong>Define the Annotation:</strong> To create a custom annotation, you start by defining an annotation interface. This interface will serve as the blueprint for your custom annotation. Annotations in Java usually have no methods (marker annotations) or may have some properties (meta-annotations).</li><li><strong>Add Metadata:</strong> If your custom annotation needs to hold additional information, you can define elements within the annotation interface. These elements can have default values and can be of various data types.</li></ol><p>Let’s say you want to create a custom annotation called @AuditLog to mark methods that should be logged for auditing purposes. Here&#39;s how you can create it:</p><pre>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>@Target(ElementType.METHOD) // Specifies where the annotation can be used (in this case, on methods)<br>@Retention(RetentionPolicy.RUNTIME) // Specifies when the annotation should be available (during runtime)<br>public @interface AuditLog {<br>    String value() default &quot;&quot;; // An optional attribute for additional information<br>}</pre><ul><li>In this example, @AuditLog is a custom annotation that can be applied to methods. It can also include an optional attribute called value.</li><li>Once you’ve created the custom annotation, you can use it in your Spring Boot application. For instance, you can apply it to a method that should be audited:</li></ul><pre>@Service<br>public class MyService {<br><br>    @AuditLog(&quot;User login&quot;)<br>    public void performLogin(String username) {<br>        // Logic for user login<br>    }<br><br>    public void someOtherMethod() {<br>        // This method is not audited<br>    }<br>}</pre><ul><li>In this example, the @AuditLog annotation is applied to the performLogin method, indicating that this method should be logged for auditing purposes. The optional attribute value can be used to provide additional information about the audit log.</li><li>You can then use reflection or other mechanisms to discover and process methods annotated with @AuditLog to implement the desired auditing functionality in your application.</li></ul><p><strong>Conclusion:</strong></p><p>In short, Spring Boot annotations are like special codes that make writing Java applications easier and cleaner. They help us set up things quickly, avoid repeating the same code, and make our programs more organized. Whether it’s using well-known annotations like @Autowired and @Value or creating our own custom codes, these tools are like magic ingredients that make our code better. As you keep learning about Spring Boot, don&#39;t forget to explore more of these special codes and resources; they&#39;ll make your coding journey more enjoyable and your applications more awesome. Understanding and using these annotations will help you build cool software with less hassle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a7e58479d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SOLID Principles: Best Practices in Software Engineering]]></title>
            <link>https://medium.com/@himashasilva/mastering-solid-principles-best-practices-in-software-engineering-82925f4551b5?source=rss-1da9afa4c9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/82925f4551b5</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[with-examples]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Himasha Silva]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 09:00:18 GMT</pubDate>
            <atom:updated>2023-09-12T09:00:18.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="SOLID Principles" src="https://cdn-images-1.medium.com/max/1024/1*lY4A8KDJx4q1lDdknkxN8w.jpeg" /><figcaption>SOLID Principles</figcaption></figure><h3><strong>Introduction</strong></h3><p>Maintaining clean, scalable, and maintainable code is essential in the constantly changing world of software engineering. Robert C. Martin’s SOLID principles provide a set of instructions for doing just that. We’ll delve further into these concepts in this article and examine how you may use them as your best practices for software development.</p><h4><strong>What are SOLID Design Principles?</strong></h4><ul><li>Single Responsibility Principle (SRP)</li><li>Open-Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP)</li><li>Dependency Inversion Principle (DIP)</li></ul><h3><strong>Single Responsibility Principle (SRP):</strong></h3><p>The single responsibility principle indicates that a class, module, or function should have only one reason to change, meaning it should do one thing.</p><p>A “reason to change” in the context of SRP refers to any conceivable modification or alteration that a class might undergo during its lifetime. The reasons for this can be divided into several software system-related concerns or responsibilities. For instance, a class that manages both user authentication and database interactions has two independent reasons to change: if the database schema changes or the authentication mechanism needs to be updated.</p><p>When a class accumulates multiple reasons to change, it becomes a tangled web of responsibilities, blurring the lines between different concerns. This is akin to juggling multiple balls at once, and as any experienced juggler will tell you, the more balls you have in the air, the higher the chance of dropping one.</p><p>Let’s look into an example in java to get more clear idea about this principle.</p><p>Consider a scenario in which the Customer class is in charge of both email notifications and the storage of customer data. Due to multiple reasons for change — one for email-related modifications and another for customer-related changes — this class violates SRP.</p><pre>public class Customer {<br>    private String name;<br>    private String email;<br><br>    // Constructor, getters, and setters for name and email<br><br>    public void saveCustomer() {<br>        // Logic to save customer information to a database<br>        System.out.println(&quot;Customer information saved.&quot;);<br>    }<br><br>    public void sendEmail() {<br>        // Logic to send a notification email to the customer<br>        System.out.println(&quot;Notification email sent to &quot; + email);<br>    }<br>}<br><br></pre><p>Now, let’s refactor it following SRP:</p><pre>// Class responsible for storing customer information<br>public class Customer {<br>    private String name;<br>    private String email;<br><br>    // Constructor, getters, and setters for name and email<br><br>    public void saveCustomer() {<br>        // Logic to save customer information to a database<br>        System.out.println(&quot;Customer information saved.&quot;);<br>    }<br>}<br><br>// Class responsible for sending email notifications<br>public class EmailService {<br>    public void sendEmail(String emailAddress, String message) {<br>        // Logic to send an email notification<br>        System.out.println(&quot;Notification email sent to &quot; + emailAddress);<br>    }<br>}</pre><p>In this refactored code:</p><p>· The Customer class is now responsible solely for storing customer information. It has no knowledge of email sending logic.</p><p>· The EmailService class is introduced to handle email-related responsibilities. It encapsulates the logic for sending email notifications.</p><p>This refactoring adheres to the Single Responsibility Principle. The Customer class has one reason to change (customer information-related changes), and the EmailService class has one reason to change (email-related changes). This separation makes the code more maintainable, easier to understand, and allows each class to evolve independently as per their specific responsibilities.</p><h3><strong>The Open-Closed Principle (OCP)</strong></h3><p>The open-closed principle states that classes, modules, and functions should be open for extension but closed for modification. It is a fundamental guideline that plays a pivotal role in building robust and maintainable systems.</p><p><em>Open for Extension :</em></p><p>A software entity should be open for extension, allowing new or existing functionality to be added or extended without altering its source code. This promotes flexibility and adaptability in software by allowing users to build upon or customize a component’s behavior.</p><p><em>Closed for modification :</em></p><p>“Closed for modification” refers to a software entity’s source code remaining unchanged after stability testing, ensuring reliability and unaffected by system changes, and preventing new features or bug fixes, after thorough validation and testing.</p><p><strong>The Role of OCP in Building Robust Systems</strong></p><p>· Reduced Risk of Bugs</p><p>· Enhanced Scalability</p><p>· Encapsulation</p><p>· Code Reusability</p><p>· Easier collaboration</p><p>Now, let’s see an example of Java code that breaks this principle and what is the accepted way to code.</p><pre>public class Shape {<br>    protected String type;<br><br>    public Shape(String type) {<br>        this.type = type;<br>    }<br><br>    public String getType() {<br>        return type;<br>    }<br><br>    public double calculateArea() {<br>        return 0.0; // Default area for unknown shapes<br>    }<br>}<br><br>public class AreaCalculator {<br>    public double calculateArea(Shape shape) {<br>        if (shape.getType().equalsIgnoreCase(&quot;circle&quot;)) {<br>            // Calculate circle area<br>            return Math.PI * Math.pow(5, 2); // Assuming radius is 5<br>        } else if (shape.getType().equalsIgnoreCase(&quot;rectangle&quot;)) {<br>            // Calculate rectangle area<br>            return 10 * 20; // Assuming width is 10 and height is 20<br>        } else {<br>            // Default area calculation<br>            return shape.calculateArea();<br>        }<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Shape circle = new Shape(&quot;circle&quot;);<br>        Shape rectangle = new Shape(&quot;rectangle&quot;);<br><br>        AreaCalculator calculator = new AreaCalculator();<br><br>        double circleArea = calculator.calculateArea(circle);<br>        double rectangleArea = calculator.calculateArea(rectangle);<br><br>        System.out.println(&quot;Circle Area: &quot; + circleArea);<br>        System.out.println(&quot;Rectangle Area: &quot; + rectangleArea);<br>    }<br>}</pre><p>Fixing the Code to follow the Open/Closed Principle:</p><pre>abstract class Shape {<br>    public abstract double calculateArea();<br>}<br><br>class Circle extends Shape {<br>    private double radius;<br><br>    public Circle(double radius) {<br>        this.radius = radius;<br>    }<br><br>    @Override<br>    public double calculateArea() {<br>        return Math.PI * Math.pow(radius, 2);<br>    }<br>}<br><br>class Rectangle extends Shape {<br>    private double width;<br>    private double height;<br><br>    public Rectangle(double width, double height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    @Override<br>    public double calculateArea() {<br>        return width * height;<br>    }<br>}<br><br>class AreaCalculator {<br>    public double calculateArea(Shape shape) {<br>        return shape.calculateArea();<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Shape circle = new Circle(5);<br>        Shape rectangle = new Rectangle(10, 20);<br><br>        AreaCalculator calculator = new AreaCalculator();<br><br>        double circleArea = calculator.calculateArea(circle);<br>        double rectangleArea = calculator.calculateArea(rectangle);<br><br>        System.out.println(&quot;Circle Area: &quot; + circleArea);<br>        System.out.println(&quot;Rectangle Area: &quot; + rectangleArea);<br>    }<br>}</pre><p>The Circle and Rectangle classes, which extend the Shape class, have been separated out in the refactored code. The AreaCalculator class will stay closed to modification and open to extension so that new shapes can be added without changing its code. This method allows to add new shapes by developing new classes that extend Shape. The Open/Closed Principle is followed in this.</p><h3>The Liskov Substitution Principle (LSP)</h3><p>One of the most important rules for object-oriented programming (OOP) is the Liskov substitution principle. It was introduced by the computer scientist Barbara Liskov in 1987.</p><p>The principle states that child classes or subclasses must be substitutable for their parent classes or super classes. Simply said, the child class must be capable of taking the place of the parent class. The benefit of this is that it informs you of what to expect from your code.</p><h4><strong>Key Principles of LSP</strong></h4><p>1. <strong>Substitutability:</strong> The core idea behind LSP is that an object of a derived class should be able to replace an object of the base class without affecting the correctness of the program. In other words, if a class Derived is a subclass of Base, you should be able to use an instance of Derived wherever an instance of Base is expected.</p><p>2. <strong>Consistency of Behavior:</strong> LSP ensures that the derived class (subclass) maintains the same behavior as the base class (superclass) in terms of fulfilling the contract set by the base class. This includes adhering to the same method signatures, invariants, and expected behavior.</p><p>3. <strong>Polymorphism:</strong> LSP is like a superpower for object-oriented programming. It lets you write flexible code that can handle not just the original class but also any new versions of it. This flexibility is called “polymorphism,” and it’s super useful.</p><p>4. <strong>Code Reuse:</strong> When you follow LSP, you can add new features or variations of a class without breaking existing code that relies on the original class. It’s like building with Lego bricks; you can add new pieces without rebuilding everything from scratch. This makes your code more reusable and easier to manage.</p><p>Let’s consider an example:</p><p>Imagine a scenario where we have a Vehicle class as the base class and a Bicycle class as a derived class. Bicycles are a type of vehicle, but they don&#39;t have engines, which makes them a special case. Let&#39;s look at the principle-violating code:</p><pre>class Vehicle {<br>    void startEngine() {<br>        System.out.println(&quot;Engine started.&quot;);<br>    }<br>}<br><br>class Bicycle extends Vehicle {<br>    // Bicycles do not have engines, but this method is inherited.<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Vehicle bicycle = new Bicycle();<br>        bicycle.startEngine(); // This will print &quot;Engine started,&quot; which is incorrect for a bicycle.<br>    }<br>}</pre><p>In this code, the Vehicle base class has a startEngine() method, and the Bicycle derived class inherits this method. However, bicycles do not have engines, so this violates the Liskov Substitution Principle.</p><p>Here’s the accepted way that follows the Liskoov Substitution Principle:</p><pre>interface Vehicle {<br>    void move();<br>}<br><br>class Car implements Vehicle {<br>    @Override<br>    public void move() {<br>        System.out.println(&quot;Car is moving with an engine.&quot;);<br>    }<br>}<br><br>class Bicycle implements Vehicle {<br>    @Override<br>    public void move() {<br>        System.out.println(&quot;Bicycle is moving without an engine.&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Vehicle car = new Car();<br>        Vehicle bicycle = new Bicycle();<br><br>        car.move(); // Outputs: Car is moving with an engine.<br>        bicycle.move(); // Outputs: Bicycle is moving without an engine.<br>    }<br>}</pre><p>In this corrected code:</p><p>· We have a Vehicle interface that defines a move() method, which is a more appropriate behavior for vehicles to have.</p><p>· Both the Car and Bicycle classes implement the Vehicle interface and provide their own implementations of the move() method.</p><p>· In the Main class, we create instances of both Car and Bicycle and call the move() method on each, which results in behavior that accurately reflects the characteristics of each vehicle.</p><h3><strong>Interface Segregation Principle(ISP):</strong></h3><p>The Interface Segregation Principle (ISP) primarily concerned with designing interfaces that are tailored to the specific needs of clients, rather than creating large, general-purpose interfaces. This principle states that high-level modules should not depend on low-level modules. Instead, they should both depend on abstractions. Additionally, abstractions should not depend on details, but details should depend on abstractions.</p><p>In simple terms, this suggests that you should develop code that depends on more generic abstractions that may be implemented in various ways rather than code that depends on specific details of how lower-level code operates.</p><p>This eliminates the need to alter the higher-level code, making it simpler to change the lower-level code. Also it emphasizes the importance of reducing coupling between components, promoting modularity, and preventing clients from depending on interfaces they don’t use.</p><p>Let’s look into an example how to implement a java code adhering to this principle:</p><p>Imagine we have a Worker interface that represents workers in a company. This interface has two methods: work() and takeBreak(). However, not all workers, such as managers, need to implement the takeBreak() method. Violating ISP, we have a single, large interface for all workers:</p><pre>// Violated Code<br>interface Worker {<br>    void work();<br>    void takeBreak();<br>}<br><br>class Engineer implements Worker {<br>    public void work() {<br>        System.out.println(&quot;Engineer is working.&quot;);<br>    }<br><br>    public void takeBreak() {<br>        System.out.println(&quot;Engineer is taking a break.&quot;);<br>    }<br>}<br><br>class Manager implements Worker {<br>    public void work() {<br>        System.out.println(&quot;Manager is working.&quot;);<br>    }<br><br>    public void takeBreak() {<br>        System.out.println(&quot;Manager is taking a break.&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Worker engineer = new Engineer();<br>        Worker manager = new Manager();<br><br>        engineer.work();<br>        engineer.takeBreak(); // Engineer takes a break, but this is not relevant.<br><br>        manager.work();<br>        manager.takeBreak(); // Manager takes a break, which is relevant.<br>    }<br>}</pre><p>In this code, both Engineer and Manager classes implement the Worker interface, even though the takeBreak() method doesn&#39;t apply to all workers. This violates the ISP by forcing all workers to implement methods they might not need.</p><p>Corrected Code (Following ISP):</p><pre>// Corrected Code<br>interface Worker {<br>    void work();<br>}<br><br>interface BreakTaker {<br>    void takeBreak();<br>}<br><br>class Engineer implements Worker {<br>    public void work() {<br>        System.out.println(&quot;Engineer is working.&quot;);<br>    }<br>}<br><br>class Manager implements Worker, BreakTaker {<br>    public void work() {<br>        System.out.println(&quot;Manager is working.&quot;);<br>    }<br><br>    public void takeBreak() {<br>        System.out.println(&quot;Manager is taking a break.&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Worker engineer = new Engineer();<br>        BreakTaker manager = new Manager();<br><br>        engineer.work();<br><br>        // Manager can take a break because the BreakTaker interface is separate.<br>        manager.work();<br>        manager.takeBreak();<br>    }<br>}</pre><p>In this corrected code:</p><p>· We have separate interfaces Worker and BreakTaker to represent workers&#39; different responsibilities.</p><p>· The Engineer class implements the Worker interface, focusing on the work() method.</p><p>· The Manager class implements both the Worker and BreakTaker interfaces, as managers can perform both tasks.</p><h3>The Dependency Inversion Principle (DIP)</h3><p>The principle states that high-level modules should not depend on low-level modules. Instead, they should both depend on abstractions. Additionally, abstractions should not depend on details, but details should depend on abstractions.</p><p>So, this principle emphasizes the importance of high-level modules (e.g., classes or components) depending on abstractions (e.g., interfaces or abstract classes) rather than concrete implementations. This principle promotes flexibility, maintainability, and ease of change in software systems.</p><p>Imagine we have a LightBulb class that represents a light bulb, and a LightSwitch class that controls the light bulb. In this code, the LightSwitch class directly depends on the concrete LightBulb class:</p><pre>// Violated Code<br>class LightBulb {<br>    public void turnOn() {<br>        System.out.println(&quot;Light bulb is on.&quot;);<br>    }<br><br>    public void turnOff() {<br>        System.out.println(&quot;Light bulb is off.&quot;);<br>    }<br>}<br><br>class LightSwitch {<br>    private LightBulb bulb;<br><br>    public LightSwitch() {<br>        this.bulb = new LightBulb(); // Violation: Direct dependency on a concrete class.<br>    }<br><br>    public void operate() {<br>        bulb.turnOn(); // Turn on the light bulb.<br>        bulb.turnOff(); // Turn off the light bulb.<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        LightSwitch lightSwitch = new LightSwitch();<br>        lightSwitch.operate();<br>    }<br>}</pre><p>In this code, the LightSwitch class directly creates an instance of LightBulb, violating the Dependency Inversion Principle because it depends on a concrete implementation.</p><p>Corrected code:</p><pre>// Corrected Code<br>interface SwitchableDevice {<br>    void turnOn();<br>    void turnOff();<br>}<br><br>class LightBulb implements SwitchableDevice {<br>    public void turnOn() {<br>        System.out.println(&quot;Light bulb is on.&quot;);<br>    }<br><br>    public void turnOff() {<br>        System.out.println(&quot;Light bulb is off.&quot;);<br>    }<br>}<br><br>class LightSwitch {<br>    private SwitchableDevice device;<br><br>    public LightSwitch(SwitchableDevice device) {<br>        this.device = device;<br>    }<br><br>    public void operate() {<br>        device.turnOn();<br>        device.turnOff();<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        SwitchableDevice bulb = new LightBulb();<br>        LightSwitch lightSwitch = new LightSwitch(bulb);<br>        lightSwitch.operate();<br>    }<br>}</pre><p>In this corrected code:</p><p>· We define an interface SwitchableDevice that represents the common behavior for devices that can be turned on and off.</p><p>· The LightBulb class implements the SwitchableDevice interface, providing the specific behavior for a light bulb.</p><p>· The LightSwitch class depends on the SwitchableDevice interface rather than the concrete LightBulb class. It accepts a SwitchableDevice instance through its constructor, allowing it to work with various devices that adhere to the interface.</p><p>This corrected code follows the Dependency Inversion Principle by relying on abstractions (interfaces) and decoupling the high-level LightSwitch class from low-level details (concrete implementations). It promotes flexibility and maintainability in the system.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, the SOLID principles offer a set of invaluable guidelines for software design, emphasizing clean, modular, and maintainable code. By adhering to these principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — developers can build more robust, extensible, and adaptable software systems. These principles promote clarity, reduce coupling, encourage abstraction, and enhance code reusability. The result is software that is easier to understand, modify, and extend over time. Embracing SOLID principles is an ongoing commitment to excellence in software craftsmanship, leading to more reliable and sustainable codebases.</p><p>Now, let’s see an example of Java code that breaks this principle and what is the accepted way to code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82925f4551b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>