<?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[Insights from ThoughtClan - Medium]]></title>
        <description><![CDATA[ThoughtClan is a Technology company, that solves critical business problems, on time and budget. Our 100+ development team focus on Data Science, Digital Commerce and Digital Engineering services. - Medium]]></description>
        <link>https://medium.com/insights-from-thoughtclan?source=rss----1c117f23c8b2---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Insights from ThoughtClan - Medium</title>
            <link>https://medium.com/insights-from-thoughtclan?source=rss----1c117f23c8b2---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:39:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/insights-from-thoughtclan" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploring the Power of Firestore Rules: Best Practices and Examples]]></title>
            <link>https://medium.com/insights-from-thoughtclan/exploring-the-power-of-firestore-rules-best-practices-and-examples-a5edbb26803d?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5edbb26803d</guid>
            <category><![CDATA[firestore-rules]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <dc:creator><![CDATA[Sanjeeva Chitlapalli]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 05:45:53 GMT</pubDate>
            <atom:updated>2024-02-21T05:45:53.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m4OXtyADz11d1FuW" /></figure><p>Firestore, Google’s NoSQL document database, offers a robust security mechanism called Firestore Rules. These rules allow developers to control access to their database, ensuring that sensitive data remains protected while providing appropriate access to authorized users. In this comprehensive guide, we will delve into the intricacies of Firestore Rules, exploring best practices and providing real-world examples to demonstrate their power.</p><h3>1. Understanding Firestore Security Rules</h3><p>Firestore Security Rules provide a powerful mechanism to control access to your database, ensuring that your data remains secure and accessible to authorized users. By defining these rules, you can enforce authentication requirements, validate data integrity, and restrict access to specific collections or documents.</p><h4>What are Firestore Security Rules?</h4><p>Firestore Security Rules are a set of conditions and permissions that determine who can read, write, and modify data in your Firestore database. These rules are defined using a simple yet expressive syntax, allowing you to create fine-grained access controls based on your application’s requirements.</p><h4>Integration with Firebase Authentication</h4><p>One of the key benefits of Firestore Security Rules is its seamless integration with Firebase Authentication. By combining Firestore with Firebase Authentication, you can enforce user-based access controls, ensuring that only authenticated users can access specific data in your database.</p><h4>The Role of Access Tokens</h4><p>Access tokens play a crucial role in Firestore Security Rules. When a user authenticates with Firebase Authentication, they receive an access token that contains information about their identity and authorization. Firestore Security Rules can then use this access token to determine if a user has the necessary permissions to read, write, or modify data.</p><h3>2. Getting Started with Firestore Rules</h3><p>To begin utilizing Firestore Security Rules, it’s important to understand the basic syntax and structure. Firestore rules consist of match statements, which specify the path to a document, and allow expressions, which define the conditions for granting access to that document.</p><h4>Firestore Rules Syntax</h4><p>Firestore rules are written in a declarative manner, following a specific syntax. The service declaration specifies the Firestore service, while match statements define the path to a document or collection. The allow expression is used to specify the conditions for granting read or write access.</p><pre>rules_version = &#39;2&#39;;<br><br>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /collection/{document} {<br>      allow read, write: if &lt;condition&gt;;<br>    }<br>  }<br>}</pre><h4>Defining Match Statements</h4><p>Match statements are used to specify the path to a document or collection within your Firestore database. You can use wildcards, such as {document=**}, to allow rules to apply to multiple documents or collections. By using these match statements, you can define fine-grained access controls based on the specific paths within your database.</p><h4>Allowing Read and Write Operations</h4><p>The allow expression is used to define the conditions for granting read or write access to a document or collection. By specifying allow read or allow write, you can control the type of access that is allowed. The conditions within the if statement are evaluated to determine if the access should be granted.</p><h3>3. Basic Rule Patterns</h3><p>Let’s explore some basic rule patterns that are commonly used in Firestore Security Rules. These patterns will help you understand how to define access controls and restrictions for your database.</p><h4>Denying All Reads</h4><p>In certain scenarios, you may want to deny all read access to your database. This can be useful when you have sensitive data that should not be exposed to any user. By using the if false condition, you can deny all read operations.</p><pre>match /{document=**} { allow read: if false;}</pre><h4>Denying All Writes</h4><p>Similar to denying reads, you may also want to deny all write operations to your database. This can be useful when you want to ensure that data remains static and cannot be modified. By using the if false condition, you can deny all write operations.</p><pre>match /{document=**} { allow write: if false;}</pre><h4>Granting Access to Authenticated Users</h4><p>To allow access only to authenticated users, you can use the request.auth object in your rules. By checking if request.auth.uid is not null, you can ensure that only authenticated users can read or write data.</p><pre>match /{document=**} { allow read, write: if request.auth.uid != null;}</pre><h4>Ensuring User-Specific Access</h4><p>To enforce user-specific access controls, you can check if the requesting user’s ID matches the ID stored in the document being accessed. This pattern is useful when you want to restrict users to their own data.</p><pre>match /users/{userId} { allow read, write: if request.auth.uid == userId;}</pre><h3>4. Advanced Rule Patterns</h3><p>Let’s explore some advanced rule patterns that can be used to enforce more complex access controls and data validations in Firestore Security Rules.</p><h4>Scoped Rules for Specific Operations</h4><p>In some cases, you may want to define different conditions for specific read or write operations. For example, you may want to allow users to read documents but restrict their ability to list all documents in a collection. By using scoped rules, you can define different conditions for get, list, create, update, and delete operations.</p><pre>match /collection/{document} {<br>  // Applies to read operations on a single document<br>  allow get: if &lt;condition&gt;;<br><br>  // Applies to list operations on the entire collection<br>  allow list: if &lt;condition&gt;;<br><br>  // Applies to create operations<br>  allow create: if &lt;condition&gt;;<br><br>  // Applies to update operations<br>  allow update: if &lt;condition&gt;;<br><br>  // Applies to delete operations<br>  allow delete: if &lt;condition&gt;;<br>}</pre><h4>Recursive Wildcards for Hierarchical Data</h4><p>Firestore allows you to organize data in collections and subcollections, creating a hierarchical structure. To apply rules to all documents within a collection and its subcollections, you can use recursive wildcards. By using {name=**}, you can match any document within the specified path, even if it is located in a deeply nested subcollection.</p><pre>match /collection/{document=**} {<br>  allow read, write: if &lt;condition&gt;;<br>}</pre><h4>Checking Data Validity with Conditions</h4><p>Firestore Security Rules enable you to validate data before allowing write operations. For example, you can check if a specific field has a certain value or if the length of a value meets certain criteria. By using conditions, you can ensure that data being written to your database is valid and meets your requirements.</p><pre>match /collection/{document} {<br>  allow write: if request.resource.data.field == &#39;value&#39; &amp;&amp; request.resource.data.value.length &gt; 5;<br>}</pre><h3>5. Common Functions for Firestore Rules</h3><p>Firestore Security Rules support the use of custom functions, which can be handy for simplifying complex conditions and enhancing code reusability. Let’s explore some common functions that can be used in Firestore Rules.</p><h4>Verifying Value Types</h4><p>You can create custom functions to verify the type of a value being written to your database. By using these functions, you can ensure that only values of a specific type are allowed.</p><pre>function isString(value) {<br>  return value is string;<br>}<br><br>function isNumber(value) {<br>  return value is number;<br>}<br><br>match /collection/{document} {<br>  allow write: if isString(request.resource.data.field) &amp;&amp; isNumber(request.resource.data.value);<br>}</pre><h4>Validating Value Inclusion in a List</h4><p>In certain cases, you may want to validate if a value belongs to a list of allowed values. By creating a custom function, you can check if a value is included in a predefined list.</p><pre>function isIncluded(value, allowedValues) {<br>  return value in allowedValues;<br>}<br><br>match /collection/{document} {<br>  allow write: if isIncluded(request.resource.data.field, [&#39;value1&#39;, &#39;value2&#39;, &#39;value3&#39;]);<br>}</pre><h4>Enforcing Value Length Restrictions</h4><p>You can also enforce length restrictions on values being written to your database. By using a custom function, you can check if the length of a value meets your specified criteria.</p><pre>function isLengthValid(value, minLength, maxLength) {<br>  return value.length &gt;= minLength &amp;&amp; value.length &lt;= maxLength;<br>}<br><br>match /collection/{document} {<br>  allow write: if isLengthValid(request.resource.data.field, 5, 10);<br>}</pre><h3>6. Ensuring Security with Nested Rules</h3><p>Firestore Security Rules allow you to nest match blocks to create more complex access controls. By nesting match blocks, you can define rules for specific paths within your database, ensuring that access is granted or denied according to your requirements.</p><h4>Accessing Other Documents with get() and exists()</h4><p>With Firestore Security Rules, you can access other documents in your database to perform additional checks or validations. The get() function allows you to retrieve the state of a document, while the exists() function checks if a document exists.</p><pre>match /collection/{document} {<br>  allow write: if exists(/databases/$(database)/documents/users/$(request.auth.uid));<br>}</pre><h4>Transactional Operations with getAfter()</h4><p>In Firestore, you can perform transactional operations using the getAfter() function. This function allows you to access the state of a document after a transaction, enabling you to define complex rules that involve multiple write operations.</p><pre>match /collection/{document} {<br>  allow write: if getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;<br>}</pre><h4>Access Call Limits and Pricing Considerations</h4><p>It’s important to be aware of the access call limits in Firestore Security Rules. Firestore enforces limits on the number of document access calls per rule set evaluation, which can impact the performance and cost of your application. Make sure to optimize your rules and consider caching to minimize the impact on your Firestore usage and billing.</p><h3>7. Deploying and Testing Firestore Rules</h3><p>Once you’ve defined your Firestore Security Rules, you need to deploy them to your Firestore database. Firestore provides multiple deployment options, including using the Firebase Console, Firebase CLI, or the Firestore REST API. After deployment, it’s crucial to test your rules thoroughly to ensure they function as expected.</p><h4>Deploying Rules with Firebase Console</h4><p>To deploy your Firestore Security Rules using the Firebase Console, navigate to the Firestore section and open the Rules tab. Write your rules in the online editor and publish them to apply the changes.</p><h4>Deploying Rules with Firebase CLI</h4><p>Using the Firebase CLI allows you to deploy your Firestore Security Rules as part of your existing deployment process. Set up Firestore in your project directory and create a .rules file to define your rules. Finally, use the Firebase CLI to deploy the rules to your Firestore database.</p><pre>firebase init firestore<br>firebase deploy - only firestore</pre><h4>Using the Firestore Rules Simulator for Testing</h4><p>Firestore provides a Rules Simulator that allows you to test your ruleset before deploying it to your production environment. The Rules Simulator allows you to simulate authenticated and unauthenticated reads, writes, and deletes, helping you ensure that your rules are working as intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fB_OGjfQoDXsdfXs" /></figure><h3>8. Best Practices for Firestore Rules</h3><p>To ensure the security and efficiency of your Firestore database, it’s important to follow best practices when defining your Firestore Security Rules. Here are some key recommendations to keep in mind:</p><ul><li>Secure by Default: Deny all access by default and only allow specific operations as needed.</li><li>Granular Access Control: Define fine-grained access controls for different operations and user roles.</li><li>Leverage Firebase Authentication: Integrate Firestore Security Rules with Firebase Authentication to enforce user-based access controls.</li><li>Validate Data Integrity and Ownership: Use conditions to validate data integrity and check if users have ownership of specific documents.</li><li>Optimize Rules and Usage: Minimize the number of access calls, consider caching, and regularly review and optimize your ruleset.</li></ul><h3>9. Real-World Examples of Firestore Rules</h3><p>Let’s explore some real-world examples of Firestore Security Rules to understand how they can be applied in practical scenarios.</p><h4>Securing Public and Protected Data Collections</h4><p>Imagine you have a Firestore database with three collections: publicdata, protecteddata1, and protecteddata2. You want to ensure that only authenticated users can access the protected data collections while allowing read-only access to the public data collection. You can achieve this by defining specific rules for each collection.</p><pre>match /publicdata/{document} {<br>  allow read;<br>}<br><br>match /protecteddata1/{document} {<br>  allow read, write: if request.auth.uid != null;<br>}<br><br>match /protecteddata2/{document} {<br>  allow read, write: if request.auth.uid != null;<br>}</pre><h4>Allowing Read-Only Access for Public Data</h4><p>If you have a collection that contains public data that should be accessible to all users, you can define rules to allow read access for everyone while restricting write access to authenticated users only.</p><pre>match /publiccollection/{document} {<br>  allow read;<br>  allow write: if request.auth.uid != null;<br>}</pre><h4>Securing User-Specific Data with Authenticated Access</h4><p>To ensure that users can only access their own data, you can enforce user-specific access controls. By checking if the requesting user’s ID matches the ID stored in the document being accessed, you can restrict access to user-specific data.</p><pre>match /users/{userId} {<br>  allow read, write: if request.auth.uid == userId;<br>}</pre><h3>10. Conclusion: Harnessing the Power of Firestore Rules</h3><p>Firestore Security Rules offer a powerful and flexible mechanism for controlling access to your Firestore database. By using these rules, you can enforce authentication requirements, validate data integrity, and restrict access to specific collections or documents. By following the best practices and examples outlined in this guide, you can ensure the security and efficiency of your Firestore database. Harness the power of Firestore Rules and build secure and robust applications with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5edbb26803d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/exploring-the-power-of-firestore-rules-best-practices-and-examples-a5edbb26803d">Exploring the Power of Firestore Rules: Best Practices and Examples</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 : Evolving Technology and Existing IT systems : Drivers of Digital Transformation]]></title>
            <link>https://medium.com/insights-from-thoughtclan/part-2-evolving-technology-and-existing-it-systems-drivers-of-digital-transformation-f2c836550a39?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/f2c836550a39</guid>
            <dc:creator><![CDATA[Harish Kashyap]]></dc:creator>
            <pubDate>Thu, 17 Nov 2022 10:13:53 GMT</pubDate>
            <atom:updated>2022-11-17T10:16:07.216Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Part 2 : Evolving Technology and Existing IT systems : Drivers of Digital Transformation</strong></h3><p>In my view, any Information processing software system in an Enterprise can be categorised into</p><ul><li><strong>Data capturing or an Information Exchange System</strong> — Any transactional system that is used to capture data, system that allows a stakeholder to participate in a business process, an information exchange platform to collaborate, a system to enable purchase of my products by end customers. etc. For example : My mobile commerce system, Web application to compare quotes and purchase an insurance. etc .</li><li><strong>Reporting and Decision making System</strong> — Any reporting and analytical system, that is read only, typically internal or partner facing, the one that is used to analyse and take decisions that help my business. For example: Performance Dashboard and Analytics system</li></ul><p>Applying the need of speed and agility for the above category of systems, the key pattern is to build software/applications with components that are independent, functional, yet loosely coupled and highly integrable with one another. I am kind of building a lego block that can allow me to build and change a larger object the way i would want. This design thought has always been there but has been made implementable with following technology evolution and changes.</p><ul><li><strong>Evolving User Interface Framework with no coupling to backend.</strong> For example: React JS, Angular and Vue JS are matured to a level where one can build rich and responsive web and mobile applications addressing a separation of concern pattern. With Progressive Web App making inroads as well, it is imperative that all enterprise adopt it faster than later.</li><li><strong>Containerisation of Infrastructure and compartmentalisation of Applications</strong>. Infrastructure is more and more virtualised with AWS, GCP and Azure cloud virtualising the hardware, docker images virtualising the Operating Systems, Kubernetes virtualising the Application servers and services and so on. Virtualisation is been made possible because of containerisation. Because the container runs my functional components, i can scale the container independently and scale up and out independently.</li><li><strong>Micro services as an architecture pattern</strong> that allow a Business function to be broken into independent functional component that can be deployed and scaled independently. Key word is scalability and this is made possible because of the containerisation we spoke about. So, today, i can have a Registration service in Java, a Promotion service in .NET, integrate them using REST based web-services accessed using an API gateway by a React JS and React native web and mobile front ends. Key thing here is that i can change my Registration independent of Promotion and scale them independently thus making my Business agile.</li><li><strong>API gateways and Integration middleware</strong> such as apigee, MuleSoft that would allow to orchestrate, manage access and integrate micro services using REST, JSON etc.</li><li><strong>Event driven systems </strong>that help in recognising and reacting to events in a timely manner. Imagine the happiness of a marketing person if he gets to know that the customer he sent an email campaign, is participating in an event related to the same product that was sent in the campaign.</li><li><strong>Machine Learning and AI Models </strong>— This is a vast topic and its application are many, especially in decision making systems. Given the amount of unstructured data that people have captured today be it in Social media text or pictures, Emails, Customer Service Call history etc, there is a larger need to analyse and understand this data. Clearly, today, there are algorithms, models and techniques that can help in clustering, classification and regressing the information so that i can be used to predict, forecast and optimise decision making. For example: One can analyse facebook data [that is unstructured] on a customers perception of the product and tie them with a promotion data that an eCommerce system sent out and predict the effectiveness of the promotion.</li></ul><p>These are only an examples of technology evolution. Key thing is that are you leveraging any of these to help your business.</p><p><strong>Existing IT System and Code: Drivers of Digital Transformation</strong></p><p>One of the other key driver to get my organisation agile is to look at the existing code base, technology landscape and see how it has been evolved. Key questions to answer are:</p><ol><li>How large is my code base today? How complex is the dependency in the code? I have seen and been through the DLL hell problem to a JAR war problem to now a Javascript conflict issue. The moment you start using tools to figure out dependencies between the code base then i think its time to refactor the code to a more elegant micro services and loosely coupled architecture.</li><li>How much time does it take to change, test and deploy the code? If it takes a sufficient downtime to deploy a simple to medium complexity functional change, then it is time to refactor the code and deployment process. A major and minor release cycles are no more relevant to an individual, business specific applications. Its time to automate regression testing, smoothen deployment process and achieve a zero downtime deployment.</li><li>Is this code base still delivering my business differentiation or can i replace it by a Commercial off the shelf product? This question need to be asked even if the system has delivered well in the past. Key thing is whether it is still relevant or has the competition caught up? If so, then its time to refactor or re-engineer.</li><li>How dependent is the current IT process and code with my employees. Let us accept it, no matter how good your employees are, any organisation does not want to have a dependency on an employee or a particular group if they happen to be critical for its business function. If the dependency on a particular tool or an employee or a group is too high, then its definitely time to relook at refactoring or re-engineering.</li></ol><p>While these are only an example, we at ThoughtClan do a current IT landscape and code quality analysis to help our clients arrive at a Digital Transformation roadmap . Reach out to <a href="/service/mailto:info@thoughtclan.com">info@thoughtclan.com</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c836550a39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/part-2-evolving-technology-and-existing-it-systems-drivers-of-digital-transformation-f2c836550a39">Part 2 : Evolving Technology and Existing IT systems : Drivers of Digital Transformation</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NodeJS Event Loop Model]]></title>
            <link>https://medium.com/insights-from-thoughtclan/understanding-nodejs-event-loop-model-fbb581ebd654?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/fbb581ebd654</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Satheesh]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 04:13:00 GMT</pubDate>
            <atom:updated>2022-09-13T04:13:00.167Z</atom:updated>
            <content:encoded><![CDATA[<p>I have always wondered how NodeJS server runtime is able to handle high throughput applications, when it is said that NodeJS is single-threaded 🤔. So, I decided to dig a little deeper to understand how the runtime makes this possible.</p><p><strong>Overview</strong></p><p>First, let’s look at what NodeJS is. It is a JavaScript runtime built to run on the server side. It is built on top of Google’s open-source V8 high-performance JavaScript engine and is fully ES6 (ECMAScript language syntax) compliant.</p><p>NodeJS can be used in a variety of use cases including but not limited to:</p><ul><li>Web applications,</li><li>Cloud serverless applications,</li><li>Scripting,</li><li>Build management.</li></ul><p>Below is a quote from Node JS’s <strong><em>about</em></strong> page. As it can be understood from this statement, event-driven programming is at the core of NodeJS runtime.</p><blockquote><em>As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.</em></blockquote><blockquote><em>(</em><a href="https://nodejs.org/en/about/">https://nodejs.org/en/about/</a><em>)</em></blockquote><p><strong>Is NodeJS Single-threaded?</strong></p><p>While the business logic that we write and the event loop runs in a single thread, NodeJS hands-off time-consuming tasks (including I/O) to an underlying library called <strong>Libuv </strong>which delegates such tasks to the kernel or a thread pool. So, to answer this question, <strong>NodeJS is not single-threaded</strong>.</p><p><strong>Single-Threaded Event Loop Model</strong></p><p>Node JS uses a concept called “<strong>Single-Threaded Event Loop Model</strong>” designed for <strong>asynchronous non-blocking I/O</strong>. This principle is heavily dependent upon queues &amp; callbacks.</p><ul><li>When we start a NodeJS application, the single-threaded runtime starts the ”main” script execution and the <strong>“event loop”</strong>.<br>- In case of scripting, this would be the start-up method e.g., logic that is written in <em>index.js</em>.<br>- In case of web applications, this would be web server initialisation logic e.g., express server.</li><li>Any I/O operations are automatically queued.<br>- This includes incoming HTTP requests too.</li><li>Such operations are delegated to <strong>Libuv</strong> (underlying C library).</li></ul><p>This principle is somewhat similar to <em>reactive programming</em> based web application architectures like e.g., Vert.x, Spring Webflux etc.</p><p><strong>How It Works</strong></p><p>Below is a representation of how NodeJS handles time-consuming / I/O operations by handing-off to <strong>Libuv</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8du1JaJr-ngDQmZ_hi-ew.png" /><figcaption>NodeJS Event Loop Model</figcaption></figure><p>When an HTTP request comes in,</p><ul><li><strong>Libuv </strong>delegates the task of reading the request from the socket to the kernel. Once request data becomes available, an event is posted in the <strong>Event Queue</strong>.</li><li>The <strong>Main Thread </strong>picks up the event from the queue and starts processing it (handles the request).</li><li>As part of the request handling, if there are any I/O operations, control passes off to <strong>Libuv</strong>.</li><li>Such operations are in-turn handled in two different ways:<br>- Some operations (e.g., making / receiving TCP calls) are handled directly by the <strong>kernel</strong>.<br>- Some operations (e.g., reading / writing files) are handled by a <strong>thread pool </strong>maintained by <strong>Libuv.</strong></li><li>In parallel, <strong>Main Thread </strong>is now free to pick next event from the event queue.</li><li>Once operation is complete, event is pushed into the <strong>Event Queue.</strong></li><li><strong>Main Thread </strong>will pick and process the event at the top of the <strong>Event Queue </strong>as and when it becomes free.</li></ul><p><strong>Summing Up</strong></p><p>As we can see, NodeJS is not single-threaded. Even though user code and event loop run in a single thread, all I/O operations are delegated either to the kernel or to a thread pool.</p><p>One final note for NodeJS newbies before we part. <strong>Do not use the “Sync” suffixed methods provided by some libraries e.g., fs.readFileSync(); this blocks the Main Thread. </strong>Always use async methods; prefer to return the promise wherever possible; use <em>“await” </em>wherever the response from the async method is required to continue executing the logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb581ebd654" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/understanding-nodejs-event-loop-model-fbb581ebd654">Understanding NodeJS Event Loop Model</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 : Business Need : Drivers of Digital Transformation]]></title>
            <link>https://medium.com/insights-from-thoughtclan/part-1-business-need-drivers-of-digital-transformation-602a59023363?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/602a59023363</guid>
            <category><![CDATA[customer-centricity]]></category>
            <category><![CDATA[digital-transformation]]></category>
            <category><![CDATA[apply-technology]]></category>
            <category><![CDATA[information-analytics]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Harish Kashyap]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 05:57:04 GMT</pubDate>
            <atom:updated>2021-09-13T06:57:36.222Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Part 1 : Business Need : Drivers of Digital Transformation</strong></h3><p>I have always been impressed by these two statements. More so relevant in the current pandemic context</p><ul><li>It is survival of the fastest now</li><li>Competition is one click away</li></ul><p>There are many cases in Software industry where many businesses have lost out by not adhering to the above. I do not want to take names but anybody who has spent significant time in Software field will know how amazon tanked a most popular offline book shop, how google took away the search engine market which was once captured by a competitor. Similarly, i see a new trend today in neo banking space which can give the traditional banks a run to their money.</p><p>So, the key thing is to stay competitive and change quickly to follow the competition if they go ahead. How do we achieve it? Answer is to use technology to transform the business digitally.</p><p>Digital transformation is all about applying and leveraging evolving technology to solve an existing business problem or to help business achieve its goals.</p><p>Let us look at it bit more detail in terms of relevance to business.</p><p>Business is all about selling relevant products/services to customers at right price.</p><p><strong>Customer is the always the king and his experience is most important:</strong></p><p>Customer expectation continues to rise. Customer wants highly personalised and speed for convenience. As the technology evolves, it is very natural for any person to expect productivity and convenience. As an example: When i am driving, i expect my mobile to take instructions using my voice, be it for opening a destination in google map, or to open my favourite youtube talks. Similarly, would like an easy way of making payments for an online purchase, preferable with one single click, I also want a quick way to compare my vehicle insurance quotes, make a purchase and sign the contract digitally. Many customers do not like to be contacted and spend time for a mundane process. More digital, better it would be.</p><p><strong>Business needs to know more about the customer :</strong></p><p>To treat the customer as king, the business would like to know more the about the customer so that they can clearly sell <strong>relevant</strong> product/services. Relevance is the key and the way to find it is to know more about the customer. For example: As a business user, i would like to have control of promotions that i setup for my products online. i would like to see the effectiveness of of my marketing campaign. Similarly, If some customer is searching for a product with a search term and if he is not getting any search results, i would like to know what that failed search term has been.</p><p><strong>Enhancing Customer reach — Make your product and service more and more visible:</strong></p><p>The popular products sell themselves. The long tail is the key. While it is known what customer wants and needs, one need to spend extra energy to make the customer aware of his new products/services, changes to existing ones be it a price or a feature etc. It might also be the case where the businesses are not able to reach out to my customers directly. For e.g. : A manufacturer always relies on a retailer to get his product reach his customer. Imagine if the manufacturer could reach the customer directly and by pass as many intermediaries as possible.</p><p><strong>Externalize your Business function and be ready to be aggregated</strong></p><p>With aggregator model (e.g.: Price Comparison sites, eCommerce Marketplaces) becoming popular, especially where the service is commoditised, it is becoming increasing difficult to stay niche of a smaller part of a larger business process and still be competitive. One has to either be ready to be part of an aggregator or offer the complete process themselves. For e.g.: Used Car selling market was very fragmented and unstructured in Indian market until aggregators like Cars24 came in. Similarly there has been lots of examples of how aggregators and marketplace players such as Udaan, RedBus, PolicyBazaar etc. have created a space for themselves and have also created a competition amongst respective service providers. Imagine a service provider who is not well equipped to be part of the aggregator platform. He will struggle to stay competitive.</p><p><strong>Automate Business Processes that are repetitive</strong></p><p>By automating business processes one can clearly achieve increased productivity, better customer service, transparency and traceability, efficiency, accuracy, convenience etc. For e.g.: Complete End to end automation of Expense management with user requiring to only upload images of receipts and bills will have many takers and benefits. Similarly Banks, automating process of onboarding a customer including KYC checks, Anti money laundering checks etc will bring in more transparency and speed. Workforce automation and Supply chain automation will bring in efficiency.</p><p><strong>Configure rules to drive change and scale</strong></p><p>Many businesses prefer to go global after being successful in one of the country of presence. It is also common to repeat a success of a particular line of business to other lines or categories. More often than not, many processes and rules will be common across countries, line of business etc with few changes specific to each country or line of business. It is imperative to have systems that are configurable and rules driven so that it is easy to make change to a specific country or to even launch to a new country.</p><p><strong>Use Information to differentiate over competition</strong></p><p>One of our client, who is a background verification service provider, wanted to build a criminal database so that it could help their decision making during verification. What was interesting was the data they used to build this database. They analysed all judgement documents given by all the courts to identify name and address data of criminals. The work was complex but what was important was that they were able to use a publicly available information to help their business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIe_elwTmjgfsWCfcwp_Jg.jpeg" /><figcaption>Apply Technology to achieve Business Competitiveness</figcaption></figure><p>So, it is clear that there is a need to capture more information, think inside-out, reach out more, analyse more about the customer, use available information effectively to be able to arrive at accurate and timely decisions. Key thing is to find out what are you doing to help achieve the above need.</p><p>We at ThoughtClan do a competitive benchmarking and Business–Technology fit gap analysis to help our clients arrive at a Digital Transformation roadmap. Reach out to info@thoughtclan.com for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602a59023363" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/part-1-business-need-drivers-of-digital-transformation-602a59023363">Part 1 : Business Need : Drivers of Digital Transformation</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Recent Developments]]></title>
            <link>https://medium.com/insights-from-thoughtclan/java-recent-developments-8161e281a0d1?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/8161e281a0d1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Satheesh]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 13:11:38 GMT</pubDate>
            <atom:updated>2021-10-25T13:34:11.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Recent Developments</h3><h4>Scripting &amp; Shell Introduction</h4><p>In the last article on <a href="https://blogs.thoughtclan.com/java-recent-developments-915da8bcb0c6">“Modules &amp; Leaner Runtime”</a>, I had explored Java Platform Modules System (JPMS) and it’s aim of creating leaner runtime.</p><p>In this article, let us see some of the scripting features introduced in Java in recent versions.</p><p>Another notable feature introduced in recent versions of Java is scripting support. It is now easier to try out Java features &amp; syntax quickly without having to create a new Java project. Similarly, one can write scripts using Java language.</p><p>The main advantage of the below features is that they give a good starting point for developers learning Java; these are sure to give a perception of ease and simplicity regarding the language.</p><h3><strong>JShell</strong></h3><p><strong><em>JShell</em></strong> was introduced in Java 9. It allows programmers &amp; learners to quickly try out a piece of code in the shell. Similar to Python &amp; PHP Shell, this can be used if we want to try out new language syntax / features and also to verify a logic quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*VN8HHVoy75VtdjWxexreRA.png" /><figcaption>JShell</figcaption></figure><p>In the above shell snippet, those highlighted in green are the code snippets / commands entered and the output are highlighted in red.</p><h3><strong>Single File Java Program Execution without ‘javac’</strong></h3><p>Another cool trick introduced in Java 11 is that when we have a single file Java program, we do not have to compile and then run it. We can directly do the below:</p><pre><em>java MySingleFileApp.java</em></pre><p>There are a few changes to java file conventions. But beware; these apply only when we are “running java files directly”. When we compile and run, the usual rules apply.</p><ul><li>The file need not be suffixed with .java. We can simply use the below command to execute files which have java code. Notice the <em>— source </em>option. This is important when a file does not have a .java suffix.</li></ul><pre><em>java — source &lt;use any version since 11&gt; MySingleFileApp</em></pre><ul><li>The first class in the file has to contain the main method.</li><li>There can be any number of classes &amp; public classes in a file.</li><li>File name need not match the main class name.</li></ul><h3><strong>Java as Shell Script</strong></h3><p>Putting the above two features together, it is now possible to write shell scripts using Java language. One can write a script like below, name it <em>print-date</em>:</p><pre><em>#!/usr/bin/java --source 11<br>import java.time.LocalDateTime;<br>public class PrintDate {<br>  public static void main(String [] args) {<br>    System.out.println(LocalDateTime.now());<br>  }<br>}</em></pre><p>And execute using a command as below:</p><pre><em>chmod 755 print-date<br>./print-date</em></pre><p>In this series of articles, we looked at some of the major changes to the Java language in recent years. Many of these are aimed at making it more developer friendly and also to incorporate many features to bring it inline with other latest programming languages.</p><p>When combined with libraries and frameworks like Spring, Java is still an easy-to-develop programming language with support for almost any feature required for developing most kinds of applications, very good community support and documentation.</p><p>For those concerned about longer boot times and heavier runtime image size while developing microservices, frameworks like Micronaut, Quarkus etc. will provide blazing fast startup times and a small runtime footprint.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8161e281a0d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/java-recent-developments-8161e281a0d1">Java — Recent Developments</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Recent Developments]]></title>
            <link>https://medium.com/insights-from-thoughtclan/java-recent-developments-915da8bcb0c6?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/915da8bcb0c6</guid>
            <category><![CDATA[osgi]]></category>
            <category><![CDATA[modular-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Satheesh]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 07:57:47 GMT</pubDate>
            <atom:updated>2021-10-18T13:13:54.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Recent Developments</h3><h4><strong>Modules &amp; Leaner Runtime</strong></h4><p>In the last article on <a href="https://blogs.thoughtclan.com/java-recent-developments-14acca48f30">“Features to Enhance Developer Friendliness”</a>, I had explored some features introduced in recent versions of Java aimed at making Java more developer friendly.</p><p>In this article, let us see Java Platform Modules System (JPMS) and it’s aim of creating leaner runtime.</p><p>As part of Java 9, a major change happened within internal JRE library classes. That is the introduction of “Java Platform Modules System” (JPMS) and subsequent re-arranging of all Java internal packages as numerous modules. I say re-arranging because this is not a major refactoring of JRE classes but arranging those packages into relevant modules.</p><h3>Modules</h3><p>Modules help to:</p><ul><li>Maintain / segregate dependencies between various modules in an application and those between application modules and library modules.</li><li>Restrict access to internal APIs which should not be exposed to other modules.</li><li>When the same classes / packages are duplicated in the class path ( due to multiple versions of the same library being present or multiple libraries using same package / class names ), the right classes / packages to use is clearly defined during compile time itself. This avoids runtime uncertainties.</li><li>Control which modules can use ‘reflection’ to parse metadata of classes in a particular module.</li><li>Create leaner runtimes using <em>jlink</em> tool.</li></ul><p>One can think that Java already has access modifiers (public, private, protected, default) for encapsulation but there is still a gap wherein we can’t expose a class to all packages within a project while ensuring it cannot be accessed by classes outside the project. JPMS aims to bridge this gap.</p><p>To begin with, JRE libraries are already modularised as seen below. As can be seen, many straightforward web applications will need only a few of the modules. This provides the opportunity to build smaller application specific JRE and lighter JVM, as the required modules are known in compile time itself and rest can be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qjAmOhsEPXEgdIAnbke7g.png" /><figcaption>Modules in JRE</figcaption></figure><p>In our applications, we can enable this by following below steps. To begin with, the application modules need to be created as separate projects / multi-module projects.</p><ul><li>Each module / project should define a <em>module-info.java under src/main/java</em>. This should include the name of the module, its dependencies and what it exposes. Example:</li></ul><pre><em>module com.tc.black.javarevision.jpmslib {</em></pre><pre><em>    requires spring.context;<br>    requires spring.beans;</em></pre><pre><em>    exports com.tc.black.javarevision.jpmslib;<br>    exports com.tc.black.javarevision.jpmslib.external;<br>    exports com.tc.black.javarevision.jpmslib.internal to spring.beans;<br>    <br>    opens com.tc.black.javarevision.jpmslib to spring.core;<br>    opens com.tc.black.javarevision.jpmslib.external to spring.core;<br>    opens com.tc.black.javarevision.jpmslib.internal to spring.core;<br>}</em></pre><ul><li>The root project ( the one with the main method ) will also be defined as a module and this is the main module. With the above example, main module’s <em>module-info.java</em> will look like this:</li></ul><pre><em>module com.tc.black.javarevision.jpms {</em></pre><pre><em>    requires spring.boot;<br>    requires spring.boot.autoconfigure;<br>    requires spring.context; <br>    requires spring.web;<br>    requires spring.beans;<br>    requires transitive com.tc.black.javarevision.jpmslib;<br>    requires org.apache.tomcat.embed.core;<br>    <br>    exports com.tc.black.javarevision.jpms;<br>    exports com.tc.black.javarevision.jpms.controller;<br>    <br>    opens com.tc.black.javarevision.jpms to spring.core;<br>    opens com.tc.black.javarevision.jpms.controller to spring.core;<br>}</em></pre><ul><li>Another important aspect is that one JAR file can contain only one module.</li><li>Once this multi-module project is built and JAR files generated for all modules, application can be run with the below command:</li></ul><pre><em>java -module-path &lt;path to the module JARs including main module JAR&gt; --module com.tc.black.javarevision.jpms/JpmsApplication</em></pre><h3><strong>JLINK and Other Tools</strong></h3><p>Along with JPMS, below tools have been introduced which can aid in some related use cases.</p><ul><li><strong><em>jdeps</em></strong> — helps in analyzing the code base to identify module dependencies</li><li><strong><em>jdeprscan</em></strong> — helps in analyzing the code base for usage of any deprecated APIs</li><li><strong><em>jlink</em></strong> — helps in creating a smaller runtime by combining the application’s and the JDK’s modules</li><li><strong><em>jmod</em></strong> — helps in working with jmod files. jmod is a new format for packaging the modules. This format allows including native code, configuration files, and other data that do not fit into JAR files</li></ul><p>We can build a custom JRE with only the required modules for a JPMS multi-module application using the command below:</p><pre><em>./jlink --module-path &lt;path to the module JARs including main module JAR&gt; --add-modules &lt;main module name&gt; --output &lt;path where the custom JRE will be created&gt;</em></pre><h3>JPMS — Barriers for Usage</h3><p>JPMS and related tools are not used frequently even now though they were released as part of Java 9. There are a few reasons for that:</p><ul><li>A typical application project has a lot of third-party library dependencies and many of today’s most used libraries have not implemented the modules system. Such dependencies will be treated as “automatic modules”; such modules are accessible to all modules and they can access all other modules. This effectively nullifies the encapsulation advantage provided by JPMS.</li><li>One of the key features of JPMS is that it does not allow duplicate packages in a “modulepath”. While this is great for consistency, new project setup with many library dependencies is going to take time as we encounter duplicate packages and cases of multiple versions of the same library in the dependency graph very often.</li><li><em>jlink </em>is a cool feature in today’s microservices world. But there are many easier alternatives like Micronaut, Quarkus etc.</li></ul><p>In the next article in this series <a href="https://blogs.thoughtclan.com/java-recent-developments-8161e281a0d1">“Scripting &amp; Shell Introduction”</a>, I have explored some of the scripting features introduced in Java in recent versions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915da8bcb0c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/java-recent-developments-915da8bcb0c6">Java — Recent Developments</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Recent Developments]]></title>
            <link>https://medium.com/insights-from-thoughtclan/java-recent-developments-14acca48f30?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/14acca48f30</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[series-java-recent]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Satheesh]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 09:43:29 GMT</pubDate>
            <atom:updated>2021-09-07T08:00:09.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Recent Developments</h3><h4><strong>Features to Enhance Developer Friendliness</strong></h4><p>In the last article on <a href="https://blogs.thoughtclan.com/java-recent-developments-d1c9cc15ef87">“Java — Incorporation of Functional Programming Concepts”</a>, I had explored the functional programming features introduced in Java 8 and above.</p><p>In this article, let me explore some other features introduced in recent versions of Java aimed at making Java more developer friendly. Many improvements have been made including fixing some of the standout issues.</p><h3><strong>Text Blocks</strong></h3><p>Java 14 introduced text blocks which eases initialisation with a multi-line string. This is done by enclosing the multi-line string within “”” and “””.</p><pre><em>var html  = &quot;&quot;&quot;<br>    &lt;html&gt;<br>     &lt;head&gt;<br>      &lt;title&gt;This is a HTML snippet&lt;/title&gt;<br>     &lt;/head&gt;<br>     &lt;body&gt;<br>     &lt;/body&gt;<br>    &lt;/html&gt;<br>  &quot;&quot;&quot;;</em></pre><h3><strong>Switch Expressions</strong></h3><p>Switch Expressions were introduced with Java 14; older switch statements were always a pain to write and maintain and the newer version aims to fix those issues, mainly:</p><ul><li>We do not have to write <em>break </em>statements in each case, as the new switch expression does not fall through like the earlier version.</li><li>A new keyword <em>yield </em>has been introduced which can be used to return a value at the end of multi-line case blocks.</li><li>Single line case blocks can use the lambda notation <em>‘-&gt;’</em> to return value immediately.</li><li>Switch expressions are treated as “expressions” and can be used in all places where an expression can be used e.g., can be passed as input to a function call and can be returned as output.</li></ul><p>Below is an example switch statement depicting all the above features.</p><pre><em>var s = &quot;foo&quot;;<br>System.out.println( switch (s) {<br>    case &quot;foo&quot;, &quot;bar&quot; -&gt; {<br>        System.out.println( &quot;Can execute some logic here.&quot; );<br>        yield 2;<br>    }<br>    default -&gt; 3;<br>} );</em></pre><h3><strong>Records</strong></h3><p>Java 16 has introduced the ability to define <em>“record” </em>classes which can be used to define POJOs. Following is an example:</p><pre><em>record Mark(Integer studentId, Long mark) {};</em></pre><p>Following rules are applied automatically:</p><ul><li>All fields declared above are private and final.</li><li>A canonical constructor is automatically defined considering the fields defined above.</li><li>Similarly, <em>toString, equals and hashCode</em> methods too are defined considering all the fields defined above. They can be overridden to provide custom logic.</li><li>Records themselves cannot extend from other classes, are final and can’t be abstract.</li><li>Getters generated for all fields.</li></ul><p>This may not be all that interesting for developers who are used to tools like <em>Project Lombok</em> which do this and more. What makes it interesting is that records can be declared directly as local variables. This will come in handy when we need a data carrier but in only one method; avoids having to create a java file just for this.</p><pre>public void myComplexMethod() {<br>    // do something</pre><pre>    // declare record as local variable<br>    record Mark(Integer studentId, Long mark) {};</pre><pre>    // use it<br>    final Mark mark = new Mark(student.id(), 50L);</pre><pre>    // do something<br>}</pre><h3><strong>Pattern Matching for ‘instanceof’</strong></h3><p>One of the other annoying things was that we had to do class cast for an object even when we have used <em>instanceof </em>to check if the object is of a certain class. This is not required anymore since Java 16. One can do this like below:</p><pre><em>if (obj instanceof String s &amp;&amp; s.length() &gt; 5) {<br>  // use s directly as string<br>}</em></pre><p>Notice that along with <em>instanceof, </em>we are able to assign it to a variable and use it thereafter in the rest of the <em>if</em> condition and within the if block.</p><p>When we have the below statement, the variable will be available after the if block and not within the if block. This is because the if condition is negative; note that the if block should have returned from the method or thrown an exception.</p><pre><em>if (!(obj instanceof String s)) { <br>    throw new IllegalArgumentException(); // or return something; <br>}<br>// s is in scope - because instanceof was able to cast the object to string<br>// in case if it was not able to and condition fails above, the execution will not reach here as the if block throws an exception</em></pre><h3><strong>‘var’ Keyword</strong></h3><p>‘var’ keyword is used in JavaScript and Kotlin to declare a variable. Java introduced this keyword for usage with method local variables, as part of Java 10. This helps in avoiding having to write longer lines / duplicating classnames when we declare and initialize a new object. E.g.,</p><pre><em>List&lt;String&gt; values = new ArrayList&lt;&gt;(); </em>can be now written as<em> var values = new ArrayList&lt;String&gt;();</em></pre><p>But unlike JavaScript, the type of a variable cannot change after the initial declaration and initialization. Java is still a statically typed language.</p><h3><strong>Private Methods in Interfaces</strong></h3><p>While Java 8 introduced default methods in interfaces, Java 9 introduced private methods. This is very useful if we want to reuse logic across different default methods in an interface.</p><h3><strong>Factory Methods for Initialising Collections</strong></h3><p>In Java 9, Factory methods were introduced in the Collections framework to ease initialisation with constant values. E.g.,</p><pre><em>List.of(“1”, “2”, “3”)</em></pre><p>Earlier we had to initialise an empty list and add values one by one or initialise an array and convert to a list.</p><p>Above are some enhancements done to the language syntax to improve ease of use for developers. In the next article in this series <a href="https://blogs.thoughtclan.com/java-recent-developments-915da8bcb0c6">“Modules &amp; Leaner Runtime”</a>, I have explored Java Platform Modules System (JPMS).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14acca48f30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/java-recent-developments-14acca48f30">Java — Recent Developments</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java — Recent Developments]]></title>
            <link>https://medium.com/insights-from-thoughtclan/java-recent-developments-d1c9cc15ef87?source=rss----1c117f23c8b2---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1c9cc15ef87</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[series-java-recent]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Satheesh]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 04:59:56 GMT</pubDate>
            <atom:updated>2021-09-02T09:49:30.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java — Recent Developments</h3><h4>Incorporation of Functional Programming Concepts</h4><figure><img alt="Function — An expression which converts a set of inputs into an output" src="https://cdn-images-1.medium.com/max/1024/0*ugIs1XE2rOjHCtO0" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Java has been an important programming language for developers over the past two decades. Still one of the most used languages, it powers countless applications including web and mobile applications, middleware, APIs, media streaming applications etc.</p><p>In the past decade, many new languages have been developed, some of which have gained mainstream recognition and usage. Interestingly, some JVM based languages like Kotlin, Scala etc. too have become widely used.</p><p>Oracle &amp; Java core development team have been constantly developing the language to ensure that the language provides features required for developing modern applications and maintains its market share in the future.</p><p>In this article, we will focus on one of the main themes in how Java has evolved since Java 8 i.e., Functional Programming Concepts being introduced in Java.</p><p>One of the first things we learn as Java developers is that Java is an object oriented programming language. Java version 8 made some major changes to introduce basic functional programming concepts to Java; this is one of the major themes in how Java is evolving. While Java still remains statically typed and object oriented (Objects are first class citizens in Java and not functions), many functional style features have been added since version 8 onwards.</p><p><strong>Functional Interfaces</strong></p><p>Functional interfaces are interfaces which have <em>“exactly one abstract method”</em>. Java 8 introduced many functional interfaces and updated many existing interfaces which fulfils the above criteria as <em>@FunctionalInterface</em>.</p><p>Although functional interfaces are not a core functional programming concept, they enable others like function composition &amp; functions which behave like first-class / higher-order functions. Also, developers can define new functional interfaces as part of their project by using <em>@FunctionalInterface </em>annotation.</p><p><strong>‘Default’ Methods in Interfaces</strong></p><p>Java 8 also introduced the ability to have default non-abstract methods in interfaces. Until then it was not possible to have non-abstract methods in interfaces.</p><p>Like the above, this has enabled the possibility of function composition. Default methods like <em>or, and and negate from java.util.function.Predicate </em>interface or <em>compose and andThen from java.util.function.Function</em> interface allow passing on results of one function to the next and so on to perform a flow as a chain of function calls.</p><p><strong>Lambda Expressions</strong></p><p>Lambda expressions provide a concise way to represent / implement a “single method interface” using an expression. If we have a functional interface and we want to implement it, instead of doing the below,</p><pre><em>Comparator&lt;Student&gt; compareByAge = new Comparator&lt;Student&gt;() {<br>  </em><a href="http://twitter.com/Override"><em>@Override</em></a><em><br>  public int compare(Student s1, Student s2) {<br>    return Integer.compare(s1.getAge(), s2.getAge());<br>  }<br>};</em></pre><p>we can simply write the implementation as a lambda expression which is more concise and understandable.</p><pre><em>Comparator&lt;Student&gt; compareByAge = (s1, s2) -&gt;<br>  Integer.compare(s1.getAge(), s2.getAge());</em></pre><p><strong>Method References</strong></p><p>Method References is a syntactical update for calling static / instance methods in a precise manner without having to explicitly write the parameter to be passed while calling. Compiler automatically infers the parameter to be passed to the methods.</p><p>Let’s see an example below. It has a lambda expression which prints every element in a list.</p><pre><em>var numbers = Arrays.asList(11, 12, 25);<br>numbers.stream().forEach( item -&gt; System.out.println( item ) );</em></pre><p>Using method references, it can be written as below. You will notice that there is no parameter given for <em>println</em>. This is auto-inferred by the compiler based upon what is passed on from each of the <em>forEach</em> iteration.</p><pre><em>var numbers = Arrays.asList(11, 12, 25);<br>numbers.stream().forEach( System.out::println );</em></pre><p><strong>Streams</strong></p><p>The features described so far in this section like functional interfaces, lambda expressions, method references, default methods culminate in the bigger feature “Streams<em>”</em> which enables us to perform functional-style operations on a stream of elements like an array, collection, lines of files, records from database etc.</p><p>Let’s see an example below. This loops through a list and prints them one by one.</p><pre><em>var numbers = Arrays.asList(11, 12, 25);<br>for(final Integer item: numbers) {<br>  System.out.println(item);<br>}</em></pre><p>With streams, this can be written in a much more precise way as below.</p><pre><em>var numbers = Arrays.asList(11, 12, 25);<br>numbers.stream().forEach( System.out::println );</em></pre><p>We can build much more complex transformations using these features. Below are two examples: the first one takes a list of strings and returns a list of each of their lengths and the second one takes a list of strings, flattens by splitting each of the strings to characters and returns the flattened list.</p><pre><em>var numbersAsWords = Arrays.asList( &quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot; );<br>var eachStringLength = numbersAsWords.stream()<br>    .map(String::length).toList();<br>System.out.println(eachStringLength);<br>var numbersGrouped = Arrays.asList(&quot;123&quot;, &quot;456&quot;, &quot;789&quot;, &quot;0&quot;);<br>var numbersSplit = numbersGrouped.stream()<br>    .mapMulti((item, downstream) -&gt; {<br>      Arrays.asList(item.split(&quot;&quot;)).forEach(downstream::accept);<br>    })<br>    .toList();<br>System.out.println(numbersSplit);</em></pre><p>Streams also support parallel execution. When we use <em>parallelStream() instead of stream()</em> in the above code snippets, the items will be processed in parallel instead of being processed sequentially.</p><p>It has to be stressed that while all these features enable “functional style” programming, they are not purely functional. Java treats lambda expressions as objects internally. So, what we have seen in this section provides syntactical ease, developer friendliness and performance; but not pure functional style programming.</p><p>While Java has introduced quite a few functional programming concepts, it does not cover other important concepts like pure functions, immutability, tail recursion etc. Considering this and the aforementioned points, one cannot use Java as a pure functional programming language or consider it for any new functional programming development. But these features allow us to write precise and performant code using functional programming constructs when we are upgrading an existing Java application or developing new applications within a Java application landscape.</p><p>In the next article in this series <a href="https://blogs.thoughtclan.com/java-recent-developments-14acca48f30">“Features to Enhance Developer Friendliness”,</a> I have highlighted some other features introduced in recent versions of Java aimed at making Java more developer friendly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c9cc15ef87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insights-from-thoughtclan/java-recent-developments-d1c9cc15ef87">Java — Recent Developments</a> was originally published in <a href="https://medium.com/insights-from-thoughtclan">Insights from ThoughtClan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>