<?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[Vedity - Medium]]></title>
        <description><![CDATA[Vedity Software is Industry-leading service providers for Data Science, Data Engineering, and Full-Stack Application development. We build the product you envision. - Medium]]></description>
        <link>https://medium.com/vedity?source=rss----27a6213cb450---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Vedity - Medium</title>
            <link>https://medium.com/vedity?source=rss----27a6213cb450---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:00:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/vedity" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Display Dynamic Html and CSS to Angular Component]]></title>
            <link>https://medium.com/vedity/display-dynamic-html-and-css-to-angular-component-fdc29fe85bd2?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/fdc29fe85bd2</guid>
            <dc:creator><![CDATA[Pinkal Patel]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 05:39:24 GMT</pubDate>
            <atom:updated>2022-09-22T05:39:24.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ud1wfnAiIoCZYwlGhBBS6A.png" /></figure><p>This blog is about how can we display Html and CSS received from server side. This is helpful while we display dynamic Html and CSS to component page. This html does not include any events.</p><p>Let’s start. First I am creating node server to create API which will return Html and CSS data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1023a1e9609647d2b43cfd1fee63e336/href">https://medium.com/media/1023a1e9609647d2b43cfd1fee63e336/href</a></iframe><p>I created app.js file with /getPage API which reads the html and css file from server and return the data to frontend.</p><p>Now we will create Angular Application using ng new application-name command. We are going to bind html using innerHtml attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7897eed687912cc1297fd93274cfa0a/href">https://medium.com/media/b7897eed687912cc1297fd93274cfa0a/href</a></iframe><p>Create service to call API to get data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2381f30dac34298e4cf53333959cb0b/href">https://medium.com/media/f2381f30dac34298e4cf53333959cb0b/href</a></iframe><p>Html can bind to component using innerhtml but css can’t bind directly. We need to append new style element using Renderer2 package of angular.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655a0be6355ace56ed6621d5a1f4db7d/href">https://medium.com/media/655a0be6355ace56ed6621d5a1f4db7d/href</a></iframe><p>After this start node server and run angular application using ng serve command. It will display design and content received from server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB0XLSWoao3IPUy91aBRpQ.png" /></figure><p>So, by using innerHtml attribute and Renderer2 package of angular we can make component dynamic. Whatever Html and CSS content received from server is displayed in that component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc29fe85bd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/display-dynamic-html-and-css-to-angular-component-fdc29fe85bd2">Display Dynamic Html and CSS to Angular Component</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discovering Life journey — the Agile way]]></title>
            <link>https://medium.com/vedity/discovering-life-journey-the-agile-way-f963bb10b2a?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/f963bb10b2a</guid>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[project-management-tips]]></category>
            <category><![CDATA[agile-methodology]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Nirali Narayan]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 12:37:50 GMT</pubDate>
            <atom:updated>2022-06-13T12:37:20.146Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discovering Life journey — the Agile way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hm4gbFUEqFpDoraYNsOJcA.png" /></figure><p>Heard of the buzzword ‘Agile’ ? Is it just a Software delivery approach ?</p><p>Today almost every industry has turned to Agile approach for product delivery.</p><p>Well, I believe Agile is not just a professional approach but can also be applied for our personal lifestyles. Or may I say we have been unknowingly following it through ages.</p><p>My point of view — Live Life ‘Agile’ size</p><p>I have always liked keeping todo lists, do all the planning and executing according to plans. So unknowingly I also had my life choices planned out. Everyone wants to create a career path that fits with their passion and allows them to grow. Obviously my life didn&#39;t work out as I had planned for it.</p><p>Certainly, I understood that my life is so like a product that follows Agile methodology and not waterfall methodology where end goal is fixed from start.</p><p>So what is Agile way of life?</p><p>To be able to understand Agile, you have to restrain your instinctive control-minded and process-driven way of looking at things.</p><p><strong>Agile is to have a growth Mindset</strong></p><p>We all have some life goals but one cannot control how our life events will take place. But to reach the goal, we need to be consistent.</p><p>But how do we stay consistent? Well new way to organise work is using the power of analysis, processes and empiricism. This results in growth mindset which is the belief that intelligence is not fixed but can be developed and understanding that learning is our greatest gift.</p><p>We also have to embrace the fact that people are unpredictable and can make mistakes. And we are never gonna reach our life’s goal without failures. Yet, we allow ourselves to take control and deal with the challenges. This will bring great results.</p><p>Like in softwares, not asserting the outcome in advance, but smartly getting things ‘done’ by constantly improving upon it.</p><p><strong>Agile is about people</strong></p><p>How do you grow constantly ? One of the approach is by getting people’s feedbacks and also giving your point of views to others(that wil also help you to grow unknowingly). Growth is about helping each other.</p><p>One must start by observing, talking to people, understanding their patterns. Also one must start inspecting their choices from feedbacks. Also Inspection enables adaptation.</p><p>Agile is about people, and more specifically, about encouraging people. We need to focus on the end product while leaving the ‘hows’ to people. Thats why agile manifesto focuses on results over control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsLtoOaQFB3e6Yb_p4cOOQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mrsunflower94?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matteo Vistocco</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Agile is about Innovation</strong></p><p>Today world has evolved and technology is booming. Innovation has been the single driving force for evaluation of mankind. The desire for constantly searching for new ideas has lead to unbelievable evolution of Earth and mankind. Today , there are so many new industries and jobs. Man has so many new life choices to make.</p><p>Agile is about innovating new ideas and not sticking to the originals. We explore, we experiment, we innovate. Thats how we constantly improve. Reaching to the end is important, we do not necessarily need to follow traditional routes .</p><p>In Conclusion, it is up-to us whether we want to follow waterfall model or Agile model. But in order to not hit the dead-ends, I have definitely started having Agile transformation in my life. It has impacted and helped me achieve success till now. What about yours?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f963bb10b2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/discovering-life-journey-the-agile-way-f963bb10b2a">Discovering Life journey — the Agile way</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adopt HOC Pattern to Improve Code Reusability in React]]></title>
            <link>https://medium.com/vedity/adopt-hoc-pattern-to-improve-code-reusability-in-react-72107e0f5cef?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/72107e0f5cef</guid>
            <dc:creator><![CDATA[Amitparmar Dev]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 10:32:44 GMT</pubDate>
            <atom:updated>2022-06-09T10:32:44.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*aWALXjv_iYA3Ao_GbJ94gw.png" /></figure><p>This article will give you a better understanding of how higher-order components work and how you can use them to achieve code reusability in React. Well, this article requires a basic to intermediate level of knowledge about React. Read my two recent articles on <a href="https://medium.com/vedity/how-do-components-interact-with-each-other-in-react-4c06a256949b">component communication</a> and <a href="https://medium.com/vedity/all-you-needs-to-know-about-virtual-dom-996626da34ab">virtual-dom</a> on medium to understand React fundamentals.</p><p><strong>Code Reusability</strong> is a very old book tactic to achieve maximum by writing a minimalistic line of code. In other words, you can use an existing piece of code to develop new functionality. But in order to reuse code, you have to write high-quality code.</p><p>In React, components are the building blocks of the application. In other words, They are the primary unit of code reuse in React. The application logic is elegantly coupled with components in React. To achieve a greater degree of reusability in React application, you have to find a way to disassemble the fine-grained logic (state logic, event-based logic, etc.) as a reusable block of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwrD4vqKj_g1ungBfsPq0w.png" /></figure><p>A <strong>higher-order component (HOC)</strong> is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.</p><p>A Higher-Order Component (HOC) is a function that takes a component as input and returns a new component as output with some additional logic.</p><p>The concept of HOC is similar to the concept of higher-order functions in JavaScript. A higher-order function is a function that takes one or more functions as arguments or returns a function. Example of higher-order functions are various array methods introduced in ES6 like .map() and .filter() etc. These methods take a function as an input to iterate over the array.</p><p>Let’s write step-by-step code to implement a HOC and understand how it improves the code reusability in React.</p><p>To understand the use of HOC, first, we will implement a scenario where we will fetch various resources from one of the free online REST APIs. Here I am using <a href="https://jsonplaceholder.typicode.com/"><strong>JSONPlaceholder</strong></a><strong> </strong>free REST API to demonstrate the HOC concept.</p><p>We are going to fetch posts and comments resources using GetPosts.js and GetComments.js respectively without using HOC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*2hQf5ZJFkr7N_tFWijyWLQ.png" /><figcaption>GetPosts.js</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Dfy89W-MiePuDEJ1GhyAAg.png" /><figcaption>GetComments.js</figcaption></figure><p>The above two files are fetching different resources from <strong>JSONPlaceholder </strong>free REST API. Both files are very identical in structure. Here we are fetching arrays of posts and comments and updating the state of the component which is passed as props to render in UI Components.</p><p>We can implement one higher-order component <em>fetchWrapper.js</em> here which will be reused to fetch any resource from the above-used API. This higher-order component will take a Wrapped Component as input and one more argument as a name of the resource to fetch. According to the resource name given in the argument, we will fetch the requested resource. Once the resource is successfully fetched from API, we will pass it as props to Wrapped Component as we have discussed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*VkgU67bRQAqo3OkTABJoPA.png" /><figcaption>fetchWrapper.js</figcaption></figure><p>Refer <em>fetchWrapper.js</em> file, <strong>fetchWrapper </strong>is the higher-order component in the above code snippet. It takes <strong>WrappedCompoent </strong>as input and it will be returned with the fetched resources as props. Here the first parameter of <strong>fetchWrapper </strong>is the wrapped component. The second parameter is the resource that we want to retrieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*A0A4CN_m3OxQ988tY4U_5w.png" /><figcaption>GetPostsWithHOC.js</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*C-AJDKahaoxhoA4xJURsnA.png" /><figcaption>GetCommentsWithHOC.js</figcaption></figure><p>In the above code snippet, <em>GetPostsWithHOC.js</em> and <em>GetCommentsWithHOC.js</em> are modified to use HOC fetchWrapper. When GetPosts and GetComments components get rendered, fetchWrapper HOC will call the respective APIs and they will get posts or comments array as data props retrieved from JSONPlaceholder API. To get these data props, we need to wrap the component in fetchWrapper HOC.</p><p>As you have noticed here, the HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC <em>composes</em> the original component by <em>wrapping</em> it in a container component. The HOC fetchWrapper is the regular javascript function where you can add as many arguments as you like. In other words, if you want to add more functionality to the existing components, you can add more functionality without modifying the actual component. Many popular JavaScript libraries use HOC to enhance code reusability i.e. Redux.</p><h4>Summary</h4><p>HOCs can add additional features to a component without modifying it. It’s expected that the component returned from a HOC has a similar interface to the wrapped component. HOC pattern is the most efficient way to have code reusability in React. If you see the repetition of your code in a project, there might be a chance to move it to a HOC. So adopt HOC to improve reusability in React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72107e0f5cef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/adopt-hoc-pattern-to-improve-code-reusability-in-react-72107e0f5cef">Adopt HOC Pattern to Improve Code Reusability in React</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correlation ID — Microservices]]></title>
            <link>https://medium.com/vedity/correlation-id-microservices-dd55cfd1a957?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd55cfd1a957</guid>
            <dc:creator><![CDATA[Khushboo patel]]></dc:creator>
            <pubDate>Tue, 17 May 2022 11:01:38 GMT</pubDate>
            <atom:updated>2022-05-17T11:01:38.076Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Correlation ID — Microservices</strong></h3><p>Microservices architecture has many advantages over monolithic architecture, however, there is one disadvantage that I observed that microservices architecture has over monolithic, is tracking down the issue/errors in production.</p><p>In my past company, we had one production issue where one of the prospects’ data was not able to process properly through the final step, in spite of passing all the validation and checks.</p><p>Our system was comprised of 15 microservices. so, all the leads and teams of microservices(including the platform team) had to go through one whole day of a working session to identify the service for which the data processing was failing because none of the services was consistently logging or sending the prospects ID or any other unique id. So, we started exploring some random ID which should be passed and tracked with each request/response with each communication within microservices and there we found the concept of <strong>Correlation ID</strong>(sometimes it is referred to as Transaction ID or Transit ID).</p><blockquote><strong>“Correlation ID is a unique identifier value that is attached to requests and messages that allow reference to a particular transaction or event chain.”</strong></blockquote><p>Here’s the following diagram which we followed in our architecture to track this unique id :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*5TE-tYKj9-eVSR11hxkIMg.png" /><figcaption>Correlation-id tracking flow</figcaption></figure><p>In this blog, we will be exploring how we can implement correlation ID in Java with <a href="https://www.baeldung.com/mdc-in-log4j-2-logback">MDC</a> (Mapped Diagnostic Context) and PHP (Larvel).</p><p>Let&#39;s first explore how we can implement Correlation ID in Java with HTTPFilter and with AOP(Aspect-oriented programming).</p><p>Maven dependency :</p><pre>&lt;!-- logback dependency (MDC) --&gt;</pre><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;<br>  &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;<br>  &lt;version&gt;1.2.3&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.logz.logback&lt;/groupId&gt;<br>  &lt;artifactId&gt;logzio-logback-appender&lt;/artifactId&gt;<br>  &lt;version&gt;1.0.24&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Create a bean and with a static variable CORRELATION_ID_HEADER to set and get the to/from the request.</p><p><strong>RequestCorrelation.java</strong></p><pre>public class RequestCorrelation {<br>  public static final String CORRELATION_ID_HEADER = &quot;correlation-Id&quot;;<br>  private static final ThreadLocal&lt;String&gt; id = new ThreadLocal&lt;&gt;();</pre><pre>  public static String getId() {<br>    return id.get();<br>  }</pre><pre>  public static void setId(String correlationId) {<br>    id.set(correlationId);<br>  }<br>}</pre><p>In the CorrelationHeaderFilter.java, we will capture the request in the doFilter() method and checks for the presence of the correlation-id. If it exist we will add it in MDC logs and if not, generate a new unique id for outgoing requests.</p><p><strong>CorrelationHeaderFilter.java</strong></p><pre>package com.bills.fdr.file.readiness.filter;</pre><pre>import java.io.IOException;<br>import java.util.UUID;<br>import javax.servlet.DispatcherType;<br>import javax.servlet.Filter;<br>import javax.servlet.FilterChain;<br>import javax.servlet.ServletException;<br>import javax.servlet.ServletRequest;<br>import javax.servlet.ServletResponse;<br>import javax.servlet.http.HttpServletRequest;<br>import org.apache.commons.lang3.StringUtils;<br>import org.jboss.logging.MDC;<br>import org.springframework.core.annotation.Order;<br>import org.springframework.stereotype.Component;<br>import lombok.extern.slf4j.Slf4j;</pre><pre>@Component<br>@Order(1)<br>@Slf4j<br>public class CorrelationHeaderFilter implements Filter {</pre><pre>@Override</pre><pre> public void doFilter(ServletRequest servletRequest, ServletResponse     servletResponse, FilterChain filterChain)throws IOException, ServletException {</pre><pre>  final HttpServletRequest httpServletRequest = (HttpServletRequest)   servletRequest;</pre><pre>  String currentCorrId = httpServletRequest.getHeader(RequestCorrelation.CORRELATION_ID_HEADER);</pre><pre>try {<br>  String uri = httpServletRequest.getRequestURI();<br>  if (StringUtils.isEmpty(currentCorrId)) <br>  {<br>     currentCorrId = UUID.randomUUID().toString();<br>     log.info(&quot;No correlationId found in Header. Generated : &quot; + currentCorrId);<br>  } <br>  else <br>  {<br>     log.info(&quot;Found correlationId in Header : &quot; + currentCorrId);<br>  }<br>  RequestCorrelation.setId(currentCorrId);<br>  MDC.put(RequestCorrelation.CORRELATION_ID_HEADER, currentCorrId);<br>  filterChain.doFilter(httpServletRequest, servletResponse);<br> }finally <br> {<br>    MDC.remove(RequestCorrelation.CORRELATION_ID_HEADER);<br> }<br>}</pre><pre>private boolean currentRequestIsAsyncDispatcher(HttpServletRequest httpServletRequest) {<br>   return httpServletRequest.getDispatcherType().equals(DispatcherType.ASYNC);<br>}<br>}</pre><p>Note : Here <strong>currentRequestIsAsyncDispatcher() </strong>is here to check for any asynchronous request in filter. If there is any asynch request, then we need to handle the request little differently.</p><p><strong>For each outgoing call :</strong></p><pre>HttpHeaders httpHeaders = new HttpHeaders();</pre><pre>httpHeaders.set(RequestCorrelation.CORRELATION_ID_HEADER,RequestCorrelation.getId());</pre><p>We can also use AOP(Aspect oriented programming) to implement Correlation ID.So, Whenever there is any outgoing call to other service we can use @Before/@After aspects to log correlation ID with MDC.</p><pre>import <em>org</em>.<em>aspectj</em>.<em>lang</em>.<em>JoinPoint</em>;<br>import <em>org</em>.<em>aspectj</em>.<em>lang</em>.<em>annotation</em>.<em>After</em>;<br>import <em>org</em>.<em>aspectj</em>.<em>lang</em>.<em>annotation</em>.<em>Aspect</em>;<br>import <em>org</em>.<em>aspectj</em>.<em>lang</em>.<em>annotation</em>.<em>Before</em>;<br>import <em>org</em>.<em>slf4j</em>.<em>MDC</em>;<br>import <em>org</em>.<em>springframework</em>.<em>context</em>.<em>annotation</em>.<em>Configuration</em>;</pre><pre>import <em>java</em>.<em>util</em>.<em>UUID</em>;</pre><pre>@Aspect<br>@Configuration</pre><pre><strong>public class </strong>CorelationIdAspect {</pre><pre><strong>private static final String </strong>CORRELATION_ID = &quot;Correlation-Id&quot;;</pre><pre>@Before(value = &quot;execution(*com.example.restTemplateUtil.exchange(..))&quot;)<br><strong>public void </strong>before(JoinPoint joinPoint) {<br>   <strong>final String </strong>correlationId = <em>generateUniqueCorrelationId</em>();<br>   <em>MDC</em>.<em>put</em>(<em>CORRELATION_ID</em>, <em>correlationId</em>);<br>}</pre><pre>@After(value = <br>&quot;execution(* com.example.restTemplateUtil.exchange(..))&quot;)<br><strong>public void </strong>afterReturning(JoinPoint joinPoint) {<br>   MDC.remove(CORRELATION_ID);<br>}</pre><pre><strong>private String </strong>generateUniqueCorrelationId() {<br>   <strong>return </strong>UUID.randomUUID().toString();<br>}<br>}</pre><p>The benefit of using the Filter or AOP for correlation id tracking is that, it completely separates logging/tracking from your business logic.You can also use interceptor (like HandlerInterceptorAdapter) to capture correlation id from request.</p><p>For logging purpose using MDC,please don’t forgot to configure logback-spring.xml file to print the correlation id in the logs as below :</p><pre>&lt;pattern&gt;%d{dd-MM-yyyy HH:mm:ss.SSS} %thread %X{correlationId} [%-5level] %class{0} - %msg%n&lt;/pattern&gt;</pre><h3><strong>Lets explore PHP (Larvel) implementation of Correlation ID:</strong></h3><p>Create and register a middleware class for correlation ID.</p><pre>class Kernel extends HttpKernel</pre><pre>{</pre><pre>.......</pre><pre>&#39;api&#39; =&gt; [&#39;correlationId&#39; =&gt; \App\Http\Middleware\CorrelationId::class</pre><pre>....]</pre><pre>........</pre><pre>}</pre><p>Create CorrelationID middleware :</p><pre>class CorrelationId<br>{<br>   public function handle(Request $request, Closure $next, string    ...$authorizedRoles)<br>{<br>   $rci = new RequestCorrelationId();<br>   if (!$request) {<br>    return;<br>   }<br>   $correlationId = $request-&gt;headers-&gt;get(&#39;correlation-Id&#39;);<br>   if (empty($correlationId)) {<br>      $correlationId = $this-&gt;generateCorrelationId($request);<br>   }<br>   $rci-&gt;setCorrelationId($correlationId);<br>   Log::withContext([<br>      &#39;$correlation-id&#39; =&gt; $correlationId<br>   ]);<br>  return $next($request)-&gt;header(&#39;correlation-Id&#39;, $correlationId);<br>}</pre><pre>  public function generateCorrelationId(Request $request)<br>  {<br>    return Str::uuid()-&gt;toString();<br>  }<br>}</pre><pre>&lt;?php<br>namespace App;<br>class RequestCorrelationId<br>{<br>   public static $CORRELATION_ID;<br>   public function __construct() {<br>   }<br>   public function getCorrelationId(){<br>     return self::$CORRELATION_ID;<br>   }<br>   public function setCorrelationId($id)<br>   {<br>    self::$CORRELATION_ID = $id;<br>   }<br>}</pre><p><strong>Why to generate and log another ID ?</strong></p><p>A question will come in to your mind that we can simply track/log any existing unique identifier/id, why to generate and track a new unique id.<br>Yes you can use that, but there are two problems :one, sometimes existing unique ids are critical and it is not secure to expose them in logs.<br>Second, not all microservices of a system works on the same unique id.<br>So, it is better to generate and log a new unique id, which is not related to any business logic and whose sole purpose is to be passed in every request and to be logged with every log entry.</p><p>I hope this blog will help you in tracking and debugging the issues in your project with correlation id in future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd55cfd1a957" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/correlation-id-microservices-dd55cfd1a957">Correlation ID — Microservices</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Testing with WireMock]]></title>
            <link>https://medium.com/vedity/integration-testing-with-wiremock-36165f253c1b?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/36165f253c1b</guid>
            <dc:creator><![CDATA[Khushboo patel]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 09:59:34 GMT</pubDate>
            <atom:updated>2022-04-22T09:59:34.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is integration testing?</h3><p>Integration testing is a phase of software testing where each module of software is combined together and tested as a group. The whole aim of this phase is to identify potential issues in the communication between different modules of the software.</p><p>In the current Microservices architecture, where each microservice has a very definite set of responsibilities and together with communication with each other they achieve a goal of a system. So, a microservice alone is not operational. For example, In an Online shopping system, an order service will talk to catalogue service for items. Catalogue service, in turn, will call inventory service and according to the response from inventory service order service will talk to payment service. So, what if the catalogue service is still underdeveloped or not available for testing. Should we wait till all the services are ready? Absolutely not.</p><p>How can we write test case for a service without the presence of the dependent service? And there comes “Mocking the services”.So, order service can consume the mock of catalog service as if real service, with the use <strong>WireMock.</strong></p><h3>Wiremock</h3><p>WireMock is a simulator for HTTP-based APIs.It constructs a HTTP server that we could connect to as we would to an actual web service. It provides a library that helps in stubbing and mocking webservices just like we mock business objects,database objects, HTTP objects etc. in unit testing with various available Mock frameworks (Mockito, PowerMock etc.). Let&#39;s start and explore how we can use it with spring boot.</p><h4><strong>Wiremock with Spring boot</strong></h4><p>Created two services: Employee Service and EmployeeCalculation service(ECS). So, for the calculation of each employee’s salary Employee service will communicate with the EmployeeCalculation service. ECS has the business logic to calculate the salary based on the Employee’s grade.</p><p>Maven Dependency :</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;com.github.tomakehurst&lt;/groupId&gt;<br>&lt;artifactId&gt;wiremock-standalone&lt;/artifactId&gt;<br>&lt;version&gt;2.6.0&lt;/version&gt;<br>&lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>DemoApplication.java</p><pre>@SpringBootApplication<br><strong>public</strong> <strong>class</strong> DemoApplication {<br>   <strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {<br>     SpringApplication.<em>run</em>(DemoApplication.<strong>class</strong>, args);<br>}<br>@Bean<br><strong>public</strong> RestTemplate restTemplate() {<br>   <strong>return</strong> <strong>new</strong> RestTemplate();<br> }<br>}</pre><p>EmployeeController.java</p><pre><br>@RestController<br>@RequestMapping(path = “/v1”)</pre><pre><strong>public</strong> <strong>class</strong> EmployeeController {</pre><pre>@Autowired<br><strong>private</strong> EmployeeService employeeService;<br><strong>private</strong> String commonURI = “/v1”;</pre><pre><strong>......<br>......<br>.......</strong></pre><pre>@GetMapping(“/employee/salary/{id}”)<br><strong>public</strong> String getEmployeeSalary(@PathVariable String id) {<br>    <strong>return</strong> employeeService.getEmployeeSalary(id, commonURI + “/employee/salary/”);<br>}<br>}</pre><p>EmployeeService.java :</p><pre><strong>public</strong> <strong>interface</strong> EmployeeService {</pre><pre>  Employee getEmployeeById(String id,String uri);<br>  List&lt;Employee&gt; getAllEmployees();<br>  <strong>void</strong> createEmployee(Employee employee);<br>  String getEmployeeSalary(String id, String uri);<br>}</pre><p>EmployeeServiceImpl.java</p><pre>@Service</pre><pre><strong>public</strong> <strong>class</strong> EmployeeServiceImpl <strong>implements</strong> EmployeeService {</pre><pre>@Autowired<br><strong>private</strong> EmployeeRepository employeeRepository;</pre><pre>@Autowired<br><strong>private</strong> RestTemplate restTemplate;</pre><pre><strong>private</strong> String empServiceURI=”/v1/employee/salary/”;</pre><pre><strong>private</strong> String empSalaryServiceURL = “http://localhost:8888&quot;;</pre><pre>.....</pre><pre>@Override</pre><pre><strong>public</strong> String getEmployeeSalary(String id,String uri) {</pre><pre>  ResponseEntity&lt;String&gt; response =   restTemplate.exchange(empSalaryServiceURL+uri+id,HttpMethod.<strong><em>GET</em></strong>,<strong>null</strong>, String.<strong>class</strong>);</pre><pre><strong> return</strong> response.getBody();<br>}<br>}</pre><pre>……</pre><p>Employee.java</p><pre>@Getter<br>@Setter<br>@Entity<br>@JsonIgnoreProperties({“hibernateLazyInitializer”, “handler”})<br>@JsonInclude(Include.<strong><em>NON_NULL</em></strong>)</pre><pre><strong>public</strong> <strong>class</strong> Employee {</pre><pre>@Id<br><strong>private</strong> String id;</pre><pre><strong>private</strong> String firstName;</pre><pre><strong>private</strong> String lastName;</pre><pre><strong>private</strong> String salGrade;</pre><pre><strong>private</strong> String salary;</pre><pre>}</pre><p>EmployeeServiceTest.java</p><pre>@RunWith(SpringRunner.<strong>class</strong>)</pre><pre>@SpringBootTest</pre><pre>@TestPropertySource(properties {“server.baseuri=http://localhost:8888&quot; })</pre><pre><strong>public</strong> <strong>class</strong> EmployeeServiceTest {</pre><pre>@Autowired<br><strong>private</strong> ResourceLoader resourceLoader = <strong>null</strong>;</pre><pre>@Autowired<br><strong>private</strong> EmployeeServiceImpl empService;</pre><pre><strong>private</strong> String empId = “1”;</pre><pre>@Rule</pre><pre><strong>public</strong> WireMockRule wireMockRule = <strong>new</strong> WireMockRule(WireMockConfiguration.<em>options</em>().port(8888).httpsPort(9999).notifier(<strong>new</strong> ConsoleNotifier(<strong>true</strong>)).extensions(<strong>new</strong> ResponseTemplateTransformer(<strong>true</strong>)));</pre><pre>@Test<br>@SneakyThrows</pre><pre><strong>public</strong> <strong>void</strong> testCalltoEmployeeService() {</pre><pre><strong>try</strong> {<br>   wireMockRule.stubFor(<em>get</em>(<em>anyUrl</em>()).willReturn(<em>aResponse</em>().withStatus(200).withHeader(&quot;Content-Type&quot;, &quot;application/json&quot;).withBody(convertJsonToEmployee(resourceLoader.getResource(&quot;classpath:EmpResponse.json&quot;).getFile()))));</pre><pre>String salary = empService.getEmployeeSalary(&quot;1&quot;,&quot;/v1/employees/salary/&quot;);</pre><pre><em>assertTrue</em>(&quot;20000&quot;.equalsIgnoreCase(salary));</pre><pre><em>verify</em>(<em>exactly</em>(1),<em>getRequestedFor</em>(<em>urlPathEqualTo</em>(&quot;/v1/employees/salary/1&quot;)));</pre><pre>} <strong>catch</strong> (IOException e) {<br>   e.printStackTrace();<br>}<br>}</pre><pre>@Test(expected = HttpClientErrorException.<strong>class</strong>)<br><strong>public</strong> <strong>void</strong> testCalltoEmployeeServiceWithErrorResponse() {</pre><pre><strong>try</strong> {<br>wireMockRule.stubFor(<em>get</em>(<em>anyUrl</em>()).willReturn(<em>aResponse</em>().withStatus(convertJsonToString(resourceLoader.getResource(&quot;classpath:404.json&quot;).getFile())).withHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)));</pre><pre>empService.getEmployeeSalary(&quot;2&quot;,&quot;/v1/employees/salary/&quot;);</pre><pre><em>verify</em>(<em>exactly</em>(1), <em>getRequestedFor</em>(<em>urlPathEqualTo</em>(&quot;/v1/employees/salary/2&quot;)));</pre><pre>} <strong>catch</strong> (IOException e) {<br>   e.printStackTrace();<br>}<br>}</pre><pre><strong>public</strong> String convertJsonToEmployee(File file) {</pre><pre><strong>try</strong> {<br>   ObjectMapper objectMapper = <strong>new</strong> ObjectMapper();<br>   EmployeeSalary empWithSalary = objectMapper.readValue(file,   EmployeeSalary.<strong>class</strong>);<br>   <strong>return</strong> empWithSalary.getSalary();<br>} <strong>catch</strong> (Exception e) {<br>  e.printStackTrace();<br>}<br><strong>return</strong> <strong>null</strong>;<br>}</pre><pre><strong>public</strong> Integer convertJsonToString(File file) {<br><strong>try</strong> {<br>  ObjectMapper objectMapper = <strong>new</strong> ObjectMapper();<br>  JsonNode jsonNode = objectMapper.readValue(file,JsonNode.<strong>class</strong>);<br>  <strong>return</strong> (Integer)jsonNode.get(&quot;status&quot;).asInt();<br>} <strong>catch</strong> (Exception e) {<br>  e.printStackTrace();<br>}<br><strong>return</strong> <strong>null</strong>;<br>}<br>}</pre><p><strong>Why WireMock?<br></strong>WireMock internally provides a layer over Mock environment. If you look closely in EmployeeServiceTest.java, we not providing any mock objects for ResponseEntity,restTemplate and stub like :</p><pre><br>When(restTestTemplate.exchange(anyUrl,HTTP.GET,null,String.class).thenReturn(mockedResponseEntityObject). </pre><p>It automatically handles internally by WireMock and that is the main advantage of using Wiremock in place of any other Object Mocking frameworks.</p><p><strong>How integration testing through Wiremock should happen in real world?<br></strong>What if the request/response of the service’s API which we have mocked is changed. Service deployment will pass in the all environment’s pipeline,but there is no use of this integration testing, then what is solution?</p><p>Create a extra service/server <em>XXXMockServer</em>.In our case, EmployeeMockServer, which will have the the updated mock objects of each and every service. Every service will update the the server(EmployeeMockServer) or vise-verse in case of any change in the service APIs. Updation can be triggered through some batch processing or through using any publisher/subscriber model. Other services can either listen to any change in the mock server or either a scheduler can be set for each service which will periodically fetch the latest API changes and create the mock of the service. Refer the below image for the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mAfptXviQOXIwxGbbEp5A.png" /></figure><h4>Wiremock vs Other Mock frameworks(Mockito,PowerMock etc.)</h4><p>WireMock is basically used in integration testing and it a simulator for HTTP based APIs. Whereas Mockito,PowerMock provides implementation of method/object and used in Unit testing.</p><p><strong>Source</strong> :<br><a href="https://github.com/gtl-khushboo/integration-testing-EmployeeService">https://github.com/gtl-khushboo/integration-testing-EmployeeService</a><br><a href="https://github.com/gtl-khushboo/integration-testing-EmployeeCalService">https://github.com/gtl-khushboo/integration-testing-EmployeeCalService</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36165f253c1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/integration-testing-with-wiremock-36165f253c1b">Integration Testing with WireMock</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do Components Interact with Each other in React?]]></title>
            <link>https://medium.com/vedity/how-do-components-interact-with-each-other-in-react-4c06a256949b?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/4c06a256949b</guid>
            <category><![CDATA[react-context-api]]></category>
            <category><![CDATA[props-in-react]]></category>
            <category><![CDATA[react-components]]></category>
            <category><![CDATA[component-communication]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[Amitparmar Dev]]></dc:creator>
            <pubDate>Thu, 07 Apr 2022 05:09:25 GMT</pubDate>
            <atom:updated>2022-04-07T05:09:25.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*J12NWawFgQ1boSFqr939Vw.png" /></figure><p>React App can be consist of enormous interactive React components. Communication between these components is an essential aspect of the UI architecture, especially with large and more complex web applications. These components are functional in nature: that is, they receive information through arguments and pass information in their return. This is called unidirectional data flow.</p><p>Let us discuss 3 prime ways of communication between React components</p><ol><li>Props mechanism</li><li>Context API</li><li>React-Redux/Redux</li></ol><h3>Props in React</h3><p>React Components accept input called <strong>Props</strong>. This is an optional parameter. In the functional component, we can access this object as props whereas in Class Component we can use this.props to access props object. Let us dive deep into props to understand how they work and how do they used to pass data between various components. We will discuss different scenarios.</p><h3>Passing data from Parent to Child:</h3><p>In React app, one component can pass data to their child components through props, similar to arguments to a function. This is an optional property, we can send to any React Component. It is the simplest way of communication between components in React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*GmXRQznxkxPnk6bV8qVdFA.png" /></figure><p>In the above example, &lt;Employee&gt; is a parent component that passes the employee name as an argument in the &lt;EmployeeDetails&gt; child component. In the child component, the empName value is accessible using a special property called props. To access the empName value in the child Component, we can write props.empName. This is a read-only property in the child component and every time when employee name gets changed, this child component also gets re-render. Children cannot update props. If you attempt to directly modify a prop in a child component, you will see the error in the console.</p><h3>Passing data from Child to Parent Component:</h3><p>As React supports unidirectional data flow, we cannot pass any data directly from the child to the parent component. To achieve this, we have to use a slightly different approach here. First, we have to pass a method of parent component to child component as props. In the give example, &lt;Employee&gt; Component passes onChangeName method to the &lt;EmployeeDetails&gt; Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*kxiDX5oZNxXbbe_WBdOrqg.png" /></figure><p>Here, the Child component&lt;EmployeeDetails&gt; can trigger a function on button click which is a functional props received from the parent component. The essence of the functional prop is that when the button is clicked, the function(onChangeName) passed in by the Employee component is executed. Thus, child-to-parent communication is achieved.</p><h3>Passing data between Sibling Components:</h3><p>In sibling components, we can use multiple ways to send data. We can use a combination of the above two methods (use callback and use of props). Other approaches are ContextAPI and Redux.</p><h3>Context API in React</h3><p>In large or complex React app, passing data using props is very cumbersome for certain reasons. ContextAPI provides a better way to pass data between components without explicitly passing props. It provides a way to pass data through the component tree without having to pass props down manually at every level. Using ContextAPI, We can easily pass data from a component to any deeply nested components in the component tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*R8YHmdmJ2W_2AT5pMLqKgQ.png" /></figure><p>In the above app, we have used React contextAPI feature to pass data from &lt;Employee&gt; component to the grandchild &lt;EmployeeProfile&gt; component. During this communication, data is not passed using props.</p><h3>React-Redux/Redux</h3><p>Redux is a third-party library used for robust communication between components at the app level. It is a state management library to store the state of the App in one place and manipulate it from anywhere in the App. As it is a JavaScript library independent from React, we can use Redux with Angular, Vuejs, or even with vanilla JavaScript.</p><p>As the data is stored in a separate state defined at one place, any component can set or update the state and other components will capture it. In this scenario, the child component can set or update a state in the store and it will be captured by the parent component too.</p><p>To setup Redux inside a React Application, you have to install the following packages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*TdafxUdrNYKhkOr7AmPFew.png" /></figure><h3>Setup Your Redux Store</h3><p>Redux store is a plain JavaScript object. We can manage our App data in Redux Store using this plain JavaScript Object. Our App data will be comprised of arrays and objects which reside in Redux Store. That means you may not put other things into the Redux state — no class instances, built-in JS types like Map / Set Promise / Date, functions, or anything else that is not plain JS data.</p><p>To set up the redux store, we will use <strong>createStore</strong> API that will create the store. This method accepts customReducer as a parameter. This store will be used available to attach with React App tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*VAhXlsaj28cKxUedNIgdAA.png" /></figure><p>In the <strong>index.js</strong> file, we will use a special react-redux component named <strong>&lt;Provider&gt;</strong> to attach Redux Store with React App tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*6KZZfF2WWOrnreGGth8EEQ.png" /></figure><h3>Designing Actions</h3><p>After the initial configuration of the Redux Store, We have to design Actions as an event that describes the initialization of action on the store. <strong>Action </strong>is a JavaScript plain object. It has a special key called <strong>type</strong>. The <strong>type</strong> key is used to define the <strong>Type of Action</strong> that you want to initiate in the store.</p><p><strong>You can think of an action as an event that describes something that happened in the application</strong>. Along with the Type key, we normally put any extra data needed to describe what’s happening into the <strong>action.payload</strong> field. This could be a number, a string, or an object with multiple fields inside. Basically <strong>actions.payload</strong> is the data which we want to pass to the store.</p><p>Refer following examples of action object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*am99XfQgc_380YLCC-H7vA.png" /></figure><h3>Writing Reducers</h3><p>Once we are ready with basic store setup and actions. We can wire up our first reducer. <strong>Reducer</strong> is a pure JavaScript function in Redux, which is responsible to update the Redux store. It takes the current <strong>state</strong> of the store and an <strong>action</strong> object as arguments. Based on the type key of the action object, Reducer decides what to update in the state of the store. Reducer returns a new State of the Store as a result.</p><p>In Other words, <strong>(state, action)=&gt;newState</strong></p><h4>Rules of Reducers<a href="https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#rules-of-reducers">​</a></h4><p>While working with Reducers following rules should be followed:</p><ul><li>They should only calculate the new state value based on the state and action arguments</li><li>They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.</li><li>They must not use any asynchronous logic or other “side effects”</li></ul><h3>Connect to Redux Store</h3><p>After setting up Redux Store, Actions, and Reducer, our redux state management system is ready to work with any complex React application. But all these components of the Redux store won’t do anything by themselves.</p><p>To connect with Redux Store, React-Redux library provides <strong>connect()</strong> function. This connect() function is a higher-order component that connects React component to the Redux store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*WZHmV6sh4oMGPLbYcgr5bQ.png" /></figure><p>In above code, <strong>mapStateToProps</strong> and <strong>mapDispatchToProps</strong> are use to refer stateProps and dispatchProps, respectively. A <strong>mapStateToProps</strong> function is used to subscribe to the Redux store. It means that at any time the store get updated, this function will gets the new state of the Redux store. This function returns a plain object which comprised of the update state of store. Our components can access this update state of store using props. If you don’t want to subscribe to store updates, pass null or undefined in place of mapStateToProps.</p><p>Similarly, <strong>mapDispatchToProps </strong>is a second argument of the connect function. If <strong>mapDispatchToProps</strong> is declared as a function taking one parameter, it will be given the <strong>dispatch</strong> of your store. It is expected to return an object. Each field of the object should be a function, by calling these functions it is expected to dispatch an actions to the store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*P0ddrjwMcJoAfdlTPFTjMw.png" /></figure><p>Above snapshot gives you a holistic view of React Redux State Management System, where View represents the React Components which triggers Actions to the Redux store using Dispatchers. It will be further handled by the Reducers which read the current state and action’s type received from Dispatcher to update the state of the store. Finally it returns the updated new state of the store which React component receives as props</p><h3>Conclusion</h3><p>Finally, we have discussed almost all widely used methods in React world for the communication between different components. First two methods are mostly applicable when parent and its child components are communicating with each other. Also, we have seen that Redux store can be used when we want to achieve component communication in the large DOM Tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c06a256949b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/how-do-components-interact-with-each-other-in-react-4c06a256949b">How do Components Interact with Each other in React?</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with GraphQL (Part I)]]></title>
            <link>https://medium.com/vedity/getting-started-with-graphql-part-i-592d16285314?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/592d16285314</guid>
            <category><![CDATA[overview]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Ronak Purohit]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 10:07:30 GMT</pubDate>
            <atom:updated>2022-03-11T10:07:30.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjVr87nTkybfJLmZM8QFfg.png" /></figure><p>The purpose of this article is to highlight the basic understanding of GraphQL along with discussing the significant pros and cons associated with this particular APIs specification.</p><p>GraphQL is an open source server-side technology which was developed by Facebook. GraphQL is an execution engine and data query language to optimize REST APIs calls. Let’s understand in more detail about GraphQL.</p><p><strong>What is GraphQL ?</strong></p><p>Let me breakdown word Graph and QL. Graph means our queries cryoll into the REST APIs and pick up the selective information and QL means query language.</p><p>“GraphQL means query language designed to built client application by providing flexible and initiative syntax asking the data requirement by clients.” in simple terms design query more smarter way</p><p>GraphQL is designed to make APIs fast, flexible, and developer-friendly. As an alternative to REST, GraphQL lets developers construct requests that pull data from multiple data sources in a single APIs call.</p><p>Additionally, GraphQL gives APIs maintainers the flexibility to add or deprecate fields without impacting existing queries. Developers can build APIs with whatever methods they prefer, and the GraphQL specification will ensure they function in predictable ways to clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*9JvbCk3Q59KSUBy8K4hwzw.png" /></figure><p>GraphQL allows making multiple resources request in a single query call, which saves a lot of time and bandwidth by reducing the number of network round trips to the server. It also helps to save waterfall network requests, where you need to resolve dependent resources on previous requests.</p><p>so far we mainly design APIs using REST and other web services.only problem with them is over fetching or under fetching. Sometimes data over fetching or under fetching need to create multiple APIs to fetch less or more data. Sometime u don’t needed more or less data. Only needed selective data.</p><p><strong>Example :</strong></p><p>Let say we have cricket teams from different countries. we have created endpoints to retrieve information of players . Using all endpoints we can collect information but information is not selective.</p><p>/players</p><p>/players/id</p><p>/country</p><p>Instead of REST APIs if we use GraphQL we don’t need to declare multiple endpoints also we can only retrieve information what we needed in the smarter way.</p><p>Instead of REST APIs if we use GraphQL we don’t need to declare multiple endpoints also we can only retrieve information what we needed in the smarter way.</p><p><strong>GraphQL Query and Mutation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5SHJcfMXtofKwJmQmlB2A.jpeg" /></figure><p><strong>Query:</strong></p><p>In REST, any request might end up causing some side-effects on the server, but by convention it’s suggested that use GET requests to retrieve data. In GraphQL we can retrieve data using the Queries.</p><p>Query have components like <strong>field, arguments, aliases, fragments, variables, operation name, directives </strong>etc.</p><pre><strong>Request:</strong></pre><pre>query countryNameAndPlayers {<br>country {<br>          name<br>          players {<br>                   name<br>                  }<br>        }<br>}</pre><pre><strong>Response :</strong></pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;country&quot;: {<br>      &quot;name&quot;: &quot;IND&quot;,<br>      &quot;players&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Test One&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;Test Two&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>As we can see query will return specific value like country name and player name no other arguments need to pass here.</p><p><strong>Mutation:</strong></p><p>Most discussions of GraphQL focus on data fetching, but any complete data platform needs a way to modify server-side data as well.</p><p>In REST, any request might end up causing some side-effects on the server, but by convention it’s suggested that one doesn’t use GET requests to modify data. GraphQL is similar — technically any query could be implemented to cause a data write. However, it’s useful to establish a convention that any operations that cause writes should be sent explicitly via a mutation.</p><p>Just like in queries, if the mutation field returns an object type, you can ask for nested fields. This can be useful for fetching the new state of an object after an update. Let’s look at a simple example mutation:</p><pre><strong>Request</strong>:</pre><pre>mutation createPlayerReview($pl: Player!, $review: ReviewInput!) {<br>createPlayerReview(player: $pl, review: $review) {<br>        stars<br>        commentary<br>    }<br>}</pre><pre><strong>Input</strong>:</pre><pre>{<br> &quot;pl&quot;: &quot;Test One&quot;,<br>     &quot;review&quot;: {<br>           &quot;stars&quot;: 5,<br>           &quot;commentary&quot;: &quot;He is a great player!&quot;<br>    }<br>}</pre><pre><strong>Response</strong>:</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;createPlayerReview&quot;: {<br>      &quot;stars&quot;: 5,<br>      &quot;commentary&quot;: &quot;He is a great player!&quot;<br>    }<br>  }<br>}</pre><p>Note: How createPlayerReview field returns stars and commentary field of newly created review.</p><p>Now again it should be not consider that GraphQL is awesome in all area.</p><p>Sometimes application not need that kind of dig up into the information and that kind of resource that u need to implement GraphQL.</p><p>Remember that not everything comes up as new not always rainbow and sunshine. There are always pros and cons available.</p><p><strong>Pros and Cons of GraphQL :</strong></p><p>As they are both specifications for building and consuming APIs, GraphQL and REST have things in common. They both retrieve resources by sending queries, can return JSON data in the request, and be operated over HTTP. Also, REST endpoints are similar to GraphQL fields, as they are entry points into the data that call functions on the server</p><p>Thinking about trying GraphQL in a business or enterprise environment? It comes with both pros and cons.</p><p><strong>Pros</strong>:</p><p>· A GraphQL schema sets a single source of truth in a GraphQL application. It offers an organization a way to federate its entire APIs.</p><p>· GraphQL calls are handled in a single round trip. Clients get what they request with no over fetching.</p><p>· Strongly defined data types reduce miscommunication between the client and the server.</p><p>· GraphQL is introspective. A client can request a list of data types available. This is ideal for auto-generating documentation.</p><p>· GraphQL allows an application APIs to evolve without breaking existing queries.</p><p>· Many open source GraphQL extensions are available to offer features not available with REST APIs.</p><p><strong>Cons</strong>:</p><p>· GraphQL presents a learning curve for developers familiar with REST APIs.</p><p>· GraphQL shifts much of the work of a data query to the server side, which adds complexity for server developers.</p><p>· Depending on how it is implemented, GraphQL might require different APIs management strategies than REST APIs, particularly when considering rate limits and pricing.</p><p>· Caching is more complex than with REST.</p><p>· APIs maintainers have the additional task of writing maintainable GraphQL schema.</p><p><strong>Conclusion:</strong></p><p>Whole summary I would say when your REST APIs become smarter it’s called GraphQL. We have understand the O<strong>verview of GraphQL, Query and Mutation With Example, Pros and Cons of GraphQL Over the other webservice.</strong></p><p>In Second Part We will be discuss about <strong>GraphQL Configuration, Schema and Types, Validation, Serving over HTTP</strong> Stay tuned for next blog.</p><p>Thank you for reading!</p><p><em>Any feedback would be much appreciated and if you liked what you’ve read please hold the clap button!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=592d16285314" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/getting-started-with-graphql-part-i-592d16285314">Getting Started with GraphQL (Part I)</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Caching Mechanism]]></title>
            <link>https://medium.com/vedity/spring-boot-caching-mechanism-8ef901147e60?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ef901147e60</guid>
            <category><![CDATA[spring-cache]]></category>
            <category><![CDATA[caching-data]]></category>
            <category><![CDATA[application-performance]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Jitendra Kakwani]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 05:11:39 GMT</pubDate>
            <atom:updated>2022-03-11T05:11:39.852Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Basic Guide to implement cache in your Spring Boot App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LPqY0YtboExKFmiFT19zIA.jpeg" /></figure><p>In this article, We will learn about caching and how to implement a cache in Spring Boot Application and increase the performance of the application.</p><p>Spring Boot has lot of features to manage the cache and it is simple to use. So lets get started.</p><h3>What is Caching ?</h3><p>Cache is a part of temporary memory (RAM). It lies between the application and the persistent database.</p><p>Caching is a mechanism used to increase the performance of a system. It is a process to store and access data from the cache.</p><p>It stores the recently used data. This helps to reduces the number of database hits as much as possible.</p><h3><strong>Why should we use the cache ?</strong></h3><p>There are some main reasons of using cache are as follows :</p><ol><li>It make data access faster and less expensive</li><li>It improves the performance of the application.</li><li>It gives responses quickly.</li><li>Data access from memory is always faster than fetching from database.</li><li>It reduces the costly backend requests.</li></ol><h3>What data should be cached ?</h3><p>The data which is to be cached is based on different requirement and scenarios. So caching data will differ for each application.</p><p>Below are some of the examples for which data should be cached :</p><ol><li>List of product should be cached for an e-Commerce store.</li><li>The data that do not change frequently.</li><li>The frequently used read query in which results does not change in each call at least for a period.</li></ol><h3>Types of Caching</h3><p>There are four types of caching are as follows :</p><ol><li>In-memory Caching.</li><li>Database Caching.</li><li>Web Server Caching.</li><li>CDN Caching</li></ol><h4><strong>In-Memory Caching</strong></h4><p>In-memory caching is a technique which is widely used. In this type of caching, data is stored in RAM. <strong>Memcached</strong> and <strong>Redis</strong> are examples of in-memory caching.</p><p><strong>Memcached</strong> is a simple in-memory cache while <strong>Redis</strong> is advanced.</p><h4><strong>Database Caching</strong></h4><p>Database caching includes cache in database. It improves the performance by distributing a query workload.</p><p>We can optimize the default configuration in database caching to further boosting the application performance.</p><p><strong>Hibernate first level cache</strong> is an example of database caching.</p><h4><strong>Web Server Caching</strong></h4><p>Web server caching is a mechanism that stores data for reuse.</p><p>It is cached for the first time when a user visits the page. If the user requests the same next time, the cache serves a copy of the page.</p><h4>CDN Caching</h4><p>The CDN stands for Content Delivery Network. It is a component used in modern web application.</p><p>It improves delivery of the content by replicating common requested files such as Html Pages, images, videos, etc. across distributed set of caching servers.</p><h3>Spring Boot Caching</h3><p>Spring boot provides a <strong>Cache Abstraction API</strong> that allow us to use different cache providers to cache objects.</p><p>The below is the control flow of Spring boot caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQIG8hKPM7FGwqflrwkb7g.png" /><figcaption>Spring Boot Caching</figcaption></figure><p>When the caching is enabled then the application first looks for required object in the cache instead of fetching from database. If it does not find that object in cache then only it access from database.</p><p>Caching makes the data access faster as data is fetched from database <strong>only the first time</strong> when it is required. Subsequently, it is fetched from the cache. Thus, Caching improves the performance of an application.</p><p>The cache abstraction works on two things :</p><ol><li><strong>Cache Declaration :</strong> It identifies the methods that need to be</li><li><strong>Cache Configuration :</strong> The backing cache where data is stored and read from.</li></ol><h3>Spring Boot Caching Annotations</h3><p>The following annotations are used to add caching support to Spring boot application.</p><h4><strong>@EnableCaching</strong></h4><p>It is a class level annotation. It is used to enable caching in spring boot application. By default it setup a <strong>CacheManager</strong> and creates in-memory cache using one concurrent <strong>HashMap</strong>.</p><pre>@SpringBootApplication<br>@EnableCaching<br>public class SpringBootCachingApplication {</pre><pre>  public static void main(String[] args) {</pre><pre>    SpringApplication.run(SpringBootCachingApplication.class, args);<br>  }<br>}</pre><p>It is also applied over a Spring configuration class as below :</p><pre>@Configuration<br>@EnableCaching<br>public class CacheConfig {<br>  // some code<br>}</pre><p>If you are using the default CacheManager and you do not want to customize it then there is no need to create separate class to apply <strong>@EnableCaching</strong>.</p><p>We can use external cache providers by registering them using <strong>CacheManager</strong>.</p><h4>@Cacheable</h4><p>It is a method level annotation. It is used in the method whose response is to be cached. The Spring boot manages the request and response of the method to the cache that is specified in the annotation attribute.</p><p>We can provide cache name to this annotation as follow :</p><pre>@Cacheable(“employees”)<br>public Employee findById(int id) {<br>  // some code<br>}</pre><p>This annotation has the following attributes :</p><h4><strong>1. cacheNames / value :</strong></h4><p>The <strong>cacheNames</strong> is used to specify the name of the cache while <strong>value</strong> specifies the alias for the cacheNames.</p><p>We can also provide a cache name by using the <strong>value</strong> or <strong>cacheNames</strong> attribute.</p><p>For example,</p><pre>@Cacheable(value=”employees”)<br>public Employee findById(int id) {<br>  // some code<br>}</pre><pre>@Cacheable(cachNames=”employees”)<br>public Employee findById(int id) {<br>  // some code<br>}</pre><h4>2. key :</h4><p>This is the <strong>key</strong> with which object will be cached. It <strong>uniquely identifies</strong> each entry in the cache. If we do not specify the key then Spring uses the default mechanism to create the key.</p><p>For example,</p><pre>@Cacheable(value=”employees”, key=&quot;#id&quot;)<br>public Employee findById(int id) {<br>  // some code<br>}</pre><h4><strong>3. keyGenerator :</strong></h4><p>It is used to define your <strong>own key generation mechanism</strong>. We need to create custom key generator class.</p><p>For example,</p><pre>@Cacheable(value=”employees”, keyGenerator=”customKeyGenerator”)<br>public Employee findById(int id) {<br>  // some code<br>}</pre><h4><strong>4. cacheManager :</strong></h4><p>It specifies the name of cache manager. It is used define your own cache manager and do not want to use spring’s default cache manager.</p><p>For example,</p><pre>@Cacheable(value=”employees”, cacheManager=”customCacheManager”)<br><strong>public</strong> Employee findByName(String name) {<br>  // some code<br>}</pre><h4>5. condition :</h4><p>We can apply a condition in the attribute by using the <strong>condition</strong> attribute. We can call it as <strong>conditional caching</strong>.</p><p>For example, the following method will be cached if the argument name has length less than 20.</p><pre>@Cacheable(value=”employees”, condition=&quot;#name.length &lt; 20&quot;)<br>public Employee findByName(String name) {<br>  // some code<br>}</pre><h4><strong>6. unless :</strong></h4><p>It specifies the object to to cached if it matches certain condition. SpEL provides a context variable <strong>#result</strong> which refers to the object that is fetched and we can apply condition on on its value.</p><p>For example,</p><pre>@Cacheable(value=”employees”, unless=”#result.length &lt; 20”)<br>public Employee findByName(String name) {<br>  // some code<br>}</pre><h4>@CachePut</h4><p>It is a method level annotation. It is used to <strong>update</strong> the cache before invoking the method. By doing this, the result is put in the cache and the method is executed. It has same attributes of @Cacheable annotation.</p><pre>@CachePut(value=”employee”)<br>public Employee updateEmployee(Employee employee) {<br>  // some code<br>}</pre><p><strong>Can we use @CachePut and @Cacheable into same method ?</strong></p><p>There is difference between @Cacheable and @CachePut is that <strong>@Cacheable</strong> annotation skips the method execution while the <strong>@CachePut</strong> annotation runs the method and put its result in the cache.</p><p>If we use these annotations together then the application shows the unexpected behaviour. So two annotations cannot be used together.</p><h4><strong>@CacheEvict</strong></h4><p>It is a method level annotation. It is used to <strong>remove</strong> the data from the cache. When the method is annotated with this annotation then the method is executed and the cache will be removed / evicted.</p><p>We can remove single entry of cache based on <strong>key</strong> attribute. It provides parameter called <strong>allEntries=true</strong>. It evicts all entries rather one entry based on the key.</p><p>For example,</p><p>Evict an entry by key :</p><pre>@CacheEvict(value=”employee”, key=&quot;#id&quot;)<br>public void deleteEmployee(int id) {<br>  // some code<br>}</pre><p>Evict the whole cache :</p><pre>@CacheEvict(value=”employee”, allEntries=true)<br>public void deleteEmployee(int id) {<br>  // some code<br>}</pre><h4><strong>@Caching</strong></h4><p>It is allows multiple nested caching annotations on the same method. It is used when we want to use multiple annotations of the same type.</p><p>Java does not allow multiple annotations of same type to be declared for given method. To avoid this problem, we use <strong>@Caching</strong> annotation.</p><p>For example,</p><pre>@Caching(evict = {<br>  @CacheEvict(“address”), <br>  @CacheEvict(value=“employee”, key=”#employee.id”)<br>})<br>public Employee getEmployee(Employee employee) {<br>  // some code<br>}</pre><h4><strong>@CacheConfig</strong></h4><p>It is a class level annotation. It is used to share <strong>common properties</strong> such as cache name, cache manager to all methods annotated with cache annotations.</p><p>When a class is declared with this annotation then it provides default setting for any cache operation defined in that class. Using this annotation, we do need to declare things multiple times.</p><p>For example,</p><pre>@Service<br>@CacheConfig(cacheNames=”employees”)<br>public class EmployeeService {</pre><pre>  @Cacheable<br>  public Employee findById(int id) {<br>    // some code<br>  }<br>}</pre><h3><strong>Spring Boot Cache Providers</strong></h3><p>The cache providers allow us to configure cache transparently and explicitly in an application.</p><p>The following steps are needed in order to configure any of these cache providers :</p><ol><li>Add the annotation <strong>@EnableCaching</strong> in the configuration file.</li><li>Add the required <strong>caching library</strong> in the classpath.</li><li>Add the <strong>configuration file</strong> for the cache provider in the root classpath.</li></ol><p>The following are the cache provider supported by Spring Boot framework :</p><ol><li>JCache (JSR-107)</li><li>EhCache</li><li>Hazelcast</li><li>Infinispan</li><li>Couchbase</li><li>Redis</li><li>Caffeine</li><li>Simple</li></ol><h4><strong>JCache</strong></h4><p>JCache is the standard caching API for Java. It is provided by <strong>javax.cache.spi.CachingProvider</strong>.</p><p>It is present on the classpath. The spring-boot-starter-cache provides the <strong>JCacheCacheManager</strong>.</p><h4>EhCache</h4><p>The EhCache is an open source Java based cache used to boost performance. It stores the cache in memory and disk (SSD).</p><p>EhCache used a file called <strong>ehcache.xml</strong>. The <strong>EhCacheCacheManager</strong> is automatically configured if the application found the file on the classpath.</p><p>If we want to use EhCache then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.ehcache&lt;/groupId&gt;<br>  &lt;artifactId&gt;ehcache&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>HazelCast</h4><p>The Hazelcast is a <strong>distributed</strong> in-memory data grid structure. It distributes the data equally among all the nodes. We can configure Hazelcast by using following property :</p><pre>spring.hazelcast.config=classpath:config/demo-config.xml</pre><p>If we want to use Hazelcast then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.hazelcast&lt;/groupId&gt;<br>  &lt;artifactId&gt;hazelcast&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Infinispan</strong></h4><p>Infinispan is embedded java library. It is used as a <strong>cache</strong> or a <strong>data grid</strong>. It stores data in key-value form. It can be easily integrated with JCache, Spring, etc.</p><p>It does not have default file location so we need to configure it by using following property :</p><pre>spring.cache.infinispan.config=infinispan.xml</pre><p>If we want to use Infinispan then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.infinispan&lt;/groupId&gt;<br>  &lt;artifactId&gt;infinispan-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Couchbase</strong></h4><p>Couchbase is a <strong>NoSQL</strong> database that can act as cache provider on top of the spring boot cache abstraction layer.</p><p>The <strong>CouchbaseCacheManager</strong> is automatically configured when we implement couchbase-spring-cache and configure couchbase.</p><p>If we want to use Couchbase then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.couchbase.client&lt;/groupId&gt;<br>  &lt;artifactId&gt;couchbase-spring-cache&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Redis</strong></h4><p>Redis is a popular in-memory data structure. It is a keystore-based data structure which is used to persist data.</p><p>The <strong>RedisCacheManager</strong> is automatically configured when we configure <strong>Redis</strong>. The default configuration is set by using property <strong>spring.cache.redis.*</strong>.</p><p>If we want to use Redis then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-data-redis&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Caffeine</strong></h4><p>Caffeine is a high performance Java based caching library. It also provides an in-memory cache.</p><p>The spring boot automatically configures the <strong>CaffeineCacheManager</strong> if Caffeine is found in the classpath.</p><p>If want to use Caffeine then we need to add the following dependency :</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.github.ben-manes.caffeine&lt;/groupId&gt;<br>  &lt;artifactId&gt;caffeine&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Simple</strong></h4><p>It is the default implementation. It configures a <strong>ConcurrentHashMap</strong> as a cache store if spring boot does not find any cache provider in the classpath.</p><h3><strong>Spring Boot Cache Example</strong></h3><p>Now its time for some practical implementation. We will create simple spring boot application and implement cache mechanism into it.</p><p>Below are the steps to create spring boot application using Spring Initializr API :</p><ol><li>Go to url : <a href="https://start.spring.io/"><strong>https://start.spring.io/</strong></a></li><li>Fill out the Project name and package as per your application.</li><li>Add the dependencies <strong>Spring Web</strong> and <strong>Spring Cache Abstraction</strong></li><li>Click on <strong>Generate</strong> the Project. When we click the Generate button then it will download the project in .zip file.</li><li>Extract the .zip file and import it into your Intellij or any IDE.</li></ol><p>Now our project is created. Lets create all neccessary files.</p><h4><strong>pom.xml</strong></h4><p>Lets open pom.xml file and see which dependencies we have added to it.</p><pre><em>&lt;?</em>xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;<em>?&gt;<br></em>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>   xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>   &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>   &lt;parent&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>      &lt;version&gt;2.6.4&lt;/version&gt;<br>      &lt;relativePath/&gt; <em>&lt;!-- lookup parent from repository --&gt;<br>   </em>&lt;/parent&gt;</pre><pre>   &lt;groupId&gt;com.example&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-cache-example&lt;/artifactId&gt;<br>   &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br>   &lt;name&gt;spring-boot-cache-example&lt;/name&gt;<br>   &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;<br>   <br>   &lt;properties&gt;<br>      &lt;java.version&gt;11&lt;/java.version&gt;<br>      &lt;lombok.version&gt;1.18.10&lt;/lombok.version&gt;<br>   &lt;/properties&gt;<br>   <br>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;<br>      &lt;/dependency&gt;</pre><pre>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>      &lt;/dependency&gt;</pre><pre>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>      &lt;/dependency&gt;</pre><pre>      &lt;dependency&gt;<br>         &lt;groupId&gt;mysql&lt;/groupId&gt;<br>         &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>         &lt;scope&gt;runtime&lt;/scope&gt;<br>      &lt;/dependency&gt;</pre><pre>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>         &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>         &lt;optional&gt;true&lt;/optional&gt;<br>         &lt;version&gt;${lombok.version}&lt;/version&gt;<br>         &lt;scope&gt;provided&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>         &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br><br>   &lt;build&gt;<br>      &lt;plugins&gt;<br>         &lt;plugin&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>         &lt;/plugin&gt;<br>      &lt;/plugins&gt;<br>   &lt;/build&gt;<br><br>&lt;/project&gt;</pre><h4><strong>Main Class</strong></h4><p>Open the <strong>SpringBootCacheExampleApplication.java </strong>and add <strong>@EnableCaching</strong> annotation to enable cache in the application.</p><pre>package com.example;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cache.annotation.EnableCaching;<br><br>@SpringBootApplication<br>@EnableCaching<br>public class SpringBootCacheExampleApplication {<br><br>   public static void main(String[] args) {<br><br>      SpringApplication.<em>run</em>(SpringBootCacheExampleApplication.class, args);<br>   }<br><br>}</pre><h4><strong>Model Class</strong></h4><p>Create model class <strong>Employee.java.</strong></p><pre>package com.example.model;<br><br>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;<br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>import javax.persistence.Column;<br>import javax.persistence.Entity;<br>import javax.persistence.GeneratedValue;<br>import javax.persistence.GenerationType;<br>import javax.persistence.Id;<br>import java.io.Serializable;<br><br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Entity<br>public class Employee implements Serializable {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.<em>IDENTITY</em>)<br>    @Column(nullable = false)<br>    private int id;<br><br>    @Column(nullable = false)<br>    private String name;<br><br>    private String address;<br>}</pre><h4>Repository Class</h4><p>Create repository class <strong>EmployeeRepository.java</strong>.</p><pre>package com.example.repository;<br><br>import com.example.model.Employee;<br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface EmployeeRepository extends JpaRepository&lt;Employee, Integer&gt; {<br><br>}</pre><h4>Service Class</h4><p>Create service class <strong>EmployeeService.java.</strong></p><pre>package com.example.service;<br><br>import com.example.model.Employee;<br>import com.example.repository.EmployeeRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.cache.annotation.CacheEvict;<br>import org.springframework.cache.annotation.CachePut;<br>import org.springframework.cache.annotation.Cacheable;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class EmployeeService {<br><br>    @Autowired<br>    EmployeeRepository employeeRepository;<br><br>    public Employee saveEmployee(Employee employee) {<br>        System.<em>out</em>.println(&quot;Save the record&quot;);<br>        return employeeRepository.save(employee);<br>    }<br><br>    @Cacheable(value = &quot;employee&quot;, key = &quot;#id&quot;)<br>    public Employee getEmployeeById(int id){<br>        System.<em>out</em>.println(&quot;Get the record with id : &quot; + id);<br>        return employeeRepository.findById(id).orElse(null);<br>    }<br><br>    @CachePut(value = &quot;employee&quot;, key = &quot;#employee.id&quot;)<br>    public Employee updateEmployee(Employee employee) {<br>        System.<em>out</em>.println(&quot;Update the record with id : &quot; + employee.getId());<br>        return employeeRepository.save(employee);<br>    }<br><br>    @CacheEvict(value = &quot;employee&quot;, key = &quot;#id&quot;)<br>    public void deleteEmployee(int id) {<br>        System.<em>out</em>.println(&quot;Delete the record with id : &quot; + id);<br>        employeeRepository.deleteById(id);<br>    }<br>}</pre><h4>Controller Class</h4><p>Create controller class <strong>EmployeeController.java</strong></p><pre>package com.example.controller;<br><br>import com.example.model.Employee;<br>import com.example.service.EmployeeService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.DeleteMapping;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.PutMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/employees&quot;)<br>public class EmployeeController {<br><br>    @Autowired<br>    EmployeeService employeeService;<br><br>    @PostMapping(&quot;/save&quot;)<br>    public ResponseEntity&lt;Employee&gt; saveEmployee(@RequestBody Employee employee) {<br>        return new ResponseEntity&lt;&gt;(employeeService.saveEmployee(employee), HttpStatus.<em>CREATED</em>);<br>    }<br><br>    @PutMapping(&quot;/update&quot;)<br>    public ResponseEntity&lt;Employee&gt; updateEmployee(@RequestBody Employee employee) {<br>        return new ResponseEntity&lt;&gt;(employeeService.updateEmployee(employee), HttpStatus.<em>OK</em>);<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Employee&gt; getEmployee(@PathVariable(&quot;id&quot;) int id) {<br>        return new ResponseEntity&lt;&gt;(employeeService.getEmployeeById(id), HttpStatus.<em>OK</em>);<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Void&gt; deleteEmployee(@PathVariable(&quot;id&quot;) int id) {<br>        employeeService.deleteEmployee(id);<br>        return new ResponseEntity&lt;&gt;(HttpStatus.<em>ACCEPTED</em>);<br>    }<br>}</pre><h4><strong>Running and Testing the Application</strong></h4><p>Now, we are going to run the application. Our application is running on port <strong>8080</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naTJ9lFZsILLpnF6KF774Q.jpeg" /></figure><p>Now, hit the url : <a href="http://localhost:8080/employee/1"><strong>http://localhost:8080/employee/1</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPMwB2ssRkt5S0k_7-xjbg.jpeg" /></figure><p>When you hit the url for the first then it executes the service method and data is fetched from the database.</p><p>But if you again hit the same url then the results will be displayed very fast as this time the data is fetched from the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y81Xqozz3_i7Nye5GF9uw.jpeg" /></figure><p>In this post, we have discussed all about Caching, Types of Cache, Caching annotations, different Caching providers and its configuration and how to add caching in Spring Boot application with example.</p><p>Now you have learned how to implement caching in Spring Boot application. With the help of caching we can increase the performance of application and reduces the application host.</p><p><em>You can find the full source code </em><a href="https://github.com/Jitz7057/Coding-Examples/tree/main/spring-boot-cache-example"><strong><em>here</em></strong></a>.</p><p><em>Thanks for reading.</em></p><p><em>If you like reading this article then please hold the clap button!</em></p><p><strong><em>Happy Caching !!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef901147e60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/spring-boot-caching-mechanism-8ef901147e60">Spring Boot Caching Mechanism</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Data Preprocessing Using Pyspark]]></title>
            <link>https://medium.com/vedity/python-data-preprocessing-using-pyspark-cc3f709c3c23?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc3f709c3c23</guid>
            <category><![CDATA[spark-dataframe]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vishal Barad]]></dc:creator>
            <pubDate>Fri, 24 Dec 2021 14:23:56 GMT</pubDate>
            <atom:updated>2021-12-24T14:23:56.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Preprocessing Using Pyspark (Part:1)</h3><p>Apache Spark is a framework that allows for quick data processing on large amounts of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNMdP5zTDwwvTiz5prNOHw.png" /><figcaption>Spark⚡</figcaption></figure><p>Data preprocessing is a necessary step in machine learning as the quality of the data affects the result and performance of the machine learning model which we applied on data. Therefore, it is extremely important that we preprocess our data before feeding it into our model.</p><p>Data preprocessing task is carried out by pandas and Pyspark as well, Here we are going to explore Pyspark.</p><p>Before we dive deep in to the preprocessing part let’s first take a brief knowledge about <strong>data exploration</strong>,</p><blockquote><strong>Data exploration</strong></blockquote><p><strong>Data exploration</strong>, also known as <strong>exploratory data analysis (EDA)</strong>, is a process for exploring, visualizing data to find pattern or uncover insight from the start and helps in identifying problems in the DataFrame as well as deciding which model or algorithm to use in subsequent steps.</p><p><strong>Let’s quickly discuss some of the data exploration technique</strong></p><ul><li><strong><em>Statistical summary of data</em></strong></li></ul><p>Pyspark’s <strong>describe</strong>() is used to view some basic statistical details like count, mean, stddev etc. of a DataFrame or a series of numeric …</p><pre><strong>data = [[1,None,&quot;vignan&quot;,95.0],<br>       [None,&quot;ojaswi&quot;,&quot;vvit&quot;,55.0],<br>       [3,None,&quot;vvit&quot;,65.0],<br>       [None,&quot;sridevi&quot;,&quot;vignan&quot;,None],                                                                                                   [None,&quot;Alrich&quot;,&quot;nonvignan&quot;,56.0],<br>       [1,None,None,55.0],<br>       [5,&quot;gnanesh&quot;,&quot;iit&quot;,1.0],<br>       [1,None,&quot;vignan&quot;,95.0],<br>       [6,None,&quot;vignan&quot;,22.0]]<br><br>columns = [&#39;student_ID&#39;,&#39;student_name&#39;, &#39;college&#39;,&#39;marks&#39;]<br>dataframe = spark.createDataFrame(data,columns)<br>dataframe.describe().show()</strong></pre><pre><strong>O/P:</strong><br>+-------+------------------+------------+-------+------------------+ |summary|        student_ID|student_name|college|             marks| +-------+------------------+------------+-------+------------------+ |  count|                 6|           4|      8|                 8| |   mean|2.8333333333333335|        null|   null|              55.5| | stddev| 2.228601953392904|        null|   null|32.302144997330615| |    min|                 1|      Alrich|    iit|               1.0| |    max|                 6|     sridevi|   vvit|              95.0| +-------+------------------+------------+-------+------------------+</pre><ul><li><strong><em>Count total number of null values</em></strong></li></ul><p>Let’s find and visualize the total number of null value present in DataFrame’s column,</p><pre><strong>import matplotlib.pyplot as plt</strong></pre><pre><strong>null_value_list = list()<br>for col_ in dataframe.columns:<br>    null_value_list.append(dataframe.filter(dataframe[col_].<br>    isNull().count())                       </strong></pre><pre><strong>plt.rcParams[&quot;figure.figsize&quot;] = (40,9)<br>columns = [col_ for col_ in dataframe.columns]<br>myexplode = [0.2, 0, 0, 0]<br>plt.pie(null_value_list, labels = columns, explode = myexplode, shadow = True, autopct=&#39;%1.0f%%&#39;)<br>plt.title(&#39;Total number of null value in column&#39;)</strong></pre><pre><strong>plt.show()</strong></pre><pre><strong>O/P:<br></strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*mTHa5NYgqxLx6sApFkwFvQ.png" /></figure><p>As we can saw “student_ID” column has 3 null values, same as for “student_name” has 5 and so on.</p><ul><li><strong><em>Count duplicate row</em></strong></li></ul><p>Let’s find how many duplicate row present in DataFrame,</p><pre><strong>import pyspark.sql.functions as funcs</strong></pre><pre><strong>dataframe.groupBy(dataframe.columns).count().where(funcs.col(&#39;count&#39;) &gt; 1).select(funcs.sum(&#39;count&#39;)).show()</strong></pre><pre><strong>O/P:<br></strong>+----------+ <br>|sum(count)| <br>+----------+ <br>|         2| <br>+----------+</pre><p>as we can show there are two duplicate rows in DataFrame as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*h7R8okk8FAgyrC51c_hHag.png" /><figcaption>Duplicate row</figcaption></figure><ul><li><strong><em>Find numeric and categorical column</em></strong></li></ul><p>Let’s find numeric (!=string) and categorical (==string) columns in DataFrame,</p><pre><strong>numeric_columns = list()<br>categorical_column = list()</strong></pre><pre><strong>for col_ in dataframe.columns:<br>    if dataframe.select(col_).dtypes[0][1] != &quot;string&quot;:<br>        numeric_columns.append(col_)<br>    else:<br>        categorical_column.append(col_)<br>        <br>print(&quot;Numeric columns&quot;,numeric_columns)<br>print(&quot;categorical columns&quot;,categorical_column)</strong></pre><pre><strong>O/P:</strong><br>Numeric columns [&#39;student_ID&#39;, &#39;marks&#39;] <br>categorical columns [&#39;student_name&#39;, &#39;college&#39;]</pre><p>Now you have better clarity about Data exploration now we are going to explore Data preprocessing,</p><p>So here we go🚩,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*5NAOcTUIzU3w2UYT73taDQ.gif" /></figure><blockquote><strong>Data preprocessing’s techniques we are going to discuss</strong></blockquote><ol><li>Drop null value</li><li>Handle missing value with imputation</li><li>Outlier detection, removal and imputation</li><li>Drop feature/column</li><li>Drop duplicates</li><li>Convert categorical feature/column into numerical</li><li>Feature scaling</li><li>Train test split data</li></ol><p>Now, here we’ll discuss first three techniques in deep with implementation. Rest of others we’ll discuss in second part of this blog.</p><blockquote><strong>Drop null value</strong></blockquote><p>Let’s first create <strong>Pyspark DataFrame</strong>. After creating data frame we’ll perform this operation.</p><pre><strong># Create pyspark dataframe<br>data = [[1,None,&quot;vignan&quot;,95.0],<br>       [None,&quot;ojaswi&quot;,&quot;vvit&quot;,55.0],<br>       [3,None,&quot;vvit&quot;,65.0],<br>       [None,&quot;sridevi&quot;,&quot;vignan&quot;,None],                                                                                                   [None,&quot;Alrich&quot;,&quot;nonvignan&quot;,56.0],<br>       [1,None,None,55.0],<br>       [5,&quot;gnanesh&quot;,&quot;iit&quot;,1.0],<br>       [1,None,&quot;vignan&quot;,95.0],<br>       [6,None,&quot;vignan&quot;,22.0]]</strong></pre><pre><strong># specify column names<br>columns = [&#39;student_ID&#39;,&#39;student_name&#39;, &#39;college&#39;,&#39;marks&#39;]</strong></pre><pre><strong># creating a dataframe from the lists of data<br>dataframe = spark.createDataFrame(data,columns)</strong></pre><pre><strong># show dataframe<br>dataframe.show()</strong></pre><pre><strong>O/P</strong>:<br>+----------+------------+---------+-----+ <br>|student_ID|student_name|  college|marks| <br>+----------+------------+---------+-----+ <br>|         1|        null|   vignan| 95.0| <br>|      null|      ojaswi|     vvit| 55.0| <br>|         3|        null|     vvit| 65.0| <br>|      null|     sridevi|   vignan| null| <br>|      null|      Alrich|nonvignan| 56.0| <br>|         1|        null|     null| 55.0| <br>|         5|     gnanesh|      iit|  1.0| <br>|         1|        null|   vignan| 95.0| <br>|         6|        null|   vignan| 22.0| <br>+----------+------------+---------+-----+</pre><p>Boom!.. Our DataFrame is created. Now let’s first check if is there any missing value present in this data frame.</p><pre><strong>from pyspark.sql.functions import *</strong></pre><pre><strong>print(dataframe.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in dataframe.columns]).show())</strong></pre><pre><strong>O/P:</strong><br>+----------+------------+-------+-----+ |student_ID|student_name|college|marks| <br>+----------+------------+-------+-----+ <br>|         3|           5|      1|    1| <br>+----------+------------+-------+-----+</pre><p>As we can saw that “student_ID”, “student_name”, “college” and “marks” have 3,4,1,1 missing values respectively.</p><p>Now, we’ll drop those missing values. Spark provides <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.dropna.html"><strong>dropna</strong></a><strong>()</strong> function, that is used to drop rows with null values in one or multiple(any/all) columns in DataFrame. While reading data from files, Spark API’s like DataFrame and Dataset assigns NULL values for empty value on columns.</p><p>Something based on a need you many needs to remove these rows that have null values as part of data cleaning.</p><pre><strong>dataframe = dataframe.dropna()<br>dataframe.show()</strong></pre><pre><strong>O/P:</strong><br>+----------+------------+-------+-----+ |student_ID|student_name|college|marks| <br>+----------+------------+-------+-----+ <br>|         5|     gnanesh|    iit|  1.0| <br>+----------+------------+-------+-----+</pre><p>There are some parameters used in <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.dropna.html"><strong>dropna()</strong></a> function, you can explore them by just clicking <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.dropna.html">here</a>.</p><blockquote><strong>Handle missing value with imputation</strong></blockquote><ol><li><strong>For numeric column</strong></li></ol><ul><li>Mean imputation</li><li>Median imputation</li><li>Mode imputation</li></ul><p>2. <strong>For categorical column</strong></p><ul><li>Frequent category imputation</li></ul><p><strong>Mean imputation</strong></p><p>Mean imputation is carried out on numeric feature/column. In this imputation missing value will be replaced by the <strong>mean</strong> of a particular feature/column.</p><pre><strong>dataframe.printSchema()</strong></pre><pre>O/P:<br>root  |-- student_ID: long (nullable = true)  <br>      |-- student_name: string (nullable = true)  <br>      |-- college: string (nullable = true)  <br>      |-- marks: double (nullable = true)</pre><p>As we can saw the “student_ID” and “marks” both are numeric columns. So we’ll perform mean imputation on these column.</p><pre><strong>from pyspark.ml.feature import Imputer</strong></pre><pre><strong>column_subset = [col_ for col_ in dataframe.columns if         dataframe.select(col_).dtypes[0][1] !=&quot;string&quot;]</strong></pre><pre><strong>imputer = Imputer(inputCols=column_subset,<br>                  outputCols=[col_ for col_ in column_subset]<br>                  ).setStrategy(&quot;mean&quot;)<br>dataframe = imputer.fit(dataframe).transform(dataframe)</strong></pre><pre><strong>dataframe.show()</strong></pre><pre>O/P:<br>+----------+------------+---------+-----+ <br>|student_ID|student_name|  college|marks| <br>+----------+------------+---------+-----+ <br>|         1|        null|   vignan| 95.0| <br>|         2|      ojaswi|     vvit| 55.0| <br>|         3|        null|     vvit| 65.0| <br>|         2|     sridevi|   vignan| 55.5| <br>|         2|      Alrich|nonvignan| 56.0| <br>|         1|        null|     null| 55.0| <br>|         5|     gnanesh|      iit|  1.0| <br>|         1|        null|   vignan| 95.0| <br>|         6|        null|   vignan| 22.0| <br>+----------+------------+---------+-----+</pre><p><strong>Median imputation</strong></p><p>Median imputation is carried out on numeric feature/column. In this imputation missing value will be replaced by the <strong>median</strong> of a particular feature/column.</p><pre><strong>from pyspark.ml.feature import Imputer</strong></pre><pre><strong>column_subset = [col_ for col_ in dataframe.columns if         dataframe.select(col_).dtypes[0][1] !=&quot;string&quot;]</strong></pre><pre><strong>imputer = Imputer(inputCols=column_subset,<br>                  outputCols=[col_ for col_ in column_subset]<br>                  ).setStrategy(&quot;median&quot;)<br>dataframe = imputer.fit(dataframe).transform(dataframe)</strong></pre><pre><strong>dataframe.show()</strong></pre><pre>O/P:<br>+----------+------------+---------+-----+ <br>|student_ID|student_name|  college|marks| <br>+----------+------------+---------+-----+ <br>|         1|        null|   vignan| 95.0| <br>|         2|      ojaswi|     vvit| 55.0| <br>|         3|        null|     vvit| 65.0| <br>|         2|     sridevi|   vignan| 55.5| <br>|         2|      Alrich|nonvignan| 56.0| <br>|         1|        null|     null| 55.0| <br>|         5|     gnanesh|      iit|  1.0| <br>|         1|        null|   vignan| 95.0| <br>|         6|        null|   vignan| 22.0| <br>+----------+------------+---------+-----+</pre><p><strong>Mode imputation</strong></p><p>Mode imputation is carried out on numeric feature/column. In this imputation missing value will be replaced by the <strong>mode </strong>of a particular feature/column.</p><pre><strong>column_subset = [col_ for col_ in dataframe.columns if dataframe.select(col_).dtypes[0][1] !=&quot;string&quot;]</strong></pre><pre><strong>for col_ in column_subset:<br>    temp_col = dataframe.groupBy(col_).count()<br>    temp_col = temp_col.dropna(subset=col_)<br>    mode = temp_col.orderBy(temp_col[&#39;count&#39;].desc()).collect()[0]  [0]<br>    dataframe = dataframe.fillna(mode, subset=col_)<br>dataframe.show()</strong></pre><pre>O/P:<br>+----------+------------+---------+-----+ <br>|student_ID|student_name|  college|marks| <br>+----------+------------+---------+-----+ <br>|         1|        null|   vignan| 95.0| <br>|         1|      ojaswi|     vvit| 55.0| <br>|         3|        null|     vvit| 65.0| <br>|         1|     sridevi|   vignan| 95.0| <br>|         1|      Alrich|nonvignan| 56.0| <br>|         1|        null|     null| 55.0| <br>|         5|     gnanesh|      iit|  1.0| <br>|         1|        null|   vignan| 95.0| <br>|         6|        null|   vignan| 22.0| <br>+----------+------------+---------+-----+</pre><p><strong>Frequent category imputation</strong></p><p>Now we saw all imputation method for the numeric column. <strong>What if DataFrame’s column is categorical?</strong></p><p>For that we’ll use <strong>frequent category imputation</strong> technique. In this technique we’ll impute missing value by the frequently occurred category.</p><pre><strong>column_subset = [col_ for col_ in dataframe.columns if dataframe.select(col_).dtypes[0][1] !=&quot;string&quot;]</strong></pre><pre><strong>for col_ in column_subset:<br>    temp_col = dataframe.groupBy(col_).count()<br>    temp_col = temp_col.dropna(subset=col_)<br>    frequent_category=temp_col.orderBy(<br>                     temp_col[&#39;count&#39;].desc()).collect()[0][0]<br>    dataframe = dataframe.fillna(frequent_category, subset=col_)<br>dataframe.show()</strong></pre><pre>O/P:<br>+----------+------------+---------+-----+ <br>|student_ID|student_name|  college|marks| <br>+----------+------------+---------+-----+ <br>|         1|      ojaswi|   vignan| 95.0| <br>|      null|      ojaswi|     vvit| 55.0| <br>|         3|      ojaswi|     vvit| 65.0| <br>|      null|     sridevi|   vignan| null| <br>|      null|      Alrich|nonvignan| 56.0| <br>|         1|      ojaswi|   vignan| 55.0| <br>|         5|     gnanesh|      iit|  1.0| <br>|         1|      ojaswi|   vignan| 95.0| <br>|         6|      ojaswi|   vignan| 22.0| <br>+----------+------------+---------+-----+</pre><p>Let’s break down above code for the better understanding.</p><pre><strong>column_subset = [col_ for col_ in dataframe.columns if dataframe.select(col_).dtypes[0][1] !=&quot;string&quot;]</strong></pre><pre><strong>for col_ in column_subset:<br>    temp_col = dataframe.groupBy(col_).count()<br>    temp_col = temp_col.dropna(subset=col_)<br>    frequent_category </strong>= <strong>temp_col.orderBy(<br>                        temp_col[&#39;count&#39;].desc()).show()</strong></pre><pre>O/P:<br>+------------+-----+ <br>|student_name|count| <br>+------------+-----+ <br>|      ojaswi|    6| <br>|      Alrich|    1| <br>|     sridevi|    1| <br>|     gnanesh|    1| <br>+------------+-----+</pre><pre>+---------+-----+ <br>|  college|count| <br>+---------+-----+ <br>|   vignan|    5| <br>|      iit|    1| <br>|     vvit|    2| <br>|nonvignan|    1| <br>+---------+-----+</pre><p>As we can saw that above code gave us the total number of time category occurred. So now we’ll convert <strong>frequent_category </strong>into RDD to collect most frequent item as follow.</p><pre><strong>frequent_category = temp_col.orderBy(<br>                    temp_col[&#39;count&#39;].desc()).collect()[0][0]<br>print(frequent_category)</strong></pre><pre>O/P:<br>ojaswi<br>vignan</pre><p>And boom!! And here we got the frequently occurred items. Now just impute them in place of missing value.</p><blockquote><strong>Outlier detection, removal and imputation</strong></blockquote><p><strong>What is outlier?</strong></p><p>In layman terms outliers are the data points that differs significantly from the observations. Or we can say that outliers are “the one of these things is not like others”.😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*_MHFSPNSUVpVeXClkPoOTw.png" /><figcaption>Outlier</figcaption></figure><p>But wait!✋🤚</p><p><strong>Do outliers really dangerous?</strong>🤔</p><p>Outliers are not always dangerous for our problem statement. In fact, outliers sometimes can be <strong>helpful indicators.</strong></p><p>For example, credit/debit card fraud detection, The credit/debit card industry has utilized the concept of outliers in detecting credit card fraud in the past and now.</p><p>Okay now you got the idea about outliers, so your question is how to detect outliers, right? Let’s deep dive into it.</p><blockquote><strong>Outlier detection</strong></blockquote><p>There are many methods for detecting outlier but here we’ll mainly focus on following two methods.</p><ol><li>Using Z-score</li><li>Using IQR</li></ol><p>Using Z-score</p><p>Z-score is a parametric outlier detection method in a one or low dimensional feature space.</p><p>This technique assumes a normal distribution/Gaussian distribution of the data. The outliers are the data points that are in the tails of the distribution and therefore far from the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*t8IHm7HvdgnXyfANoabM7Q.png" /></figure><p>A normal distribution/Gaussian distribution is shown above and it is estimated that,<br><strong>68%</strong> of the data points lie between <strong>+/- 1 </strong>standard deviation.<br><strong>95%</strong> of the data points lie between <strong>+/- 2</strong> standard deviation<br><strong>99.7%</strong> of the data points lie between <strong>+/- 3 </strong>standard deviation</p><p>We can find Z-score using below formula</p><h3>Z-score = (x -mean) / standard deviation</h3><p>If the z-score of a data point is more than <strong>+/- 3</strong>, it indicates that the data point is quite different from the other data points. Such a data point can be an outlier.</p><p>Let’s find outlier,</p><p>In order to find outlier first let’s create Pyspark DataFrame which has outlier.</p><pre><strong>data = [[&quot;Patty O’Furniture&quot;,5.9],<br>        [&quot;Paddy O’Furniture&quot;,5.2],<br>        [&quot;Olive Yew&quot;,5.1],<br>        [&quot;Aida Bugg&quot;,5.5],<br>        [&quot;Maureen Biologist&quot;,4.9],<br>        [&quot;Teri Dacty&quot;,5.4],<br>        [&quot;Peg Legge&quot;,6.2],<br>        [&quot;Allie Grate&quot;,6.5],<br>        [&quot;Liz Erd&quot;,7.1], <br>        [&quot;A. Mused&quot;,14.5],<br>        [&quot;Constance Noring&quot;,6.1],<br>        [&quot;Lois Di Nominator&quot;,5.6],<br>        [&quot;Minnie Van Ryder&quot;,1.2],<br>        [&quot;Lynn O’Leeum&quot;,5.5]]</strong></pre><pre><strong>columns = [&#39;student_name&#39;,&#39;height&#39;]</strong></pre><pre><strong>dataframe = spark.createDataFrame(data,columns)<br>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+-----------------+------+ <br>|     student_name|height| <br>+-----------------+------+ <br>|Patty O’Furniture|   5.9| <br>|Paddy O’Furniture|   5.2| <br>|        Olive Yew|   5.1| <br>|        Aida Bugg|   5.5| <br>|Maureen Biologist|   4.9| <br>|       Teri Dacty|   5.4| <br>|        Peg Legge|   6.2| <br>|      Allie Grate|   6.5| <br>|          Liz Erd|   7.1| <br>|         A. Mused|  14.5| <br>| Constance Noring|   6.1| <br>|Lois Di Nominator|   5.6| <br>| Minnie Van Ryder|   1.2| <br>|     Lynn O’Leeum|   5.5| <br>+-----------------+------+</pre><p>Now let’s detect outlier in above DataFrame using Z-score method</p><pre><strong>from pyspark.sql.functions import *</strong></pre><pre><strong>column_subset = dataframe.columns<br>for col in column_subset:<br>    if dataframe.select(col).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        mean = dataframe.select(mean(col)).collect()[0][0]<br>        stddev = dataframe.select(stddev(col)).collect()[0][0]<br>        upper_limit = mean + (3*stddev)<br>        lower_limit = mean - (3*stddev)<br>        dataframe = dataframe.filter((dataframe[col]&lt;lower_limit) |      (dataframe[col]&gt;upper_limit))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+------------+------+ <br>|student_name|height| <br>+------------+------+ <br>|    A. Mused|  14.5| <br>+------------+------+</pre><pre><strong>Note: Outlier can be found in numerical column only</strong></pre><p>As we can see that student_name=<strong>A. Mused </strong>has <strong>14.5</strong> height is an outlier.</p><p>And bust!!⚡ you got clear idea about how to find outlier, Now let’s dive deep into the outlier removal and outlier imputation technique.</p><p><strong>Z-score Outlier removal</strong></p><pre><strong>from pyspark.sql.functions import *</strong></pre><pre><strong>column_subset = dataframe.columns<br>for col in column_subset:<br>    if dataframe.select(col).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        mean = dataframe.select(mean(col)).collect()[0][0]<br>        stddev = dataframe.select(stddev(col)).collect()[0][0]<br>        upper_limit = mean + (3*stddev)<br>        lower_limit = mean - (3*stddev)<br>        dataframe = dataframe.filter((dataframe[col]&gt;lower_limit) &amp; (dataframe[col]&lt;upper_limit))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+-----------------+------+ <br>|     student_name|height| <br>+-----------------+------+ <br>|Patty O’Furniture|   5.9| <br>|Paddy O’Furniture|   5.2| <br>|        Olive Yew|   5.1| <br>|        Aida Bugg|   5.5| <br>|Maureen Biologist|   4.9| <br>|       Teri Dacty|   5.4| <br>|        Peg Legge|   6.2| <br>|      Allie Grate|   6.5| <br>|          Liz Erd|   7.1| <br>| Constance Noring|   6.1| <br>|Lois Di Nominator|   5.6| <br>| Minnie Van Ryder|   1.2| <br>|     Lynn O’Leeum|   5.5| <br>+-----------------+------+</pre><p>As we can see that student_name=<strong>A. Mused </strong>has <strong>14.5</strong> height (which is an outlier) has been removed.</p><p><strong>Z-score Outlier imputation</strong></p><p>We can impute outlier by mean or median of the particular feature/column.</p><p>Here we are gonna see mean imputation.</p><pre><strong>from pyspark.sql import Window<br>from pyspark.sql.functions import *</strong></pre><pre><strong>column_subset = dataframe.columns<br>for col in column_subset:<br>    if dataframe.select(col).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        mean = dataframe.select(mean(col)).collect()[0][0]<br>        stddev = dataframe.select(stddev(col)).collect()[0][0]<br>        upper_limit = mean + (3*stddev)<br>        lower_limit = mean - (3*stddev)<br>        dataframe = dataframe.withColumn(col,when((dataframe[col]   &lt;lower_limit) | (dataframe[col]&gt;upper_limit),<br>round(mean(col).over(Window.orderBy(lit(1)))).cast(&#39;int&#39;)).otherwise(dataframe[col]))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+-----------------+------+ <br>|     student_name|height| <br>+-----------------+------+ <br>|Patty O’Furniture|   5.9| <br>|Paddy O’Furniture|   5.2| <br>|        Olive Yew|   5.1| <br>|        Aida Bugg|   5.5| <br>|Maureen Biologist|   4.9| <br>|       Teri Dacty|   5.4| <br>|        Peg Legge|   6.2| <br>|      Allie Grate|   6.5| <br>|          Liz Erd|   7.1| <br>|       <strong>  A. Mused|   6.0</strong>| <br>| Constance Noring|   6.1| <br>|Lois Di Nominator|   5.6| <br>| Minnie Van Ryder|   1.2| <br>|     Lynn O’Leeum|   5.5| <br>+-----------------+------+</pre><p>Look, we successfully imputed outlier by mean value of that feature/column. <strong>“| A. Mused| 6.0|”.</strong></p><p>Same way you can impute outlier by median.</p><p>This is all about Z-score outlier detection method, Now let’s look at <strong>IQR outlier detection method</strong>.</p><p><strong>Using IQR</strong></p><p><strong>IQR (interquartile range) </strong>is a measure of statistical dispersion, which is the spread of the data. The IQR may also be called the <strong>midspread</strong>, <strong>middle 50%</strong>, or <strong>H‑spread.</strong> It is defined as the difference between the 75th and 25th percentiles of the data.</p><p><strong>or</strong></p><p>The <strong>IQR (interquartile range) </strong>defines the difference between the third and the first quartile. Quartiles are the partitioned values that divide the whole series into 4 equal parts. So, there are <strong>3 quartiles</strong>. <strong>First Quartile</strong> is denoted by <strong>Q1 </strong>known as the <strong>lower quartile</strong>, the <strong>second Quartile</strong> is denoted by <strong>Q2 </strong>and the<strong> third Quartile </strong>is denoted by <strong>Q3 </strong>known as the <strong>upper quartile</strong>. Therefore, <strong>the interquartile range is equal to the upper quartile minus lower quartile.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgcwv8B1ikmR2Yq-lf2vYQ.png" /><figcaption>IQR</figcaption></figure><p>So formula of IQR is,</p><pre>IQR = <strong>Q3 - Q1</strong></pre><p>To detect the outliers using this method, we define a new range, let’s call it decision range, and any data point lying outside this range is considered as outlier and is accordingly dealt with. The range is as given below:</p><pre>Lower Bound: <strong>(Q1 - 1.5 * IQR)<br></strong>Upper Bound: <strong>(Q3 + 1.5 * IQR)</strong></pre><p>Any data point less than the <em>Lower Bound or </em>more than the <em>Upper Bound </em>is considered as an outlier.</p><p>Let’s find outlier on above DataFrame</p><pre><strong>for col_ in dataframe.columns:<br>    if dataframe.select(col_).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        q1,q3 = dataframe.approxQuantile(col_,[0.25, 0.75],0) <br>        IQR = q3 - q1<br>        lower_bound = q1 - (1.5*IQR)<br>        upper_bound = q3 + (1.5*IQR)<br>        dataframe = dataframe.filter((dataframe[col]&lt;lower_bound) |  (dataframe[col]&gt;upper_bound))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:</strong><br>+----------------+------+ <br>|    student_name|height| <br>+----------------+------+ <br>|        A. Mused|  14.5| <br>|Minnie Van Ryder|   1.2| <br>+----------------+------+</pre><pre><strong>Note: Outlier can be found in numerical column only</strong></pre><p>As we can see that <strong>A. Mused </strong>and<strong> Minnie Van Ryder </strong>both are<strong> </strong>the<strong> </strong>outliers.</p><p>Now let’s dive deep into the IQR outlier removal and outlier imputation technique.</p><p><strong>IQR Outlier removal</strong></p><pre><strong>for col_ in dataframe.columns:<br>    if dataframe.select(col_).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        q1,q3 = dataframe.approxQuantile(col_,[0.25, 0.75],0) <br>        IQR = q3 - q1<br>        lower_bound = q1 - (1.5*IQR)<br>        upper_bound = q3 + (1.5*IQR)<br>        dataframe = dataframe.filter((dataframe[col]&gt;lower_bound) &amp; (dataframe[col]&lt;upper_bound))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+-----------------+------+ <br>|     student_name|height| <br>+-----------------+------+ <br>|Patty O’Furniture|   5.9| <br>|Paddy O’Furniture|   5.2| <br>|        Olive Yew|   5.1| <br>|        Aida Bugg|   5.5| <br>|Maureen Biologist|   4.9| <br>|       Teri Dacty|   5.4| <br>|        Peg Legge|   6.2| <br>|      Allie Grate|   6.5| <br>|          Liz Erd|   7.1| <br>| Constance Noring|   6.1| <br>|Lois Di Nominator|   5.6| <br>|     Lynn O’Leeum|   5.5| <br>+-----------------+------+</pre><p>As we can see that student_name=<strong>A. Mused </strong>and<strong> Minnie Van Ryder </strong>(which are the outliers) have been removed.</p><p><strong>IQR Outlier imputation</strong></p><p>We can impute outlier by mean or median of the particular feature/column.</p><p>Here we are gonna see mean imputation.</p><pre><strong>for col_ in dataframe.columns:<br>    if dataframe.select(col_).dtypes[0][1]==&quot;string&quot;:<br>        pass<br>    else:<br>        q1,q3 = dataframe.approxQuantile(col_,[0.25, 0.75],0) <br>        IQR = q3 - q1<br>        lower_bound = q1 - (1.5*IQR)<br>        upper_bound = q3 + (1.5*IQR)<br>        dataframe = dataframe.withColumn(col_,when((dataframe[col_]&lt;lower_bound)  (dataframe[col_]&gt;upper_bound),round(mean(col_).over(Window.orderBy(lit(1))))).otherwise(dataframe[col_]))</strong></pre><pre><strong>dataframe.show()</strong></pre><pre><strong>O/P:<br></strong>+-----------------+------+ <br>|     student_name|height| <br>+-----------------+------+ <br>|Patty O’Furniture|   5.9| <br>|Paddy O’Furniture|   5.2| <br>|        Olive Yew|   5.1| <br>|        Aida Bugg|   5.5| <br>|Maureen Biologist|   4.9| <br>|       Teri Dacty|   5.4| <br>|        Peg Legge|   6.2| <br>|      Allie Grate|   6.5| <br>|          Liz Erd|   7.1| <br>|         A. Mused|   6.0| <br>| Constance Noring|   6.1| <br>|Lois Di Nominator|   5.6| <br>| Minnie Van Ryder|   6.0| <br>|     Lynn O’Leeum|   5.5| <br>+-----------------+------+</pre><p>Look, we successfully imputed outlier by mean value of that feature/column. <strong>“| A. Mused| 6.0|” </strong>and <strong>“| Minnie Van Ryder| 6.0|</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*vEMpD7FbswFzv82WrpuG4Q.jpeg" /></figure><h3>Conclusion</h3><p>So, to summarize, we have understood the <strong>overview of Pyspark,</strong> <strong>Drop null value, Handle missing value with imputation, Outlier detection, removal and imputation</strong>. We have seen these techniques with implementation in <strong>Pyspark </strong>and <strong>Python</strong>.</p><p>Now in second part we’ll be discuss about <strong>Drop feature/column, Drop duplicates, Convert categorical feature/column into numerical, Feature scaling, Train test split data </strong>therefor stay tuned😊 and stay healthy(●&#39;◡&#39;●)<strong>.</strong></p><p>Thank you for reading!</p><p>Do you have any question? if yes, please reach out to me on LinkedIn —<a href="http://linkedin.com/in/vishal-barad-926bb4134"> <strong>Vishal Barad</strong></a>. Happy to chat!</p><p><em>Any feedback would be much appreciated and if you liked what you’ve read please hold the clap button!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3f709c3c23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/python-data-preprocessing-using-pyspark-cc3f709c3c23">Python Data Preprocessing Using Pyspark</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you Needs to know about Virtual DOM]]></title>
            <link>https://medium.com/vedity/all-you-needs-to-know-about-virtual-dom-996626da34ab?source=rss----27a6213cb450---4</link>
            <guid isPermaLink="false">https://medium.com/p/996626da34ab</guid>
            <category><![CDATA[react-virtual-dom]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[dom-vs-virtual-dom]]></category>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[diffing-algorithm]]></category>
            <dc:creator><![CDATA[Amitparmar Dev]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 13:37:23 GMT</pubDate>
            <atom:updated>2021-12-14T13:37:23.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugYqCEGdcNDUgyCChB7Yeg.jpeg" /></figure><p>As a web developer, you may have come across the term called DOM many times. Furthermore, while working with JavaScript Library like React, you may have heard of one buzzword and that is Virtual DOM. This article will explain all you need to know about Virtual DOM. This will help you to uplift knowledge about core React concepts.</p><p>Before diving into Virtual DOM, let’s understand some basic terminologies first.</p><h4><strong>DOM</strong></h4><p>The <strong>DOM</strong> (“<em>Document Object Model</em>”) is a standard specified and documented by W3C (World Wide Web Consortium). It defines a standard for accessing documents like HTML, XML:</p><blockquote>“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”</blockquote><p>In context to HTML Document, the above definition says that DOM allows you to manipulate the content, structure, and style of your UI. DOM is a tree structure representation of HTML Document where root node represents the &lt;html&gt; element itself. All elements of the HTML document become child nodes subsequently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*V7iPUiXaNZFkIm0615F63Q.png" /><figcaption>From MDN WebDocs (Mozilla)</figcaption></figure><p>When you load the HTML document in the browser, it creates and maintains its document object model of the page by constructing a DOM tree of HTML elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*2rtcCt_r8jytI3ArXWunAg.png" /></figure><p>As shown in the example image, right-click on the web page and click on Inspect property to access the DOM Tree. Every time you make some changes in UI, the browser would repeat Reflow and Repaint all changed DOM tree nodes and their children in order to reflect the changes you made in your UI. This process of changing UI and making frequent updates in DOM may cost the performance of UI. It may also affect the page rendering and page load time. If your page is large and has a complex UI structure, it can be a very visible lagging in the loading of the page.</p><p>For instance, Lets create an HTML page that has a list element with some listed values. Now we are adding more elements to this list using JavaScript as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYnYhKOVUkxX48BYRCZOsg.png" /></figure><p>As demonstrated, we can update the list element in UI by manipulating the DOM object directly. This snippet shows that when we are adding a new list element, we are appending a new child element to the DOM which results in creating a whole new list element in UI. Every time when we make changes in the list, DOM creates and updates a new List to DOM. These DOM manipulations are very expensive operations and it also impacts UI performance especially for large-scale or complex UI applications.</p><h4>Virtual DOM in REACT</h4><p>To conquer the above mentioned drawbacks, in every DOM there is a corresponding Virtual DOM (VDOM) in React. Virtual DOM is an object identical to the JavaScript Object. In other words, Virtual DOM is simply a programming concept or a representation of a DOM object in memory as a virtual form. Virtual DOM has the same power and has properties and methods as the real DOM object. But Virtual DOM is not directly responsible for displaying elements on UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bb_aRAN0X4DT6-KFbhV4CQ.png" /><figcaption>Rendering/ Re-rendering React APP using Virtual DOM</figcaption></figure><p>When React App gets rendered for the first time on the browser, it basically creates a fresh copy of the DOM object as a render tree along with a Virtual DOM in memory for future updates. Later when a component gets updated due to state or props changes, the component and its children get re-rendered. While Updating Virtual DOM, React takes a snapshot of Virtual DOM at each time just before updating Virtual DOM. Now one contains the updated Virtual DOM and one which is just the preupdated version of this updated Virtual DOM. Now it compares the preupdated version with the updated Virtual DOM and works out the changes for instance what part of UI has been changed in the DOM. To update UI, React syncs the actual DOM object with Virtual DOM which is stored in memory using a library such as ReactDOM. This process is called <a href="https://reactjs.org/docs/reconciliation.html"><strong>Reconciliation</strong></a>.</p><p>Basically, the process of DOM updating for every in the React App requires comparisons between actual DOM and a Virtual DOM stored in memory. Though the comparison process ends with a new copy of the DOM tree, In a generic way React has to process O(n³) number of operations to transform one tree into another. In the case of complex apps, these comparisons are far too expensive.</p><p>Instead, React implements a heuristic O(n) algorithm based on two assumptions:</p><ol><li>Two elements of different types will produce different trees.</li><li>The developer can hint at which child elements may be stable across different renders with a key prop.</li></ol><h4>The Diffing in React</h4><p>Now React use the heuristic approach and implement <strong>Diffing Algorithm</strong> to update components optimally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*E_-iQKX_RBdBhSZMEEbaoA.png" /></figure><h4>Elements Of Different Types</h4><p>As we discussed, after first rendering, Virtual DOM creates a copy of the DOM tree in memory. In subsequent updates, Virtual DOM creates a snapshot of the render tree and check, If the root element of the render tree is different, it completely tears down the old tree and begins from the root of the new tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4FQAFZPJX7bjNqpHGi0fEw.png" /></figure><p>During this update, old DOM nodes are destroyed. Component instances receive componentWillUnmount(). When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive UNSAFE_componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.</p><h4>Elements Of The Same Type</h4><p>Once the component with the same type is updated, then the algorithm compares each and every attribute of the element. It compares and keeps the same valued attributes and changes only the new/differed attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lK2LFFcrIF8w6Q4QA1AYaw.png" /></figure><p>When the component with the same type gets updated, the same instance is maintained, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, on the underlying instance.</p><p>Next, the render() method is called and the <strong>Diffing algorithm</strong> recurses on the previous result and the new result.</p><h4>Updates in Child Elements</h4><p>When React finds any change in child elements, it just compares and calculates which children changed and updates it using <strong>Diffing algorithm</strong> as we have seen above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*FvsaAG4O3xd5S9aYsxrGvw.png" /></figure><p>In above example, List element gets changed when we add new list item &lt;li&gt;Orange&lt;/li&gt;. React match each child of &lt;ul&gt; and finger it out mutation in the list. Insertion of this list item at the beginning of the list will impact and it can worsen the performance here. React will mutate every child instead of a newly inserted item. To resolve this issue, we should use a key attribute. React uses the key to match children in the original tree with children in the subsequent tree when each child has been assigned a unique key value. For instance, adding a key to our inefficient example above can make the tree conversion efficient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*lxbjwZc5oQaYpWlrDq_12A.png" /></figure><h4>Conclusion</h4><p>So, to summarize, we have understood the basics of virtual DOM and its insights. We have seen that frequent DOM manipulations are expensive. <strong>Reconciliation</strong> is a process where Virtual DOM is a DOM representation in memory that is in sync with Real DOM. React use the <strong>Diffing algorithm</strong> to compare Virtual DOM and preupdated Virtual DOM to update DOM.</p><ol><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/DOM">https://developer.mozilla.org/en-US/docs/Glossary/DOM</a></li><li><a href="https://reactjs.org/docs/faq-internals.html#gatsby-focus-wrapper">https://reactjs.org/docs/faq-internals.html#gatsby-focus-wrapper</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=996626da34ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vedity/all-you-needs-to-know-about-virtual-dom-996626da34ab">All you Needs to know about Virtual DOM</a> was originally published in <a href="https://medium.com/vedity">Vedity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>