<?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 Pavitra Gupta on Medium]]></title>
        <description><![CDATA[Stories by Pavitra Gupta on Medium]]></description>
        <link>https://medium.com/@guptapavitra?source=rss-2fbebb32f4fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G_0YH5-iYyMbJHHL6ePoeA.jpeg</url>
            <title>Stories by Pavitra Gupta on Medium</title>
            <link>https://medium.com/@guptapavitra?source=rss-2fbebb32f4fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:46:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guptapavitra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Watermarking and Late Data in Data Streaming]]></title>
            <link>https://medium.com/@guptapavitra/understanding-watermarking-and-late-data-in-data-streaming-2b2e67bded36?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2e67bded36</guid>
            <category><![CDATA[streaming-analytics]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 17:57:10 GMT</pubDate>
            <atom:updated>2024-03-04T17:57:26.838Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’re navigating the complexities of streaming use cases, concepts like windowing, watermarking, and late data are crucial. This article demystifies these essential elements of streaming data pipelines, offering a foundation for understanding how to manage real-time data effectively. Whether you’re new to the subject or refining your expertise, we’ll explore the necessity of windowing, the importance of event time over processing time, and concepts of watermarking and late data in data streaming systems.</p><h3>Concept of Windowing</h3><p>Imagine you have a website that is accessed by millions of users every day. From this website, you’re collecting a continuous stream of event data, such as page views, clicks, form submissions, and so on. Your aim is to constantly monitor <em>number of page views by logged-in vs not-logged-in users</em> in order to make some data-driven decisions.</p><p>Because streaming data is infinite and is never supposed to end, you can’t wait for all the data to come in before you do the calculations. This is where the concept of windowing becomes invaluable. Windowing is when you divide time into manageable segments or “windows.”</p><p>Let’s say, we decide to make windows of 2 minutes. This means that every 2 minutes, we will group the number of pageviews in two separate segments — logged-in and not-logged-in users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hl_shwmyTl7ldQWnIfz75w.png" /><figcaption>Graphical representation of page-views as streaming data</figcaption></figure><h3>Concept of Event Time and Why Event Time is Sometimes Considered Over Processing Time</h3><p>What you see marked in yellow and orange in the image represents the processing time of these events. Processing time is the moment data is observed and processed by the system, irrespective of when the actual event occurred. However, it’s not true that actual event time and the processing time will always be the same, close or in-order. For various reasons — including network latencies and event generating systems being offline — event times and processing times are usually different than each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1A19kWdIfdxnDfVQ-wtdg.png" /><figcaption>Ideal scenario where event time = processing time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3EjvFPpjCFDJuzzoiLdDrQ.png" /><figcaption>Real world scenario where event time &lt; processing time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTlW9NCLXAM1tZHrcBcRFA.png" /><figcaption>Events coming after their window ended are marked in purple</figcaption></figure><p>In scenarios where only processing time is considered, the system processes data sequentially as it arrives. This methodology simplifies operations as there’s no requirement to account for the original event timestamps. However, this simplicity comes at the cost of potential inaccuracies in scenarios where the timing of the event itself carries significant importance. In numerous applications, the precise moment an event occurs is crucial for accurate analysis and decision-making.</p><p>Processing based on event time ensures that analyses and aggregations reflect real-world occurrences accurately, thus maintaining the integrity of the insights derived from the data.</p><h3>Concept of Watermarking and Late Data</h3><p>Remember we decided to make 2 minute windows for our pipeline? Let’s say, these windows are 11.00–11.02, 11.02–11.04, 11.04–11.06 and so on.</p><p>In our example, let’s say a webpage was opened at 11.03, however due to network latency we received this event at 11.09. Here comes the difficult to understand part of this article. If we were processing the data based on the processing time, it would go to the 11.08-11.10 window. But because we want to process the event based on the event time, we should be putting it in 11.02-11.04 window. Does this mean we have to make the 11.02-11.04 window wait for this long before that window outputs processed data? And did we even know we were going to get an event 6 minutes late like this? Could we be getting some data an hour late too and should we have waited for that data too? We will have to draw a line somewhere after which we start calling data as late and stop waiting for any more of it for that window. This line in fact is called the watermark.</p><p>Let’s understand a watermark in more detail from <a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.DataFrame.withWatermark.html">pyspark’s withWatermark function</a>. This function takes two inputs including the column name which contains the event time and the delay threshold. If we give 4 minutes as the delay threshold, every window will wait for a minimum of 4 minutes after that window’s end before it starts marking data as late data. Getting late data is usually a bad thing for our processing pipeline because it is either discarded or is processed later. But then we are also bound to make the trade-off because after-all how much more can we make our pipeline wait for this upcoming data! Hope this clarifies things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNTdMZDHUav_heYE0iqxgA.png" /><figcaption>Incorrect depiction of watermark (based on the understanding developed till now)</figcaption></figure><p>One more thing before we reach the conclusion of the article! What does it mean by <em>our pipeline will wait for a minimum of 4 minute</em>? Does this mean that our pipeline will also wait for 2 hours and 3 hours before it marks the data as late data? The use of <em>minimum</em> doesn’t make sense here, right? Let me explain.</p><p>Any moment in data processing, watermark is not equal to current processing time + delay threshold. In fact, watermark is equal to maximum event time received so far + delay threshold. This is important because this gives two buffers to our late coming data:</p><ol><li>The actual watermark we configured in our settings.</li><li>The usual delay with which data comes to us — in other words, the usual difference from event time to processing time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X6eNhg4LPSXn_bL2_6Xhg.png" /></figure><h3>Looking ahead</h3><p>We discussed in this article why we need windowing, watermarking and late data. However, what we did not discuss is what we do with the late data. I am going to leave this for some other time.</p><h3>Conclusion</h3><p>In the landscape of data streaming, the efficient management of late data is paramount to ensuring the accuracy and relevance of real-time analytics. By understanding the nuances of windowing, the significance of event time, watermarking and late data, developers and data architects can design systems that not only handle the velocity and volume of streaming data but also maintain the veracity of the insights derived from it. As the digital universe continues to expand, the ability to adeptly navigate the challenges of late data will remain a critical competency in harnessing the full potential of real-time data streaming technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2e67bded36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle — Intro, Example, and Why it is more difficult than you think]]></title>
            <link>https://medium.com/@guptapavitra/single-responsibility-principle-intro-example-and-why-it-is-more-difficult-than-you-think-1cd3a4b45877?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd3a4b45877</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 09:41:51 GMT</pubDate>
            <atom:updated>2024-02-05T09:41:51.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Responsibility Principle — Intro, Example, and Why it is more difficult than you think</h3><h4>Introduction</h4><p>In the realm of software design, the Single Responsibility Principle (SRP) stands as a cornerstone, a concept often attributed to Robert C. Martin, popularly known as Uncle Bob. This principle, part of the SOLID principles, is pivotal in guiding developers toward creating maintainable and scalable code.</p><p>But what exactly is SRP? In this post, we will unravel this with a practical example and understand why it is not as easy as we think it is. ;)</p><h4>TL;DR</h4><p>In this article, through a practical example involving two classes — Order and Invoice, we demonstrate how SRP is applied and how it evolves with changing requirements. If you already know the principle in theory and don’t have the time to go through the example in detail, jump to the section <em>What we learn from the example </em>and read ahead.</p><h4>What is Single Responsibility Principle as told by Uncle Bob?</h4><blockquote>The essence of the Single Responsibility Principle lies in the notion that a class should have one, and only one, reason to change.</blockquote><p>This means each class should be assigned a single functionality or responsibility. Yes, it is that simple — but only in theory. Read ahead to understand what I mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CCpQKD27bCTdRZeS" /><figcaption>Many responsibilities? Maybe not a good idea for classes. Photo by <a href="https://unsplash.com/@pf91_photography?utm_source=medium&amp;utm_medium=referral">Patrick</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>Example</h3><h4>Base Setup: Order class</h4><p>To clearly understand the principle, we will construct a base setup and then will add more code to it as new requirements come in.</p><p>Let’s start with a class called Order — representing a customer&#39;s order, encapsulating details relevant to a purchase. The parameters included here provide a snapshot of what an order might comprise.</p><pre>class Order {<br>    private int orderId;<br>    private String customerName;<br>    private double orderTotal;<br>    private Date orderDate;<br><br>    // Constructor, getters and setters for these fields<br>    public Order(int orderId, String customerName, double orderTotal, Date orderDate) {<br>        this.orderId = orderId;<br>        this.customerName = customerName;<br>        this.orderTotal = orderTotal;<br>        this.orderDate = orderDate;<br>    }<br><br>    // Getters and setters...<br>}</pre><h4>Requirement change 1: Print the order</h4><p>A new requirement comes that we need to print the Order objects to a printer. Let’s create a function to print the respective order details.</p><pre>class Order {<br>    // Existing fields and constructor<br><br>    public void printOrderDetails() {<br>        String printableDetails = &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Customer Name: &quot; + customerName + &quot;\n&quot; +<br>               &quot;Order Total: $&quot; + orderTotal + &quot;\n&quot; +<br>               &quot;Order Date: &quot; + orderDate.toString();<br><br>        System.out.println(printableDetails);<br><br>        String defaultPrinter = <br>          PrintServiceLookup.lookupDefaultPrintService().getName();<br><br>        InputStream is = new ByteArrayInputStream(printableDetails.getBytes());<br><br>        PrintService service = PrintServiceLookup.lookupDefaultPrintService();<br><br>        try {<br>            DocPrintJob job = service.createPrintJob();<br>            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;<br>            Doc doc = new SimpleDoc(is, flavor, null);<br>            job.print(doc, null);<br>        } catch (PrintException e) {<br>            e.printStackTrace();<br>        } finally {<br>            try {<br>                is.close();<br>            } catch (IOException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br><br>    // Getters and setters...<br>}</pre><p>This looks good. We have an Order class, which has the required attributes, constructor, getters and setters and a function to print its objects to a printer. From a Single Responsibility point of view, our class looks good because it deals with things related to orders.</p><h4>Requirement change 2: Add invoices. Create PDFs of orders and invoices</h4><p>Let’s say our manager comes to us with some added functionality:</p><ol><li>Along with orders, we will be dealing with the invoices as well.</li><li>We need to print invoices the same way we are printing the orders.</li><li>We also need to create PDFs in the same format as our previous printouts for both Orders and Invoices.</li></ol><p>Do these requirements seem realistic? Let’s try to add these to our code. Here are our new update classes.</p><pre>class Order {<br>    // Existing fields and constructor<br><br>    public void printOrderDetails() {<br>        String printableDetails = &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Customer Name: &quot; + customerName + &quot;\n&quot; +<br>               &quot;Order Total: $&quot; + orderTotal + &quot;\n&quot; +<br>               &quot;Order Date: &quot; + orderDate.toString();<br><br>        System.out.println(printableDetails);<br><br>        String defaultPrinter = <br>          PrintServiceLookup.lookupDefaultPrintService().getName();<br><br>        InputStream is = new ByteArrayInputStream(printableDetails.getBytes());<br><br>        PrintService service = PrintServiceLookup.lookupDefaultPrintService();<br><br>        try {<br>            DocPrintJob job = service.createPrintJob();<br>            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;<br>            Doc doc = new SimpleDoc(is, flavor, null);<br>            job.print(doc, null);<br>        } catch (PrintException e) {<br>            e.printStackTrace();<br>        } finally {<br>            try {<br>                is.close();<br>            } catch (IOException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br><br>    public void createOrderPDF() {<br>        String printableDetails = &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Customer Name: &quot; + customerName + &quot;\n&quot; +<br>               &quot;Order Total: $&quot; + orderTotal + &quot;\n&quot; +<br>               &quot;Order Date: &quot; + orderDate.toString();<br><br>        try (PDDocument document = new PDDocument()) {<br>            PDPage page = new PDPage();<br>            document.addPage(page);<br><br>            PDPageContentStream contentStream = new PDPageContentStream(document, page);<br><br>            contentStream.setFont(PDType1Font.HELVETICA, 12);<br>            contentStream.beginText();<br>            contentStream.newLineAtOffset(100, 700);<br>            contentStream.showText(printableDetails);<br>            contentStream.endText();<br>            contentStream.close();<br><br>            document.save(&quot;order.pdf&quot;);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br><br>    // Getters and setters...<br>}</pre><pre>class Invoice {<br>    private int invoiceId;<br>    private int orderId;<br>    private double invoiceAmount;<br>    private Date invoiceDate;<br><br>    // Constructor, getters and setters for these fields<br>    public Invoice(int invoiceId, int orderId, double invoiceAmount, Date invoiceDate) {<br>        this.invoiceId = invoiceId;<br>        this.orderId = orderId;<br>        this.invoiceAmount = invoiceAmount;<br>        this.invoiceDate = invoiceDate;<br>    }<br><br>    public String printInvoiceDetails() {<br>        String printableDetails = &quot;Invoice ID: &quot; + invoiceId + &quot;\n&quot; +<br>               &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Invoice Amount: $&quot; + invoiceAmount + &quot;\n&quot; +<br>               &quot;Invoice Date: &quot; + invoiceDate.toString();<br><br>        System.out.println(printableDetails);<br><br>        String defaultPrinter = <br>          PrintServiceLookup.lookupDefaultPrintService().getName();<br><br>        InputStream is = new ByteArrayInputStream(printableDetails.getBytes());<br><br>        PrintService service = PrintServiceLookup.lookupDefaultPrintService();<br><br>        try {<br>            DocPrintJob job = service.createPrintJob();<br>            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;<br>            Doc doc = new SimpleDoc(is, flavor, null);<br>            job.print(doc, null);<br>        } catch (PrintException e) {<br>            e.printStackTrace();<br>        } finally {<br>            try {<br>                is.close();<br>            } catch (IOException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br><br>    public void createInvoicePDF() {<br>        String printableDetails = &quot;Invoice ID: &quot; + invoiceId + &quot;\n&quot; +<br>               &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Invoice Amount: $&quot; + invoiceAmount + &quot;\n&quot; +<br>               &quot;Invoice Date: &quot; + invoiceDate.toString();<br><br>        try (PDDocument document = new PDDocument()) {<br>            PDPage page = new PDPage();<br>            document.addPage(page);<br><br>            PDPageContentStream contentStream = new PDPageContentStream(document, page);<br><br>            contentStream.setFont(PDType1Font.HELVETICA, 12);<br>            contentStream.beginText();<br>            contentStream.newLineAtOffset(100, 700);<br>            contentStream.showText(printableDetails);<br>            contentStream.endText();<br>            contentStream.close();<br><br>            document.save(&quot;order.pdf&quot;);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br><br>    // Getters and setters...<br>}</pre><p>What did we do?</p><ul><li>We added an Invoice class along with functions printInvoiceDetails and createInvoicePDF.</li><li>We added a function in Order class called createOrderPDF.</li></ul><p>This does the job. But — and this is where it starts to become really interesting — we start getting into problems. Or if I say it in a different way, some problems now start becoming more visible than before.</p><ul><li><strong>Problem 1: </strong>Both classes are becoming too big. And it now seems that the classes have responsibilities way beyond just managing Orders and Invoices. Most of the code in each class is for printing to the printer and creating PDFs.</li><li><strong>Problem 2: </strong>Both classes have common code — and in fact most of it is common. This means that every time we have to make a change to how we print or create a PDF, we have to make the same change in two places.</li></ul><p><strong>Solution: </strong>Redefine the responsibilities.</p><p>Well, now that these issues are arising, a good idea is to rethink the responsibilities. How about following:</p><ul><li>An Order class with its parameters and a function getOrderDetails which returns the order details in a self-formatted manner.</li><li>An Invoice class with its parameters and a function getInvoiceDetails which returns the invoice details in a self-formatted manner.</li><li>A PDFCreator class which has a create method to create a PDF with the provided content.</li><li>A SimplePrinter class which has a print method to print the provided content on printer.</li></ul><p>Let’s see how this will look in the code.</p><pre>class Order {<br>    // Existing fields and constructor<br><br>    public String getOrderDetails() {<br>        return &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Customer Name: &quot; + customerName + &quot;\n&quot; +<br>               &quot;Order Total: $&quot; + orderTotal + &quot;\n&quot; +<br>               &quot;Order Date: &quot; + orderDate.toString();<br>    }<br>    <br>    // Getters and setters...<br>}</pre><pre>class Invoice {<br>    // Existing fields and constructor<br><br>    public String getInvoiceDetails() {<br>        return &quot;Invoice ID: &quot; + invoiceId + &quot;\n&quot; +<br>               &quot;Order ID: &quot; + orderId + &quot;\n&quot; +<br>               &quot;Invoice Amount: $&quot; + invoiceAmount + &quot;\n&quot; +<br>               &quot;Invoice Date: &quot; + invoiceDate.toString();<br>    }<br><br>    // Getters and setters...<br>}</pre><pre>class PDFCreator {<br>    public void create(String content, String fileName) {<br>        try (PDDocument document = new PDDocument()) {<br>            PDPage page = new PDPage();<br>            document.addPage(page);<br><br>            PDPageContentStream contentStream = new PDPageContentStream(document, page);<br><br>            contentStream.setFont(PDType1Font.HELVETICA, 12);<br>            contentStream.beginText();<br>            contentStream.newLineAtOffset(100, 700);<br>            contentStream.showText(content);<br>            contentStream.endText();<br>            contentStream.close();<br><br>            document.save(fileName);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><pre>class SimplePrinter {<br>    public void print(String content) {<br>        String defaultPrinter = <br>          PrintServiceLookup.lookupDefaultPrintService().getName();<br><br>        InputStream is = new ByteArrayInputStream(content.getBytes());<br><br>        PrintService service = PrintServiceLookup.lookupDefaultPrintService();<br><br>        try {<br>            DocPrintJob job = service.createPrintJob();<br>            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;<br>            Doc doc = new SimpleDoc(is, flavor, null);<br>            job.print(doc, null);<br>        } catch (PrintException e) {<br>            e.printStackTrace();<br>        } finally {<br>            try {<br>                is.close();<br>            } catch (IOException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}</pre><p>Let’s revisit if we solved our problems:</p><ul><li><strong>Problem 1: </strong>Too big classes and increasing responsibilities on each class? Solved. The newer classes are smaller and more readable; and each has its clear responsibility.</li><li><strong>Problem 2: </strong>Common<strong> </strong>code in multiple places? Solved. We have the functions to print and create PDFs only in one place.</li></ul><p><strong>Quick recap:</strong> In our exercise, as the requirements evolved over time, we divided the responsibilities in our code as compared to what we had before and made it more clearer, maintainable and streamlined.</p><h4>What we learn from the example</h4><p>Initially when we started with a smaller set of requirements, we thought of our Order class to have a single responsibility — i.e. management of orders. And to be honest, it was okay. Creating multiple classes for printing orders could have felt a little over-engineered at that time.</p><p>When our requirements changed, keeping the same notion of a single responsibility would have made less and less sense. It was then when we realised that our code was really not having a single responsibility per class. And so, like good software developers, we reconsidered our notion and refactored the code.</p><h3>Why SRP is difficult to put to practice</h3><p>Single Responsibility Principle seems like a straightforward one when we hear about it for the first time or say when we are preparing it for an interview. One class for one responsibility. Simple, right!</p><blockquote>However, things get difficult when we try to put it to practice. For the abstract topic SRP is, it gets difficult to reason what a single responsibility might even mean in our code. Our judgement eventually depends on the context, the domain, the size and evolution of the code, and our individual style and design choices.</blockquote><p>That’s the reason that many a times, we as developers either end up over-simplifying things or over-complicating them.</p><h3>Moving on</h3><p>If you have been in the software industry for some time, you would know that requirements have a habit of constantly changing. Currently in our code, functions getOrderDetails and getInvoiceDetails hardcode the format in which we are printing or creating the PDFs. An additional requirement could be to format the content however we want at runtime before printing or creating a PDF, instead of hardcoding the format. With the knowledge you are equipped with through this article, how would you design your classes to deal with this new requirement? Will you be adding new classes considering it is a new responsibility or in some way by splitting the current responsibilities; or will you be adding the functionality somewhere in the same classes?</p><h3>Conclusion</h3><p>The Single Responsibility Principle is a fundamental concept in software design, essential for creating maintainable and scalable code. It guides developers to isolate functionalities, making each class responsible for a single aspect of the application. While SRP can be challenging to grasp due to its abstract nature and the need for contextual interpretation, mastering it is crucial for any developer aiming to write clean, efficient, and adaptable code. As Uncle Bob emphasizes, understanding and implementing SRP is a key step towards excellence in software engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd3a4b45877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Open/Closed Principle: Your Code’s Best Friend]]></title>
            <link>https://medium.com/@guptapavitra/navigating-the-open-closed-principle-your-codes-best-friend-4faa7bb09b11?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faa7bb09b11</guid>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 14:15:53 GMT</pubDate>
            <atom:updated>2024-02-02T14:15:53.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, we dive deep into the Open/Closed Principle (OCP), a cornerstone concept in object-oriented programming that advocates for software entities such as classes, modules, and functions to be open for extension but closed for modification. This principle might initially appear contradictory; how can something be both open to change and closed at the same time? We’ll unravel this paradox by exploring what it means to be “open for extension” and “closed for modification,” and why this distinction is crucial for creating flexible and maintainable software. Through practical examples, we’ll illustrate common pitfalls in disregarding OCP and demonstrate the right approach to adhere to this principle. We’ll also address frequently asked questions and doubts about OCP, emphasizing its benefits such as enhanced modularity, ease of testing, and reduced risk of bugs. By the end of this exploration, you’ll understand how adhering to the Open/Closed Principle can lead to more scalable, maintainable, and robust software systems, facilitating easier extensions and adaptations to meet future demands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4jQj78Ua6r11Wxm1" /><figcaption>Photo by <a href="https://unsplash.com/@brandi1?utm_source=medium&amp;utm_medium=referral">Brandi Redd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Open/Closed Principle — A deep dive into its definition</h3><p>At its core, OCP is a fundamental principle in object-oriented programming that states:</p><blockquote>Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</blockquote><p>But what does it even mean to be open for extension, but closed for modification? <strong><em>Doesn’t it seem contradictory?</em></strong> Let’s try to understand.</p><h4><strong>What does being open for extension mean?</strong></h4><p>It means that we should be able to add more functionality to the software. Or in other words we should be able to accommodate more requirements.</p><h4>What does being closed for modification mean?</h4><p>It means that we should not be modifying any pre-existing classes, modules or functions.</p><h4>Then how are we expected to add more functionality without modifying the existing classes? 🤔</h4><p>If we follow OCP, we can add new functionality by creating new classes <em>only</em> without modifying any existing one.</p><h4>Is that even possible?</h4><p>Let’s try to see it using some example.</p><h3>Example</h3><h4>The wrong way!</h4><p>Picture this: we’re tasked with creating a payment processing system. Initially, the payments are supposed to be done using credit cards only. So we create the following class.</p><pre>// Low level class<br>public class PaymentProcessor {<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing credit card payment of $&quot; + amount);<br>    }<br>}<br><br>// Usage code (high level class)<br>public class Main {<br>    public static void main(String[] args) {<br>        PaymentProcessor processor = new PaymentProcessor();<br>        processor.processPayment(100);<br>        processor.processPayment(150);<br>    }<br>}</pre><p>The code is neat. But then, the winds change. PayPal payments need to be added, and soon after, maybe even crypto payments. So, you change your code as follows:</p><pre>// Low level class<br>public class PaymentProcessor {<br>    public void processPayment(double amount, String paymentType) {<br>        if (paymentType.equals(&quot;credit_card&quot;)) {<br>            System.out.println(&quot;Processing credit card payment of $&quot; + amount);<br>        } else if (paymentType.equals(&quot;paypal&quot;)) {<br>            System.out.println(&quot;Processing PayPal payment of $&quot; + amount);<br>        } else if (paymentType.equals(&quot;bitcoin&quot;)) {<br>            System.out.println(&quot;Processing Bitcoin payment of $&quot; + amount);<br>        }<br>    }<br>}<br><br>// Usage code (high level class)<br>public class Main {<br>    public static void main(String[] args) {<br>        PaymentProcessor processor = new PaymentProcessor();<br>        processor.processPayment(100, &quot;credit_card&quot;);<br>        processor.processPayment(150, &quot;paypal&quot;);<br>        processor.processPayment(150, &quot;bitcoin&quot;);<br>    }<br>}</pre><p>Because we modified our low level class to accommodate the new requirement, our code <strong><em>didn’t</em></strong> follow the Open/Closed Principle. According to the principle, it is okay to extend the functionality but not at the expense of modifying the existing classes.</p><p>Without OCP, our approach would be to keep adding if-else statements to our existing PaymentProcessor class every time a new payment type is onboarded. It&#39;s like adding more items to an already cluttered room. Before you know it, your code is a labyrinth of conditional statements, and navigating it feels like walking through a maze blindfolded.</p><h4>The right way!</h4><p>But then, if what we have done so far is not correct, what should we do? Let’s try to rewrite the same code in a different way:</p><pre>// new abstraction (interface)<br>public interface PaymentProcessor {<br>    void processPayment(double amount);<br>}<br><br>// low level class 1<br>public class CreditCardPaymentProcessor implements PaymentProcessor {<br>    @Override<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing credit card payment of $&quot; + amount);<br>    }<br>}<br><br>// low level class 2<br>public class PayPalPaymentProcessor implements PaymentProcessor {<br>    @Override<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing PayPal payment of $&quot; + amount);<br>    }<br>}<br><br>// low level class 3<br>public class BitcoinPaymentProcessor implements PaymentProcessor {<br>    @Override<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing Bitcoin payment of $&quot; + amount);<br>    }<br>}<br><br>// Usage code (high level class)<br>public class Main {<br>    public static void main(String[] args) {<br>        PaymentProcessor creditCardProcessor = new CreditCardPaymentProcessor();<br>        creditCardProcessor.processPayment(100);<br><br>        PaymentProcessor payPalProcessor = new PayPalPaymentProcessor();<br>        payPalProcessor.processPayment(150);<br><br>        PaymentProcessor bitcoinProcessor = new BitcoinPaymentProcessor();<br>        bitcoinProcessor.processPayment(150);<br>        <br>        // Adding a new payment method doesn&#39;t require changing existing low<br>        // level classes.<br>        // Just adding a new one that implements the PaymentProcessor interface.<br>    }<br>}</pre><p>Read the above code carefully. Previously available low level class PaymentProcessor has been divided into multiple classes — each representing a specific type of payment. Now, if we want to add a new payment type, we will be creating a new low level class and won’t be making any change to the existing low level classes. And that’s how — my friends — we can achieve the milestone of using the Open/Closed Principle.</p><h4>Frequently asked doubts:</h4><ol><li><strong>Doubt 1:</strong> You might argue that our code in the Main class is still undergoing changes, suggesting it does not adhere to the Open/Closed Principle. And you would be correct. However, there’s an important distinction to consider. The SOLID principles are not intended to apply to driver code (which we’ve identified as usage code above). Instead, they are most applicable to non-driver code — which, in large software systems, constitutes the majority. A practical approach is to increasingly relocate code from the driver class into more low-level classes and modules.</li><li><strong>Doubt 2:</strong> You might argue that our code has become significantly longer than before, and that accomplishing the same task now requires many more lines of code. Indeed, that’s correct. However, we’re not trying to save paper here, and having longer code does not slow down your software (no, it doesn’t). The purpose of the SOLID design principles is to make the code more readable and manageable. If there’s ever a bug in your credit card payments, you’ll face a lesser mess — ultimately enhancing developer productivity and reducing stress.</li><li><strong>Doubt 3:</strong> Let’s suppose there’s a requirement to make payments not only in USD but also in other currencies. This might necessitate extensive changes to the code, to the extent that your existing classes end up being modified. Does this mean our code does not adhere to the Open/Closed Principle? Not necessarily! The OCP, like all SOLID design principles, serves as a guideline to help us write better code, based on our current understanding of the requirements. Our existing implementation indeed follows the Open/Closed Principle for adding new payment methods, as it allows the introduction of new PaymentProcessor implementations for each new payment method without modifying existing classes. However, introducing support for multiple currencies presents a new dimension of flexibility not accounted for in the original design.</li><li><strong>Doubt 4: </strong>If you’ve grasped the concept, you might argue that the considerable effort required to understand and implement it — resulting in so many classes — seems like overkill. Does this mean learning this principle is pointless? Not at all! Although the example has been intentionally simplified to clearly illustrate the concept, unlike in the example, most software projects will not end with just 4–5 classes, nor will most classes contain only 3–4 lines of code. As the size of the codebase increases, managing it becomes increasingly difficult, making it more and more sensible to apply the SOLID principles.</li></ol><h4>Important benefits of OCP</h4><ol><li><strong>Enhanced Modularity:</strong> OCP encourages the segregation of components into well-defined, interchangeable modules with clear interfaces. This modularity facilitates understanding, maintaining, and updating systems.</li><li><strong>Ease of writing test-cases:</strong> Because of increased modularity and isolation, it’s easier to write test cases without worrying about many parts of the system at the same time.</li><li><strong>Ease of Extension:</strong> By adhering to OCP, systems are designed to be extended with new functionality without modifying existing code, making it easier to add features or address new requirements as they arise.</li><li><strong>Reduced Risk of Bugs:</strong> Since existing code remains unchanged when new features are added, the risk of introducing bugs into already-tested and working parts of the system is minimized.</li><li><strong>Improved Maintainability: </strong>Systems designed with OCP in mind tend to be more maintainable, as they avoid the complexity and fragility associated with directly modifying existing code. This leads to easier updates and less technical debt over time.</li><li><strong>Encourages Reusability:</strong> The principle promotes the development of reusable components. Since components are closed for modification, they are designed to be flexible and reusable in different contexts and applications.</li><li><strong>Better Scalability:</strong> OCP-compliant systems are more scalable, as they can grow in functionality through the addition of new modules or extensions without impacting the existing system’s stability or performance.</li><li><strong>Facilitates Parallel Development:</strong> With clearly defined interfaces and separations of concerns, different parts of a system can be developed in parallel by different teams, accelerating development timelines.</li></ol><h3>Conclusion</h3><p>The Open/Closed Principle (OCP) is a cornerstone of sustainable software development, guiding developers to create systems that are easily extendable without modifying existing code. By adhering to OCP, developers can enhance system modularity, facilitate easier testing, and reduce the introduction of bugs when extending functionality. Although implementing OCP might initially seem to increase code volume, the payoff in terms of maintainability, scalability, and developer productivity is immense. Ultimately, OCP helps in building software that can adapt to future demands with minimal disruption, proving its value as an essential practice for long-term software health and evolution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faa7bb09b11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Effective Object Serialization in Java]]></title>
            <link>https://medium.com/@guptapavitra/a-guide-to-effective-object-serialization-in-java-54cda2375db4?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/54cda2375db4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[serialization]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 12:45:48 GMT</pubDate>
            <atom:updated>2023-12-20T12:45:48.855Z</atom:updated>
            <content:encoded><![CDATA[<p>When we write a Java program, any objects we create are stored in the primary memory of the computer. For example, consider this Person class:</p><pre>public class Person {<br>    private String name;<br>    private String address;<br><br>    public Person(String name, String address) {<br>        this.name = name;<br>        this.address = address;<br>    }<br>}</pre><p>Let’s create an object of it:</p><pre>Person person = new Person(&quot;Pavitra&quot;, &quot;Bengaluru, India&quot;);</pre><p>When the program runs, the object person is stored in the primary memory.</p><p>What if we want to persist the state of our Java object on the disk? Or what if we need to send the state of this object to another computer over a network? In both cases, we must serialize the object, which involves converting its state — the values of its fields at a given moment — into a byte stream. This byte stream can then be saved to disk or transferred through the network. Further, when we want to read the object state from the disk or on the computer sitting on the other side of the network, we need to read that byte stream and then convert it back to the Java object.</p><p>Converting Java objects to byte stream is called Serialization. In python, it is the same as the concept of pickling. The reverse process of converting the byte stream back to the object is called deserialization or unpickling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHczc6irxqXsoslk0K2rvQ.png" /></figure><p>Two important examples where serialization and deserialization play a crucial role are in distributed computing and web services. In distributed computing, data frequently needs to be shared among different nodes of a system, requiring objects to be sent across the network. In web services, serialization is crucial for data exchange between clients and servers.</p><p>Java provides Serializable interface in its core to help us quickly serialize and deserialize java objects.</p><p>Let us use the previously created Person class to demonstrate this. Following is a driver class to save the Person object on disk.</p><pre>import java.io.FileOutputStream;<br>import java.io.IOException;<br>import java.io.ObjectOutputStream;<br><br>public class SerializationDriver {<br>    public static void main(String[] args) {<br>        Person person = new Person(&quot;Pavitra&quot;, &quot;Bengaluru, India&quot;);<br><br>        try (<br>            FileOutputStream fileOut = new FileOutputStream(&quot;person.ser&quot;);<br>            ObjectOutputStream out = new ObjectOutputStream(fileOut)<br>        ) {<br>            out.writeObject(person);<br>            System.out.println(&quot;Serialized data is saved in person.ser&quot;);<br>        } catch (IOException exception) {<br>            exception.printStackTrace();<br>        }<br>    }<br>}</pre><p>When we run this driver code, it throws the following error.</p><pre>java.io.NotSerializableException: com.guptapavitra.Person<br> at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)<br> at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)<br> at com.guptapavitra.SerializationDriver.main(SerializationDriver.java:15)</pre><p>As the error name suggests, our Person class is not serializable. To remove this error and to make our class serializable, we have to make a simple change, and that is to make Person class implement java.io.Serializable interface. Here is the updated Person class.</p><pre>import java.io.Serializable;<br><br>public class Person implements Serializable {<br>    private String name;<br>    private String address;<br><br>    public Person(String name, String address) {<br>        this.name = name;<br>        this.address = address;<br>    }<br>}</pre><p>When we try to run the same SerializationDriver class with our new Person class which extends java.io.Serializable interface, the code doesn’t throw any error. Once the program is run, we can see the person.ser file in our project’s root folder.</p><h4>Transient Fields</h4><p>In case we want to have a field in the objects of a class which we don’t want to be converted during the process of serialization, we will have to declare the field as transient. In our person class, we can do this as follows:</p><pre>import java.io.Serializable;<br><br>public class Person implements Serializable {<br>    private String name;<br>    private String address;<br>    private transient String password;<br><br>    public Person(String name, String address, String password) {<br>        this.name = name;<br>        this.address = address;<br>        this.password = password;<br>    }<br>}</pre><p>Because password is marked as a transient field, it won’t be put into the state at the time of serialization.</p><p>Common reasons to make a field as transient include protecting sensitive information, avoiding serialization of context-specific information like database connections, and optimizing performance by excluding fields that can be derived or recalculated.</p><h3>Conclusion</h3><p>Converting state of Java objects to byte arrays and those byte arrays back to Java objects is important for many scenarios. Two such scenarios are saving the objects on disk or sending the objects over the network. The former is called Serialization and the later is called deserialization. Java provides a quick way to achieve this through the java.io.Serializable interface. We saw how simply implementing Serializatable interface does the job for us. We also discussed how using the transient keyword on some fields will make the serialized byte stream devoid of the state associated with those fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54cda2375db4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Got the basics already? Don’t know how to be a better programmer? Read this.]]></title>
            <link>https://medium.com/@guptapavitra/got-the-basics-already-dont-know-how-to-be-a-better-programmer-read-this-c42e72ee77c8?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42e72ee77c8</guid>
            <category><![CDATA[better-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 09:28:23 GMT</pubDate>
            <atom:updated>2022-04-20T09:28:23.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, one of my friends — who has been working with BI tools for a long time — asked me how he can become a good programmer. He has already done the due diligence to learn the very basics of Java syntax — things like how to write a for loop, if else conditions, switch statements etc. As of today, he is able to approach the his coding problems by googling them and pasting the solution from StackOverflow or some other documentation examples along with some edits of his own. It’s important to mention that he doesn’t want to be a competitive programmer, but simply wants to know how he can write genuinely good code with the help of everlasting internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R7kdFEeWgzdSBt1p" /><figcaption>Photo by <a href="https://unsplash.com/@mimithian?utm_source=medium&amp;utm_medium=referral">Mimi Thian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog post contains my take on how you can approach programming and solve your day-to-day problems if you are just starting in this world. Take everything with a pinch of salt because this is my experience and many others out there can have different experiences of the same. As and when I get more understanding on this topic, I will try to keep updating it.</p><ol><li><strong>Forget that you can mug up the libraries and their reference documentations.</strong> I have seen perfectionist-humans-turned-programmers in the beginning of their programming journey thinking that they need to eventually learn the whole reference documents for the libraries they work with. This is far from how programmers work. These references are ‘references’. These references are like natural language dictionaries. You don’t start mugging up every word in a dictionary when you learn a language — be it your first language or your second. The use of these references is to refer these when you are searching for something. Don’t try to mug it up.<br>So, what is the use of these references? That brings me to my second point.</li><li><strong>Learn the concepts associated with a library, and not the library code.</strong> To understand this, let’s take an example. I was recently working on a code to decrypt files. It took me quite a long time to write this small code. Why? Because I didn’t know the underlying concepts of encryption decryption process. I didn’t know what asymmetric and symmetric encryptions were. I didn’t know what encryption algorithms were. In fact, I didn’t know with confidence if I were to use a private key or a public key to decrypt my files. I was conceptually lost. When this task landed on me, I tried searching for libraries that I could use to accomplish the task of decrypting files. However, given all of these words — like RSA, public key, private key, PGP, GPG, key size — were just floating around everywhere in the code that I saw online. It didn’t make any sense to me. <br>The approach that worked in this case was watching some videos on encrypting-decrypting process, reading some articles on it, and then moving to the actual code. The code eventually made sense then.<br>What I want you to take from this is that it’s important to know what you really want to do on a granular level before jumping in the coding. Once you know that it would take a private key and a passphrase to decrypt the file and there is an algorithm involved which you will probably have to mention somewhere, the intuition will strike. You can go to your chosen library reference and search for a function like ‘.decrypt’ somewhere. Chances are that this function would require you to give it a private key, a passphrase for the private key and the algorithm that it can use. <br>With this, I am also completing what I left in between in the last point. This is how a reference should be used. First you should learn the concepts associated with what you are planning to do, and then your intuition should ask you to search for the right methods in that library reference.</li><li><strong>Try to write cleaner code.</strong> By this, I don’t mean that you should first learn all the clean code practices and then jump on to coding. No, it wouldn’t work that way. Writing clean code takes time and practice. So, while you are writing, just ensure that you are trying to write it cleanly. Eventually, after months and months of practice, tidiness would become a habit. To learn how you can write clean code, you can try googling, or maybe read <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Uncle Bob’s book with the same name</a>. Learning about code smells from <a href="https://refactoring.guru/refactoring/smells">refactoring.guru</a> also helped me a lot.</li><li><strong>Learn the core of your programming language.</strong> You should learn really well the core syntax of your chosen language. Loops, conditionals, break, continue keywords, etc. are all important for sure. You should also know the common language specific features. For example, Java 8 introduced Java Streams. Knowing streams can reduce the size of your code and in fact increase the readability a little more. You should spend time in understanding it by reading articles on the new feature (And not by reading <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">stream’s reference</a>. Remember it’s important to know the concepts before you read what methods does the library provide. However, stream’s reference has some concepts as well.).</li><li><strong>Keep an eye on finding important libraries. </strong>Over time, when you keep coding, based on what you do, you will continue to find libraries that are important to your work. For example, those who work a lot with files, will continue to see libraries like Java IO, Java NIO and classes like Path, URI, FileSystem etc in their code. Once you have already used these libraries some times, you can scroll through the references of these libraries to check what all methods do these provide. Now that you already work with files a lot, you would be able to map files’ concepts to the actual libraries’ methods. This will help you because the next time you need some method, you would be able to remember if the library already has it.</li><li><strong>Pay attention to IDE’s autocomplete suggestions. </strong>The software world is quite big. Many times you find that what you want to do is a repeated task and someone has created a library, a class or a function for it. I remember, not more than a year ago I was stuck writing some code for a week. I asked for help from a teammate and he told me that there was already a class for it. I was embarrassed and unhappy for killing so much of my time. Had I used ‘ctrl + &lt;space&gt;’ on my keyboard to look for what all classes were available with a similar name, I would not have needed to waste so much of my time. So many utilities associated with the &lt;ClassName&gt; I was working with, were available in a class named &lt;ClassName&gt;Utils. It’s important to keep your mind open when you program and not to hesitate to search for things which you think can be repetitive for someone else too. What if a solution already exists!</li></ol><p>Surely it is essential to write more and more code if you want to be a better coder. When you write a lot of code, eventually you learn all of what I have mentioned here. This article is an attempt to show you the right direction when you are starting with your journey. Hope this helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42e72ee77c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TableRowJsonCoder in Apache Beam Pipelines]]></title>
            <link>https://medium.com/@guptapavitra/tablerowjsoncoder-in-apache-beam-pipelines-fbe89d668fe?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe89d668fe</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-dataflow]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 17:31:42 GMT</pubDate>
            <atom:updated>2021-09-01T17:31:42.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eQPuwvQsfGA6lEOn" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is a coder in Apache Beam?</strong></p><p>Apache Beam is used for distributed processing. This means that at a single point of time, there can be more than 1 VMs (workers) working together during the execution of your pipeline. These workers sometimes need to exchange data among each other. The exchange of data happens over a network. However, we can’t send data over network as Java Objects. That’s why the data is first converted (or encoded) to a machine understandable format and then sent to the other worker. On receiving the encoded data, the other worker converts (or decodes) this data from this machine understandable format to a Java Object and then works on it.</p><p>Even outside the scope of apache beam, this encoding and decoding is used for two purposes, 1. to save objects to the machine and 2. to transport objects over the network. To convert Java objects to a machine understandable format, these are some of the options we have.</p><ul><li>JSON</li><li>XML</li><li><a href="http://en.wikipedia.org/wiki/Yaml">YAML</a></li><li>Java Serializable</li><li>Facebook’s <a href="https://thrift.apache.org/">Thrift</a> (RPC + serialization)</li><li><a href="http://code.google.com/apis/protocolbuffers/">Google Protocol Buffers</a></li><li><a href="http://avro.apache.org/">Apache Avro</a></li></ul><p><strong>What is TableRowJsonCoder?</strong></p><p>Before we talk about TableRowJsonCoder, let’s talk a little about TableRow class. If you work with Bigquery data in your beam pipeline, you would have seen TableRow objects some or the other time. Data can directly be read in and be written to TableRow objects using <a href="https://beam.apache.org/documentation/io/built-in/google-bigquery/">Beam’s Bigquery IO connector</a>.</p><p>Apache Beam comes with many inbuilt <a href="https://beam.apache.org/releases/javadoc/2.0.0/org/apache/beam/sdk/coders/package-summary.html">coders</a> which help encode and decode Java Objects. TableRowJsonCoder is one of these inbuilt Apache Beam coders and is used to convert TableRow objects to JSON format and vice versa.</p><p><strong>Example of encoding:</strong></p><pre>public class Runner {<br>    public static void main(String[] args) throws IOException {<br>        // Creating the TableRowJsonCoder instance<br>        TableRowJsonCoder coder = TableRowJsonCoder.<em>of</em>();<br><br>        // Creating a TableRow instance<br>        TableRow tableRow = new TableRow();<br>        tableRow.set(&quot;first name&quot;, &quot;Pavitra&quot;);<br>        tableRow.set(&quot;last name&quot;, &quot;Gupta&quot;);<br><br>        // Creating an output stream<br>        FileOutputStream outputStream = new FileOutputStream(&quot;./table-row-json-encoded&quot;);<br><br>        // Finally encoding the TableRow object to JSON<br>        coder.encode(tableRow, outputStream);<br>    }<br>}</pre><p>In the above code, we create a coder instance, a tableRow instance and an output stream; and finally encode the TableRow Java object to JSON using the coder. This JSON is finally written to the file mentioned in the output stream.</p><p>We get the following result in the ./table-row-json-encoded file.</p><pre>,{&quot;first name&quot;:&quot;Pavitra&quot;,&quot;last name&quot;:&quot;Gupta&quot;}</pre><p><strong>Example of decoding:</strong></p><pre>public class Runner {<br>    public static void main(String[] args) throws IOException {<br>        // Creating the TableRowJsonCoder instance<br>        TableRowJsonCoder coder = TableRowJsonCoder.<em>of</em>();<br><br>        // Creating an input stream<br>        FileInputStream inputStream = new FileInputStream(&quot;./table-row-json-encoded&quot;);<br>        <br>        // Finally decoding JSON to the TableRow object<br>        TableRow tableRow = coder.decode(inputStream);<br><br>        System.<em>out</em>.println(tableRow);<br>    }<br>}</pre><p>In the above code, we create a coder instance and an input stream; and finally decode the recently encoded JSON to the TableRow Java object using the coder. This TableRow object is then printed on the console.</p><p>On running the main function, we see the following output on the console.</p><pre>GenericData{classInfo=[f], {first name=Pavitra, last name=Gupta}}</pre><p><strong>You wouldn’t need to do this manually though…</strong></p><p>When you are working on a beam pipeline, you aren’t supposed to do the encoding and decoding yourself. This is something beam does internally. What you will have to do sometimes is to tell beam which coders you want to use on your PCollections. For most of the types including TableRow, beam is able to guess the coders automatically. You can find the list of default coders <a href="https://beam.apache.org/documentation/programming-guide/#data-encoding-and-type-safety">on this webpage</a>. Consider you are fetching data from Bigquery using the beam’s inbuilt BigqueryIO connector and choosing to get data as TableRow objects, you will automatically be using TableRowJsonCoder without mentioning any coder at all. However, above examples are good to understand the internal working.</p><p><strong>Bonus Tip — Let’s tweak things in our example:</strong></p><p>Now that we are decoding from a human readable format (JSON), let’s manually tweak it before the decoding. I have changed the ‘first name’ from ‘Pavitra’ to ‘Sushmita’.</p><pre>,{&quot;first name&quot;:&quot;Sushmita&quot;,&quot;last name&quot;:&quot;Gupta&quot;}</pre><p>Running the decoding example gives the following error.</p><pre>Exception in thread &quot;main&quot; com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input: expected close marker for Object (start marker at [Source: (String)&quot;{&quot;first name&quot;:&quot;Sushmita&quot;,&quot;last name&quot;:&quot;Gupta&quot;&quot;; line: 1, column: 1])</pre><p>If you pay attention to the encoded JSON in the file ./table-row-json-encoded, you will see an extra character before the JSON’s opening curly bracket. The ASCII number used to represent this character determines the length of the JSON.</p><p>TableRowJsonCoder uses two coders internally, <a href="https://beam.apache.org/releases/javadoc/2.1.0/org/apache/beam/sdk/coders/StringUtf8Coder.html">StringUtf8Coder</a> and <a href="https://www.baeldung.com/jackson-object-mapper-tutorial">Jackson ObjectMapper</a>. StringUtf8Coder in the nested context results in that extra character in the beginning representing the length of the JSON.</p><p><strong>Conclusion</strong></p><p>Apache Beam has the concept of coders for serialization and deserialization of Java Objects. TableRow is a common type we use to read and write data using <a href="https://beam.apache.org/documentation/io/built-in/google-bigquery/">Apache Beam BigqueryIO connector</a>. We can use TableRowJsonCoder to directly convert TableRow to JSON and vice versa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe89d668fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shallow Copy, Deep Copy, and No Copy of Immutable Objects in Python]]></title>
            <link>https://medium.com/analytics-vidhya/shallow-copy-deep-copy-and-no-copy-of-immutable-objects-in-python-b6e673e23c01?source=rss-2fbebb32f4fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e673e23c01</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pavitra Gupta]]></dc:creator>
            <pubDate>Sat, 23 May 2020 16:57:37 GMT</pubDate>
            <atom:updated>2020-05-26T15:01:47.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Shallow Copy, Deep Copy and No Copy of Mutable Objects in Python</h3><p>Python has two types of copies — deep copy and shallow copy. In this document, we are going to discuss about what these are in the context of mutable objects. But first, we will see what I mean by <em>no copy</em>. Let’s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L4wt15NBCoJN_SUW" /><figcaption>Photo by <a href="https://unsplash.com/@louishansel?utm_source=medium&amp;utm_medium=referral">Louis Hansel @shotsoflouis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>No Copy</h3><p>Well, no copy — as the name suggests — is not a copy. It’s just a newbie programmer assigning one variable in another, and expecting a copy.</p><p>Follow this example:</p><pre>a = [[1, 2, 3], [4, 5, 6]]<br>b = a</pre><pre>print(a)<br># [[1, 2, 3], [4, 5, 6]]</pre><pre>print(b)<br># [[1, 2, 3], [4, 5, 6]]</pre><p>Above isn’t a copy. After we execute the lineb = a, there is only one object in the memory, and two variables pointing to it.</p><pre>a.append(7)</pre><pre>print(a)<br># [[1, 2, 3], [4, 5, 6], 7]</pre><pre>print(b)<br># [[1, 2, 3], [4, 5, 6], 7]</pre><p>Or the other way around.</p><pre>a.append(8)</pre><pre>print(b)<br># [[1, 2, 3], [4, 5, 6], 7, 8]</pre><pre>print(a)<br># [[1, 2, 3], [4, 5, 6], 7, 8]</pre><p>So, when you assign one mutable object to another variable:</p><ul><li>There are no new object (or in this case — list) created in the memory.</li><li>There is just a new variable pointing to the same object.</li><li>Any change in the object stored in memory through one variable would also reflect if you access the object through another variable. Because essentially, it’s the same object.</li></ul><p>Now that we are clear that assignment doesn’t create a copy in python, let’s discuss what options we have when it comes to copying mutable objects in python.</p><h3>Shallow Copy</h3><p>A shallow copy of a mutable object produces a new object in the memory. But elements of the original object are not copied in the memory. Just the references of these elements are seen in the new object.</p><p>Difficult? Let’s see in an example.</p><pre>import copy</pre><pre>a = [[1, 2, 3], [4, 5, 6]]<br>shallow_a = copy.copy(a)</pre><p>In the above code, we are using python copy.copy() to shallow copy a to shallow_a.</p><pre>print(shallow_a)<br>[[1, 2, 3], [4, 5, 6]]</pre><p>This looks exactly the same, right? But it did look the same even during assignment. Let’s see further.</p><pre>a.append(9)</pre><pre>print(a)<br># [[1, 2, 3], [4, 5, 6], 9]<br>print(shallow_a)<br># [[1, 2, 3], [4, 5, 6]]</pre><p>Do you already see how it is different from simple assignment? If not, check what happened when we appended 7 to a in the assignment example.</p><p>This time, we appended 9 to a and it got appended as expected. Because shallow_a is a copy of a, and not a reference to the same object in memory, shallow_a should not automatically have 9. And it doesn’t. So, all good!</p><p>Congratulations. We have learnt basics about shallow copying mutable objects in python!</p><h3>But then why do I need deep copy at all?</h3><p>In the last example, the first and the second elements of a are also lists. Let’s append 4 to the first inner list and check both the variables.</p><pre>a[0].append(4)</pre><pre>print(a)<br># [[1, 2, 3, 4], [4, 5, 6], 9]</pre><pre>print(shallow_a)<br># [[1, 2, 3, 4], [4, 5, 6]]</pre><p>Same problem again? Baffled? Something’s wrong? No. Nothing is wrong. Python shallow copy behaves like this. Let’s learn what really happened.</p><p>When we shallow copied a, we copied the outer list, and ended up having two outer lists in the memory— one that was pointed by a, and another that was pointed by shallow_a. But the inner lists didn’t get their own copies in the memory. So, we still ended up with only two inner copies, and not four.</p><p>When we appended 9 to a initially in the shallow copy example, we actually appended only to a, and not to shallow_a, because these were completely different objects in the memory. But when we appended 5 to the first inner list, that change was also seen by shallow_a because it’s the same two inner lists in the memory. Makes sense?</p><p>In fact, it’s called a shallow copy, because it has just one level of copying involved. If the elements of the original objects are also mutable objects (in our example - inner lists), then the new object doesn’t have its own set of inner objects. What you see while printing the new object is the same inner objects in the memory as you see while printing the original object. And that’s where deep copy comes into picture.</p><p>But before we proceed to deep copies, here is a very important part — one in which many get trapped. Let’s follow another example.</p><pre># Initialise a new list of lists<br>a = [[1, 2, 3], [4, 5, 6]]</pre><pre># Make a shallow copy<br>shallow_a = copy.copy(a)</pre><pre># Replace the first element<br>a[0] = [6, 7, 8]</pre><pre>print(a)<br># [[6, 7, 8], [4, 5, 6]]</pre><pre>print(shallow_a)<br># [[1, 2, 3], [4, 5, 6]]</pre><p>There was a different response to a similar operation a minute ago, right? If you make a change an inner list of a, it would propagate to shallow_a as well. Isn’t that why we needed deep copies at all? So, in this example, shallow_a should have been [[6, 7, 8], [4, 5, 6]] Right? <em>All wrong.</em></p><p>In the very last example, we are <em>not making a change</em> in the first inner list. We are actually assigning the first element of the outer list to a new list which points to a completely different memory location. And because the original inner list didn’t get changed in the memory, we didn’t see a change in shallow_a. To differentiate with the previous example, there we were appending 4 to the inner list, and because it was the same inner list in the memory that got appended with 4, it reflected in the shallow_a. Makes sense?</p><p>This is one of the things I was <em>the most</em> confused about when I first heard about different types of copies. So, now if one of your colleagues ask you for shallow copy, you — unlike me when I learnt it for the first time — will be able to convince him/her that you know it.</p><p>Let’s move to deep copy.</p><h3>Deep Copy</h3><p>A deep copy of a mutable object is a new object in the memory. All the nested elements of the original object have their separate copies in the memory. In other words, unlike shallow copies, no nested elements of the new object ever point to the nested elements of the original object in the memory.</p><p>Again, difficult? Let’s see with an example.</p><pre>import copy</pre><pre>a = [[1, 2, 3], [4, 5, 6]]</pre><pre>deep_a = copy.deepcopy(a)</pre><pre>print(deep_a)<br># [[1, 2, 3], [4, 5, 6]]</pre><p>Now, let’s try to change the value of a:</p><pre>a[0].append(7)</pre><pre>print(a)<br># [[1, 2, 3, 7], [4, 5, 6]]</pre><p>Above, we created a list of lists, called it a, deep copied it using python copy library, called the deep copy deep_a, and then appended 7 to the first element of a.</p><p>Let’s check the value of deep_a.</p><pre>print(deep_a)<br># [[1, 2, 3], [4, 5, 6]]</pre><p>deep_a doesn’t change at all. As mentioned in the definition, in deep copy, even the nested elements are copied in the memory. So, elements of the original object and elements of the new object don’t point to the same objects in memory. That’s why, when we append an element even the inner list, it doesn’t reflect in the deep copy.</p><p>Similarly, any modifications in deep_a don’t reflect in a. These are two different lists. Just that these lists — at the time of copying — had the same values.</p><h3>Conclusion</h3><p>In this document, we learnt about two types of copies in python. We also learnt that assignment isn’t technically a copy. To recap the difference and similarity between deep and shallow copies:</p><ul><li>In shallow copy, the object created by copy has its nested elements pointing to the same objects in the memory as of the nested elements of the original object.</li><li>In deep copy, the object created by copy has its nested elements pointing to the new copies of the element objects in the memory. These new copies of the element objects are totally different in memory than those of original element objects in the memory.</li><li>In both the copies, the object created by copy itself is a different object in memory than the original object.</li></ul><p>Feel free to write any suggestions or corrections in the comments. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e673e23c01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/shallow-copy-deep-copy-and-no-copy-of-immutable-objects-in-python-b6e673e23c01">Shallow Copy, Deep Copy, and No Copy of Immutable Objects in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>