<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nitin Karthy on Medium]]></title>
        <description><![CDATA[Stories by Nitin Karthy on Medium]]></description>
        <link>https://medium.com/@nitin-karthy?source=rss-b07eb4f922c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SK0ewEuhVl1d3MNPZGAPPg.jpeg</url>
            <title>Stories by Nitin Karthy on Medium</title>
            <link>https://medium.com/@nitin-karthy?source=rss-b07eb4f922c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 00:07:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nitin-karthy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Learning JMH — Part 1: The setup]]></title>
            <link>https://nitin-karthy.medium.com/learning-jmh-part-1-the-setup-45e819fddae4?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/45e819fddae4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jmh]]></category>
            <category><![CDATA[performance-tuning]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 15:52:30 GMT</pubDate>
            <atom:updated>2025-01-18T16:03:37.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning JMH — Part 1: The setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RULk7dQg32hG-j94aoKuKw.png" /><figcaption>Source: <a href="https://www.flickr.com/photos/david_knight/7785169954">https://www.flickr.com/photos/david_knight/7785169954</a></figcaption></figure><p>At work, I am investigating a module of our Java application for concurrency improvements. For this, I have to dive deeper into Java’s concurrency features. The investigation would also need tools and techniques to identify bottlenecks and validate any improvements done. For this I am learning to use <a href="https://github.com/openjdk/jmh">JMH </a>(Java MicroBenchmark Harness). This series of posts aim to document my learning.</p><blockquote>The primary use of JMH for me, I anticipate, is that it will improve the dev experience by making the inner dev loop of debug-fix-test faster. I can use JMH to exercise a part (a class or method) with multiple threads, identify and profile bottlenecks, try out a fix and get fast feedback in mere minutes. Comparing that to building the whole application and deploying to performance test environment and firing a Gatling performance test suite which would take an hour on the minimum, I think the JMH workflow will make my investigation more productive.</blockquote><p>Apart from using JMH in my day job on the actual application, I aim to use it against toy programs utilizing <a href="https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/util/concurrent/package-use.html">java concurrency APIs</a> simulating issues so I can learn how JMH results highlight those issues. So, this series of posts will not feature basic introduction to JMH or how to start using it. For such purposes — a great introduction to the tool and it’s capabilities that got me started was this <a href="https://www.baeldung.com/java-microbenchmark-harness">Baeldung article</a>. But the most important learning material for me was the structured <a href="https://github.com/openjdk/jmh/tree/master/jmh-samples/src/main/java/org/openjdk/jmh/samples">examples</a> in the JMH GitHub repo.</p><p>I have setup a GitHub repo — <a href="https://github.com/nitinkarthy/java-concurrency-experiments/">https://github.com/nitinkarthy/java-concurrency-experiments/</a> — with the examples that I create for learning.</p><p>To begin, I have a class using <a href="https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/util/concurrent/locks/StampedLock.html">StampedLock</a> which will be the CUT (Class Under Test).</p><pre>public class BadImpl {<br>    StampedLock lock = new StampedLock();<br>    String previousValue = &quot;&quot;;<br>    String currValue = &quot;&quot;;<br><br>    public void methodOne() {<br>        long stamp = lock.writeLock();<br>        previousValue = currValue;<br>        currValue = &quot;&quot; + System.currentTimeMillis();<br>        lock.unlock(stamp);<br>    }<br>}</pre><p>To test this, I have the following JMH Benchmark definition</p><pre>@BenchmarkMode(Mode.AverageTime)<br>@OutputTimeUnit(TimeUnit.MICROSECONDS)<br>@State(Scope.Thread)<br>public class BenchmarkStampedLock {<br><br>    BadImpl badImpl;<br><br>    @Setup<br>    public void setup() {<br>        badImpl = new BadImpl();<br>    }<br><br>    @Benchmark<br>    public void benchmarkBadImpl() {<br>        badImpl.methodOne();<br>    }<br>}</pre><p>And finally to run the benchmark against the CUT, I have the main class.</p><pre>public class Main {<br>    public static void main(String[] args) throws RunnerException {<br>        Options opt = new OptionsBuilder()<br>                .include(BenchmarkStampedLock.class.getSimpleName())<br>                .forks(1)<br>                .warmupIterations(5)<br>                .measurementIterations(50)<br>                .threads(10)<br>                .build();<br>        new Runner(opt).run();<br>    }<br>}</pre><p>I use the main-method approach since it enables re-defining the benchmark quickly. There is also a <a href="https://plugins.jetbrains.com/plugin/7529-jmh-java-microbenchmark-harness">good plugin</a> for the same for IntelliJ Idea for similar work. For more repeated use of the benchmark it is recommended to compile and bundle the jar with maven and run the jar but since my use case is the dev-modify cycle of both the application code as well as the benchmark definition code, I use the main-method approach.</p><p>An important point to keep in mind is the benchmark code is not compiled and run as is. Using the annotations, <em>more java source files are generated by the internal JMH annotation processor</em> and those java files are then compiled and executed to generate the statistics.</p><p>Running the main class I see this.</p><pre># JMH version: 1.37<br># VM version: JDK 23.0.1, OpenJDK 64-Bit Server VM, 23.0.1+11<br># VM invoker: C:\java.exe<br># VM options: -javaagent:C:\JetBrains\IntelliJ IDEA 2020.3.1\lib\idea_rt.jar=51439:C:\JetBrains\IntelliJ IDEA 2020.3.1\bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8<br># Blackhole mode: compiler (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)<br># Warmup: 5 iterations, 10 s each<br># Measurement: 50 iterations, 10 s each<br># Timeout: 10 min per iteration<br># Threads: 10 threads, will synchronize iterations<br># Benchmark mode: Average time, time/op<br># Benchmark: me.nitkart.stampedlock.BenchmarkStampedLock.benchmarkBadImpl<br><br># Run progress: 0.00% complete, ETA 00:09:10<br># Fork: 1 of 1<br># Warmup Iteration   1: 0.119 �(99.9%) 0.002 us/op<br># Warmup Iteration   2: 0.106 �(99.9%) 0.001 us/op<br># Warmup Iteration   3: 0.102 �(99.9%) 0.001 us/op<br># Warmup Iteration   4: 0.110 �(99.9%) 0.001 us/op<br># Warmup Iteration   5: 0.104 �(99.9%) 0.001 us/op<br>Iteration   1: 0.117 �(99.9%) 0.004 us/op<br>Iteration   2: 0.107 �(99.9%) 0.001 us/op<br>#--- Some lines elided for brevity ---<br>Iteration  49: 0.160 �(99.9%) 0.001 us/op<br>Iteration  50: 0.102 �(99.9%) 0.001 us/op<br><br><br>Result &quot;me.nitkart.stampedlock.BenchmarkStampedLock.benchmarkBadImpl&quot;:<br>  0.155 �(99.9%) 0.027 us/op [Average]<br>  (min, avg, max) = (0.094, 0.155, 0.303), stdev = 0.054<br>  CI (99.9%): [0.128, 0.182] (assumes normal distribution)<br><br><br># Run complete. Total time: 00:09:12<br><br>Benchmark                              Mode  Cnt  Score   Error  Units<br>BenchmarkStampedLock.benchmarkBadImpl  avgt   50  0.155 � 0.027  us/op</pre><p>The key metrics here are the Score and the Error</p><ul><li><strong>Score </strong>of 0.155 𝜇s/op indicates that each execution of the method <em>BadImpl.methodOne</em> took on an average 0.155 microseconds.</li><li><strong>Error </strong>range of 0.027 indicates that; with 99.9% statistical confidence, the true mean lies within 0.027 - 0.027 (= 0.128𝜇s/op) and 0.027 + 0.027 ( = 0.182𝜇s/op)</li></ul><p>This concludes the 1st post. ToDos (for myself)for the next part</p><ul><li>Why is the error range percentage so high? Error rate percentage = (0.155–0.027)*100 / 0.155 = 82.5%. Are the results trustworthy?-</li><li>How to use the profiler feature of JMH to investigate bottlenecks in the code?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45e819fddae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing with Kotlin & Blockhound]]></title>
            <link>https://nitin-karthy.medium.com/using-blockhound-with-kotlin-7aa0a3f28364?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa0a3f28364</guid>
            <category><![CDATA[blockhound]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[coroutine-context]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 16:30:42 GMT</pubDate>
            <atom:updated>2023-04-04T16:18:31.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9Ea62GvzM7u_PQjrPXVGtw.jpeg" /></figure><p><a href="https://github.com/reactor/BlockHound">Blockhound </a>is a Java library that helps developers detect blocking calls in non-blocking threads.</p><blockquote>Blocking calls are operations that wait for some external event to happen, such as reading from a file or a network socket.</blockquote><p>Kotlin provides excellent support for programming non-blocking applications with suspend language feature and the coroutines libraries. However, in real world scenarios 3rd party Java/Kotlin libraries may need to be used to access specific IO scenarios. HTTP libraries, Database access libraries etc. It is essential that these libraries do not block the thread thereby negating the benefits of coroutines. All coroutines code that is designated to run on <em>Dispatchers.Default</em> must be ensured to be non-blocking by the developer. Blockhound helps us here to test the library features used for any blocking IO. Blcokhound can introspect deep into the call chain and lets us know of blocking operations not only in the 3rd party library but also in any dependencies within the 3rd party library.</p><p>This post explains the Kotlin project setup to unit test a 3rd library method for blocking IO.</p><p>If you are new to Blockhound it will be useful to read <a href="https://blog.frankel.ch/blockhound-how-it-works/">Nicolas Fränkel’s excellent intro</a> about it.</p><h3>How to use Blockhound with Kotlin in JUnit</h3><p>To use Blockhound properly in Kotlin, the following dependencies should be present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*gJWyReRJ7LJsr12clJdLGg.png" /><figcaption>Dependencies in Gradle</figcaption></figure><p><em>io.projectreactor.tools:blockhound</em> is the base Blockhound dependency. Including <em>org.jetbrains.kotlinx:kotlinx-coroutines-debug </em>dependency <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-debug/kotlinx.coroutines.debug/-coroutines-block-hound-integration/">configures </a>Blockhound to work with coroutines. It is essential to include the latter dependency to detect blocking code in Kotlin coroutines.</p><p>And the unit test code looks like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*MGv0aVXHYfDjwjV3XGi13w.png" /></figure><p><strong>Enable and start Blockhound</strong>: Before the test, Blockhound needs to be installed so that the agent can start tracking all blocking/non-blocking APIs withing the JVM. This is achieved by calling Blockhound.install() in a JUnit BeforeAll annotated method.</p><p><strong>Coroutine Context setup</strong>: Use <em>runTest</em> coroutine test builder and then start a new context with <em>withContext</em>. Dispatchers.Default must be used since Blockhound is configured by default to detect blocking APIs only when executed in this coroutine context. Dispatchers.Default and Dispatchers.Main (in Android) are the designated <a href="https://kt.academy/article/cc-dispatchers">coroutine contexts</a> for non-blocking IO and hence the need to switch to this context.</p><p><strong>Invoke the library method:</strong> In the block of the withContext, the library code may be exercised to verify it is non-blocking. If a blocking API is encountered, then the test fails. For example if we run the above code with this mock class with a blocking file read invocation…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*YfKD3EsuzBwE9vAW4ZsqfA.png" /><figcaption>Mock implementation of a Blocking API Library</figcaption></figure><p>… the test fails with the following following exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNxXamTou9UgAM9B07y8xA.png" /></figure><p>To summarize…</p><ol><li>Include the dependencies</li><li>Start Blockhound</li><li>Set the right coroutineContext</li><li>Exercise the library being evaluated for Blocking IO.</li></ol><p>If you do detect any Blocking API used within the library, you may wrap up the API call with a function using <em>withContext(Dsipatcher.IO)</em> to make it suspended and safe to use from other coroutine contexts. See <a href="https://kt.academy/article/cc-dispatchers">here</a>. It does not make the API non blocking magically, but it runs in the IO context which is designed to run blocking threads.</p><h3>Closing Thoughts</h3><p>It is important to test all variants, happy-paths and exception-paths of the 3rd party library to prove that there are no blocking APIs used underneath. Blockhound performs dynamic analysis and unless the code path (containing blocking APIs) is not exercised by your code, it cannot detect and alert you.</p><p>Although these JUnit tests are valuable for exploring the 3rd party library from a blocking APIs perspective, I do not add them permanently to my application’s test suite. I use these Blcokhound tests in a throw-away exploratory manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa0a3f28364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Composition to reduce prop drilling in React]]></title>
            <link>https://nitin-karthy.medium.com/using-composition-to-reduce-prop-drilling-in-react-375dafbb681d?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/375dafbb681d</guid>
            <category><![CDATA[composability]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 07:24:46 GMT</pubDate>
            <atom:updated>2021-10-28T10:49:59.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*x4ogYvz4FRrUXsowYIF4fA.jpeg" /><figcaption><a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4474947">https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4474947</a></figcaption></figure><p>Prop drilling is how ReactJS facilitates one way data binding. While it is very easy to follow when developing components top-down; it is very cumbersome to debug a React component that receives a prop which is being managed by other component many levels higher. You can use the <a href="https://youtu.be/DQjMiKEwl_E">React DevTools</a> to visually follow the props hierarchy but still debugging is cumbersome.</p><p>There are many approaches to reduce the prop drilling if it gets too deep. Some of which are</p><blockquote>Using <a href="https://reactjs.org/docs/context.html">React Context</a> API</blockquote><blockquote>Using <a href="https://reactjs.org/docs/render-props.html">Render Props</a> (or HOC)pattern</blockquote><blockquote>Using Composition pattern</blockquote><p>In this post, I shall explore the “Using Composition pattern” approach.</p><p>Let’s start with an example of nested React components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6bmN7FmtqAQVZrs1DmZpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqlNsiquzwEEQ0I-cdgKkQ.gif" /></figure><p>Here, the <em>RootComponent </em>is managing a state variable and it is being used in <em>TargetLeafComponent</em>. For the sake of illustration all these components are listed in the same file, but it may be spread across many source JS files. The problems with this approach in a project of few 1000 lines o code are:</p><ol><li>Declaration of the state variables and their usage are in separate compoennts which can be in different files. Finding this flow when analyzing source code is extremely difficult and may require the application to be started each time and tracing props being drilled via React DevTools.</li><li>The intermediate components’ — <em>FirstLevelInnerComponent </em>&amp; <em>SecondLevelInnerComponent — </em>props are polluted so that they can be passed down. These intermediate components act like a proxy. For succinctness only 2 props are shown here, but in a real application there could be many props which makes the problem worse. Some would argue that <a href="https://reactjs.org/docs/jsx-in-depth.html#spread-attributes">prop-spreading</a> is a solution, but I consider it to be an even bigger problem because it is just syntactic sugar, but the semantics are still the same for whoever is reading the code.</li></ol><p>Re-factoring it to a Composition pattern…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDTk3SYiwcmRjM9CnOCdRw.png" /></figure><p>It is evident that the 2 negative aspects of prop drilling are avoided here</p><ol><li>The <em>RootComponent </em>has the state variables defined and also in the same component we see that the <em>TargetLeafComponent </em>being wired with the props. So we see the definition and the usage close by (in the same file) increasing readability.</li><li>The intermediate components — <em>FirstLevelInnerComponent </em>&amp; <em>SecondLevelInnerComponent</em>— are not burdened with proxying the props down. Elimination of un-necessary props (if you think of the React component as a function, the elimination of un-necessary args) is a readability win!</li></ol><p>So, what exactly are the recipe steps to achieve this pattern?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmBWvq68iwhu5hx1QdZOcw.png" /></figure><p><strong>Step 1</strong>: Identify intermediate components where props are simply being proxied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*dygsyNfrORUp53QbY716xg.png" /></figure><p><strong>Step 2</strong>: Refactor them by removing proxied-only props and instead, just render the children prop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*QsAZTfd0laWpPjn1E6Anbw.png" /></figure><p><strong>Step 3</strong>: Compose them by nesting the React components where needed. This would be the root component where some state management logic exists.</p><p>All code used in this post can be found in this GitHub Repo</p><p><a href="https://github.com/nitinkarthy/react-composition">GitHub - nitinkarthy/react-composition: Created with CodeSandbox</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375dafbb681d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom type conversions in Spring Data Projections]]></title>
            <link>https://nitin-karthy.medium.com/custom-type-conversions-in-spring-data-projections-48db914aaa39?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/48db914aaa39</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 06:37:56 GMT</pubDate>
            <atom:updated>2021-06-14T06:37:56.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbZ4d3IzTmi46SzfihlJqw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chrislawton?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Lawton</a> on <a href="https://unsplash.com/s/photos/transformation?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Spring Data provides the <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections">feature</a> to execute any native SQL query and de-serialize the result-set into a Java object. This is a very handy 😍 feature in situations where an SQL statement can <em>project</em> out the data from our tables in a specific manner that is not easily/elegantly obtained via loading JPA entities from the DB.</p><p>The way the de-serialization works is when we provide an interface that matches the column names being returned from the SQL query. SO, for e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc08bb69607d0adae26c2d2e3d330d85/href">https://medium.com/media/dc08bb69607d0adae26c2d2e3d330d85/href</a></iframe><p>The interface <em>NameProjection</em> has the getter methods matching the name and types of the columns being queried (projected) from the SQL query.</p><blockquote>The native queries in the examples are simplistic for illustratory purposes only. In real life they are more complex.</blockquote><p>Recently we had a situation where we had to query the DB tables and extract some images. They are stored in the DB as BLOBs, but the service layer of our application expects it to be retrieved as a byte array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56d1a63425e04b8a4a08606bca0877ae/href">https://medium.com/media/56d1a63425e04b8a4a08606bca0877ae/href</a></iframe><p>But, this did not work. We were getting a cryptic error.</p><pre><strong>java.lang.IllegalArgumentException: Projection type must be an interface!</strong><br>    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.11.RELEASE.jar:4.3.11.RELEASE]<br>    at org.springframework.data.projection.ProxyProjectionFactory.createProjection(ProxyProjectionFactory.java:110) ~[spring-data-commons-1.13.7.RELEASE.jar:na]<br>    ...</pre><p>Googling reveled similar issues faced by other users like <a href="https://stackoverflow.com/questions/55247358/spring-jpa-java-lang-illegalargumentexception-projection-type-must-be-an-int/55306892">this</a>, <a href="https://stackoverflow.com/questions/46825928/java-lang-illegalargumentexception-projection-type-must-be-an-interface-error">this</a>, &amp; <a href="https://stackoverflow.com/questions/53836889/exception-when-trying-to-use-projection-for-entity-with-clob-type-property-in-sp">this</a>.</p><p>The key issue is that <strong><em>Spring Data is unable to convert the BLOB JDBC type retrieved into a byte array</em></strong>. The recommended answer is to create a converter and register it with spring. More details in this <a href="https://stackoverflow.com/a/65355897/1533977">answer</a>.</p><p>But, there is a simpler method to implement the conversion logic using <strong>Java 8 default interface</strong> methods. This seems to be better in terms of maintainability since the conversion logic is co-located with the projection code when compared to separate pieces of Spring config code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba439e096b3954f1c93531d0c0438d0/href">https://medium.com/media/0ba439e096b3954f1c93531d0c0438d0/href</a></iframe><p>At the place where the projection proxy object will be consumed, make sure to use getImage()!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48db914aaa39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use Render Props pattern?]]></title>
            <link>https://nitin-karthy.medium.com/when-to-use-render-props-pattern-8634649fcfe8?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8634649fcfe8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 13:13:07 GMT</pubDate>
            <atom:updated>2020-11-28T13:13:07.335Z</atom:updated>
            <content:encoded><![CDATA[<p>Much has been talked and written about WHAT Render Props pattern is within the React framework. Although I have used libraries that implement the pattern and required me to write the function-prop; I did not have an intuitive sense for the pattern. I was always a user of the pattern (via a library) and could never use it to re-factor my own code. Recently I think I have gained an intuitive sense and here’s an attempt to explain it.</p><p>Let’s start with a simple example of plain React usage and increase the requirements on our components when Render Prop will start to make sense. We have a <strong>&lt;Card&gt;</strong> component from a library that needs to be colored with the color of the day in our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b96ce74ad91785a39d9a9e5f4450cee3/href">https://medium.com/media/b96ce74ad91785a39d9a9e5f4450cee3/href</a></iframe><p>So, we’ve created <strong>&lt;ColoredCard&gt;</strong> that fetches the color of the day and supplies the info via a prop to the <strong>&lt;Card&gt;</strong>. And we use the <strong>&lt;ColoredCard&gt;</strong> in our application. All’s well!</p><p>A few days later, along comes a new requirement that states all the <strong>&lt;Modal&gt;</strong>s in our application should also be colored with the color of the day. Now we need a <strong>&lt;ColoredModal&gt;</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b901da09b7babf181600b18ee60a1468/href">https://medium.com/media/b901da09b7babf181600b18ee60a1468/href</a></iframe><p>It’s easy to see that DRY principle is being violated here. The are only a few changes between the 2 components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLQ62mUd4eCirVtUg1Gw1g.png" /><figcaption>Diff</figcaption></figure><p>To adhere to DRY principle, we’d like to…</p><ul><li>Extract out the common logic of getting color of the day into it’s own component</li><li>Pass the color value as a prop to ANY interested component.</li></ul><p>Let’s extract out the color logic into a generic component which can be used to COMPOSE other components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f34e6b690404b9848ccec3a6411f1d00/href">https://medium.com/media/f34e6b690404b9848ccec3a6411f1d00/href</a></iframe><p>We have extracted the color fetching logic into <strong>&lt;Colored&gt;</strong> and then used composition at the usage site by accepting ANY component via the propToColorize prop.</p><blockquote>But it doesn’t work because the actual color prop value is <strong>not</strong> being passed from <strong>&lt;Colored&gt;</strong> to <strong>&lt;Card&gt; </strong>or <strong>&lt;Modal&gt;.</strong></blockquote><p>Since we are accepting a component as a prop variable, we cannot pass it a prop. Here’s where the Render Prop pattern comes to our rescue. As a first step, let’s make propToColorize accept a <strong>function</strong> rather than a plain component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/488ac05ea184589879813b25fb66a01b/href">https://medium.com/media/488ac05ea184589879813b25fb66a01b/href</a></iframe><p>Now, we have <strong>&lt;Colored&gt;</strong> accepting a function prop <em>propToColorize</em> which eventually gets the color value as a function argument. But we wanted to colorize a component like Modal or Card… what did we achieve with colorizing a function? 🤔</p><p>It becomes clear when we see the usage site for COMPOSITION using <strong>&lt;Colored&gt;</strong>. <em>The function being passed as a prop has the component to be colored embedded in it</em>. And, the function argument is used as a bridge to pass the color value from <strong>&lt;Colored&gt;</strong> to <strong>&lt;Card&gt; </strong>or <strong>&lt;Modal&gt;.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a469d8070302f4c71239fa2eda917e/href">https://medium.com/media/e1a469d8070302f4c71239fa2eda917e/href</a></iframe><blockquote>So, the pass-a-function-as-a-prop trick is used just for being able to pass in a prop into the component being used inside the function body 💡 !!!</blockquote><p>So, WHEN should we use the pattern? When we need to…</p><ul><li>Extract out the common logic into a generic component</li><li>Compose the generic component with a consumer component by passing information from the generic component into the props of the consumer component.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8634649fcfe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Readable queries when working with Gremlin Console]]></title>
            <link>https://nitin-karthy.medium.com/readable-queries-when-working-with-gremlin-console-20a33c915b35?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a33c915b35</guid>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[readable-code]]></category>
            <category><![CDATA[readability]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[tinkerpop]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 16:30:59 GMT</pubDate>
            <atom:updated>2018-09-20T16:30:59.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I am fiddling with Graph data structures and am playing with the excellent Gremlin from the Apache <a href="http://tinkerpop.apache.org/">Tinkerpop3 </a>stack. I don’t get to work on it as often I’d like to. Once I get back to it after a few days or a week; understanding the queries I wrote earlier takes some time to get loaded back into memory. No offence to the Gremlin API designers. IMO, they have done an excellent job to make a fluent, chainable and composable API. It’s just that I am still learning the API and it’s semantics and a few days of not looking at me makes it rusty. This is one of my queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*q-Pg1KaLcMzedNrj_-Ftkw.png" /></figure><p>I was wondering whether the queries can be written similar to the <a href="https://dzone.com/articles/the-better-way-to-write-sql-query">readable SQL style</a> — broken into lines, indented, commented etc. to aid readability.</p><p>My first attempt was to split chunks of the query into lines. This should help me to read the query in logical chunks, and also comment out certain sections and test. This was what I tried first in the Gremlin console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*UC1saW-Em0076In1t8hNwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*jgseawnfkG0rzQjVMV_RCg.png" /></figure><p>OK, Gremlin barfed on me. It doesn’t seem to like the newlines. After some fiddling around, I realized that putting the <strong>dots at the end</strong> of each line rather than at the beginning of the subsequent line seems to play well with Gremlin console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*Oie3r5tiI0kEmKn53DxkPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*6dRJ3Hl1dnaKuizwEakflw.png" /></figure><p>Using this, we can comment out sections of the query for debugging purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*TEixV_0wh3uLgoMAnH-caw.png" /></figure><p>Also, meaningful comments can be provided to explain the queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*N7_ekFekZRwMYnYRf9YzDQ.png" /></figure><p>Looks good to me for now… I hope I will come back to it next time and grok it faster. Also, I hope it would be easy to pass on to team members when the time comes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a33c915b35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring an imperative function to a functional compose-able form]]></title>
            <link>https://nitin-karthy.medium.com/refactoring-an-imperative-function-to-a-functional-compose-able-form-642fa9f054a5?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/642fa9f054a5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[lodash]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Fri, 14 Sep 2018 18:09:27 GMT</pubDate>
            <atom:updated>2018-09-14T18:09:27.047Z</atom:updated>
            <content:encoded><![CDATA[<p>I am following the great Functional Programming podcast <a href="https://soundcloud.com/lambda-cast">LambdaCast</a>. We have been using Lodash for some time now. But I discovered that Lodash has a cousin Lodash FP which helps program in a more functional compose-able way. It was claimed that the functinal compose-able style of programming makes the code more readable. I wanted to test it out.</p><p>In my code-base, I had this function that takes a string, if it has newline characters, converts it into an array with br tags in it. Eventually it would be used in a JSX expression. For the sake of this example the br tag is a string. I can see how the intent of this function is obscured by the loop constructs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b4d7a661382e687d008f54c240652e/href">https://medium.com/media/68b4d7a661382e687d008f54c240652e/href</a></iframe><p>This is the version that I had re-factored it to before knowing the compose-able style using Lodash. This is more terse, but it looks more cryptic than the imperative version. I could have broken it into a couple of statements, but one of my stretch goals was to define the function as a an <a href="https://dev.to/promhize/javascript-in-depth-all-you-need-to-know-about-expressions-statements-and-expression-statements-5k2">expression</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cc6ab93875e797a400ef8be7b5851f2/href">https://medium.com/media/5cc6ab93875e797a400ef8be7b5851f2/href</a></iframe><p>And, this is the version that follows the compose-able style (at least, i think so). Sure looks more readable to me than either versions above. flow is a lodash/fp function which gives a new function where the order of functions is more readable. In the snippet above, any one trying to read the function will have to start understanding the innermost nested function and read outwards. flow makes it more readable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dbdc98cb8f5efab2186d20b292bca6d/href">https://medium.com/media/8dbdc98cb8f5efab2186d20b292bca6d/href</a></iframe><p>A full working example can be found here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2FImperativeToFunctional%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2FImperativeToFunctional%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/c690d5dab88b43fa4c3f61232f72af69/href">https://medium.com/media/c690d5dab88b43fa4c3f61232f72af69/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642fa9f054a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serially fetching API results using JS Promises]]></title>
            <link>https://nitin-karthy.medium.com/serially-fetching-api-results-using-js-promises-1d03ad277ef1?source=rss-b07eb4f922c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d03ad277ef1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Nitin Karthy]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 18:10:23 GMT</pubDate>
            <atom:updated>2018-07-05T18:10:23.032Z</atom:updated>
            <content:encoded><![CDATA[<p>On my current React project, I needed to control access to a back-end API in a serial fashion. The application required entities to be added from the front-end to a back-end processing REST API. Each item takes 3–5 seconds to process. The next item’s processing may be affected adversely if done in parallel with the previous item’s processing.</p><p>There were 3 options available.</p><ul><li>Accept all requests from the front-end in parallel at the back-end. Serial process it at the back-end. But this meant potential timeouts at the front-end if many parallel requests were made.</li><li>Block the UI until an item is processed so that the next items’ processing may not be triggered.</li><li>Queue the requests at the front-end in the browser. This would allow the UI to be flexible to add more items by the user. Better UX. This was the approach I waned to try.</li></ul><p>My first attempt used traditional JS callbacks…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-cb%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-cb%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d29f4e060cb5db1f75c607776e45334a/href">https://medium.com/media/d29f4e060cb5db1f75c607776e45334a/href</a></iframe><p>Next, I wanted to try implementing the same using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promises </a>instead of callbacks. I had always used a promise object returned by some API but never had to create one. So, this was a learning opportunity. Also, it would help preserve the same fetch semantics in my React components to invoke APIs…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-v1%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-v1%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b616bf97825c240d523ed99d3b8c1022/href">https://medium.com/media/b616bf97825c240d523ed99d3b8c1022/href</a></iframe><p>What’s happening is…</p><ol><li>An incoming request creates a new promise from a fetch invocation and returns the promise to the caller.</li><li>A copy of this promise is kept in <em>lastRunningRequestsPromise</em>.</li><li>The next fetch invocation is not invoked directly.</li><li>A new Promise object is created and returned to the caller.</li><li>The new Promise object’s executor function hooks to the <em>.then()</em> method of the previous promise. Basically it will be invoked only when the previous promise (API) returns.</li><li>When the subsequent fetch API returns, the output obj is sent back to original caller via invoking the resolve callback function argument of the promise created in step 4.</li></ol><p>While testing, I realized that the if condition can be avoided by creating a promise at the beginning that immediately resolves. And the final version is …</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-v2%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40NitinKarthy%2Fqueued-fetch-v2%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/80e8aa81e0040ecd224e21b1c2520050/href">https://medium.com/media/80e8aa81e0040ecd224e21b1c2520050/href</a></iframe><p>Although the final version is just 15 lines (minus the testing code), it took a good 2 hours of wrapping my head around JavaScript Promises to complete it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d03ad277ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>