<?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 Nilanjan 🌱🌱 on Medium]]></title>
        <description><![CDATA[Stories by Nilanjan 🌱🌱 on Medium]]></description>
        <link>https://medium.com/@nilthedev?source=rss-9154a21eb659------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x3V85SGIqjcQ36r3ktH9Sg.png</url>
            <title>Stories by Nilanjan 🌱🌱 on Medium</title>
            <link>https://medium.com/@nilthedev?source=rss-9154a21eb659------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:49:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nilthedev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Access Database with Kotlin using JDBC: The Fundamentals]]></title>
            <link>https://levelup.gitconnected.com/how-to-access-database-with-kotlin-6b86f6680cd7?source=rss-9154a21eb659------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b86f6680cd7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[jdbc]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Nilanjan ]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 02:33:59 GMT</pubDate>
            <atom:updated>2021-12-04T15:41:31.923Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how databases are accessed at the low-level using JDBC</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DVDmqbyX5GAIiYdIo0pzQ.png" /></figure><p>Accessing databases is a common task. All the server-side applications access databases in one way or another. As long as Kotlin is concerned it inherits a rich set of libraries from the Java world, thanks to the interoperability. These libraries provide dazzling features like ORM, typesafe SQL, and so on.</p><p>However, if you are doing this for the first time, all the sophisticated libraries may not make much sense. To get you up and running, in this article, I will give you an introduction to JDBC.</p><p>Specifically, you would learn about,</p><ol><li>What is JDBC? And how to use it with Kotlin?</li><li>What is a JDBC URL?</li><li>How to establish a connection with a database and execute SQL queries.</li><li>What is connection pooling and how to implement it with HikariCP?</li></ol><h4><strong>What is JDBC?</strong></h4><p>JDBC stands for Java Database Connectivity. It’s a low-level library that provides functionality to interact with a database. To use JDBC you don’t have to depend on any third-party library. It comes bundled with all the JDKs out there.</p><h4>How to use JDBC with Kotlin?</h4><p><em>The code used in this article is available in this </em><a href="https://github.com/nilTheDev/jdbc-article"><strong><em>Github </em>Repository</strong></a><em>.</em></p><p><strong>Step 1:</strong> Prepare a table in your database</p><p><strong>Step 2:</strong> Find the JDBC driver of your database and add it to your project</p><p><strong>Step 3:</strong> Establish a connection using a JDBC URL</p><p><strong>Step 4:</strong> Write and execute SQL queries</p><h4>Prepare a table</h4><p>Let’s create a table called users and populate it with some data. I will be using PostgreSQL. You can use the database of your choice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f95db9448da8e1716380d23228ead7/href">https://medium.com/media/c3f95db9448da8e1716380d23228ead7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9577a12d628c829a0f1535e524a3dfe/href">https://medium.com/media/e9577a12d628c829a0f1535e524a3dfe/href</a></iframe><p>Now the result of a SELECT * FROM users query looks something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2fbc53dbe420e0b122e0670e4405f92/href">https://medium.com/media/f2fbc53dbe420e0b122e0670e4405f92/href</a></iframe><h4>Add the JDBC driver to your project</h4><p>To access this data from your Kotlin code, you have to include the JDBC driver of your database as a Gradle dependency. If you are not using PostgreSQL, you need to find the JDBC driver of the database you are using. A simple Google search would suffice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cfaa3b95012c82da1772b800660e8f6/href">https://medium.com/media/3cfaa3b95012c82da1772b800660e8f6/href</a></iframe><p>Now, we’ll see how to retrieve the data from the database.</p><h4>Create a model class</h4><p>First, create a model class for the data we are about to receive from the database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cbc40720ceda5dbe95b63d08a29d07a/href">https://medium.com/media/4cbc40720ceda5dbe95b63d08a29d07a/href</a></iframe><h4>Establish a database connection via a JDBC URL</h4><p>To create a database connection you would need a JDBC URL. Here is how the JDBC URL looks like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3ebacec4df4d4f16081b2b650b1402f/href">https://medium.com/media/c3ebacec4df4d4f16081b2b650b1402f/href</a></iframe><p>As you can see the JDBC URL consists of three major components. The host name , the port number and the database name .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0m-YLy02hhHHUZyDtIdIAQ.png" /><figcaption>broken down version of a JDBC URL</figcaption></figure><p>To create a connection, use the DriverManager.getConnection method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d16645e76785b9021f4051c4ea46178d/href">https://medium.com/media/d16645e76785b9021f4051c4ea46178d/href</a></iframe><p>The first argument of the DriverManager.getConnection method is the JDBC URL, the second argument is the username of the database and the last argument is the password for that particular user.</p><p>You can verify whether the connection is valid or not using the isValid() method on a Connection object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ab397e8725fb113532235d4000352a/href">https://medium.com/media/b8ab397e8725fb113532235d4000352a/href</a></iframe><h4>Write and execute SQL queries</h4><p>Now, you can write and execute SQL queries using the connection. But as JDBC is a low-level library everything needs to be done by hand.</p><p>To execute a SELECT query using the connection you need to,</p><ol><li>Prepare a SQL statement</li><li>Execute the statement.</li><li>Iterate through the ResultSet and retrieve values with methods such as getInt or getString</li></ol><p>Consider the following example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0b760cc7e4691d07a1c7bc908336427/href">https://medium.com/media/f0b760cc7e4691d07a1c7bc908336427/href</a></iframe><h4>What is connection pooling?</h4><p>An introduction to database interaction is incomplete without learning about connection pooling.</p><p>Say you are writing a server-side application. Every time a user hits an endpoint you open a fresh database connection to fetch data. This is inefficient because opening a database connection is an expensive task and should not be done over and over. This is the exact problem that connection pooling can solve.</p><p>With connection pooling, you can open multiple connections that would be alive throughout the lifetime of the application. These connections would be encapsulated into a DataSource. Whenever you need to access the database, instead of creating a fresh connection you would ask the DataSource for one. The DataSource would give you a connection from the connection pool<strong>.</strong></p><p>Numerous libraries would equip you with convenient APIs for implementing connection pooling. HikariCP<strong> </strong>is one of the best libraries that satisfies this requirement. By default, it uses 10 connections as the maximum limit. And it is easily modifiable. If you want to know more about configuring pool size check out this guide: <a href="https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing"><strong>About Pool Sizing</strong></a>.</p><p>Let’s see a quick example of connection pooling using HikariCP.</p><p>Start with adding the dependency to your build.gradle.kts file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78537c8a5f442c46a222efb99ffd62e/href">https://medium.com/media/a78537c8a5f442c46a222efb99ffd62e/href</a></iframe><p>To initialize a DataSource<strong>,</strong></p><ol><li>Create a HikariDataSource() object</li><li>Set the JDBC URL</li><li>Set the username</li><li>Set the password</li><li>Obtain the connection from the DataSource</li><li>Use the connection the way I demonstrated above</li></ol><p>Here is a working example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/158fbeecf7e9dce59b5218b99f4f51c3/href">https://medium.com/media/158fbeecf7e9dce59b5218b99f4f51c3/href</a></iframe><p><strong>Note: </strong>There are multiple ways for initializing a DataSource with HikariCP. Read the <a href="https://gist.github.com/nilTheDev/c681d54b8c6e85369e3249a40ecf03e5"><strong>initialization section</strong></a> of the README file of the <a href="https://github.com/brettwooldridge/HikariCP"><strong>HikariCP Github Repository</strong></a>.</p><h4>Why do we need additional abstraction over JDBC?</h4><p>As you can see, accessing databases withJDBC can quickly become a cumbersome task. The process is error-prone and a lot of heavy lifting and discipline is required from the developer-end. This is where the libraries and frameworks come in handy.</p><p>When it comes to libraries and frameworks to access databases there are a variety of options to choose from. You may opt to use a full-fledged ORM like Hibernate, or you can use something low-level like JDBI. JDBI provides a convenient layer of abstraction over JDBC. There are a few Kotlin-first libraries as well. The most popular is the Exposed library from Jetbrains. Exposed comes in two flavors. A typesafe SQL wrapping DSL and lightweight data access objects.</p><p>To get a comprehensive overview of all the database libraries in the Java world you may read the article linked below.</p><p><a href="https://www.marcobehler.com/guides/java-databases"><strong>Java &amp; Databases: An Overview of Libraries &amp; APIs by Marco Behler</strong></a></p><h4>Here is a brief summary:</h4><ol><li>You can access a database through the low-level JDBC library. It comes bundled with all the JDKs out there. So, no need for another dependency.</li><li>To connect with a particular database you need the JDBC driver for that particular database.</li><li>All libraries for databases in the JVM world are built on top of JDBC.</li><li>While working on a real project you should be using a connection pooling mechanism. Connection pooling lets you keep a small number of database connections alive. Instead of creating a fresh connection every time, you (re)use a connection from the pool.</li><li>HikariCP is a good choice while implementing connection pools. By default, it uses 10 connections as the maximum limit. And it is easily modifiable.</li></ol><h4>Wrapping Up</h4><p>Irrespective of the library you decide to go with, now you have a basic understanding of what’s going on under the hood while you are querying your database from the application layer.</p><p>I am glad that you have finished reading the article. I would really appreciate a couple of words on your thought. ✏️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b86f6680cd7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-access-database-with-kotlin-6b86f6680cd7">How to Access Database with Kotlin using JDBC: The Fundamentals</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reflection using Kotlin]]></title>
            <link>https://levelup.gitconnected.com/understanding-reflection-using-kotlin-a5874bf63010?source=rss-9154a21eb659------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5874bf63010</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[reflections]]></category>
            <dc:creator><![CDATA[Nilanjan ]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 03:22:56 GMT</pubDate>
            <atom:updated>2021-11-08T12:29:43.877Z</atom:updated>
            <content:encoded><![CDATA[<h4>Almost all frameworks or libraries utilize the power of reflection under the hood. Knowing about it would make you a better developer.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfxqdwgOPniZ5rhB1PO23A.png" /></figure><p>Have you ever wondered how the libraries or frameworks, that rely on the JVM-based languages such as Kotlin or Java, work under the hood? To me, it had been some sort of <em>black magic</em> unless I came across the idea of reflection. In libraries like Retrofit or Kotlin-serialization, you define a bunch of classes or interfaces and annotate them with some predefined keywords and it works perfectly in the runtime. The same is true for Android. You extend some classes such as Main-Activity or ViewModel and the end result is a functioning app.</p><p>However, it is really not obvious that how do these libraries know what you defined or exactly where you did that. There must be some mechanism built into these languages that allow playing with the statically defined classes and interfaces at runtime. This is precisely what reflection is built for.</p><p>In this article, I would attempt to demystify reflection through a few trivial code examples. I understand that you are not always supposed to dig into the details of a library. It is crucial for a developer to be able to appreciate abstraction. Although, getting a high-level glimpse of how these frameworks function under the hood would, of course, augment your development toolbox.</p><p>Who knows you might be building a bleeding-edge framework, that solves many problems of those that are in existence right now, in the upcoming years or so.</p><p><strong>Disclaimer:</strong> <em>Keep in your mind that most frameworks or libraries will not always be using reflection for everything. Since reflection is a slower process as compared to the other primitive programming stuff the frameworks would implement intermediate compilers.</em></p><h4>What is reflection?</h4><p>In a nutshell, reflection enables you to reference statically defined classes, functions, or interfaces at runtime. Post that you can introspect it. You may,</p><ol><li>Access the properties or functions of the class irrespective of the access-modifier</li><li>Find out whether any member of that class has been annotated with some particular annotations</li><li>Manipulate the class/interface as necessary</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ArjhOfXGB5KdzlA3l1nBg.png" /></figure><p>That is an immense power. As I have mentioned you can even manipulate the private properties of a class. So, yeah, you have to be scrupulous while using reflection as it breaks encapsulation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRN6OnheJ9ZEm4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRN6OnheJ9ZEm4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRN6OnheJ9ZEm4%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="172" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a86f456e3f0c1ee1db4ed243fb670e8/href">https://medium.com/media/0a86f456e3f0c1ee1db4ed243fb670e8/href</a></iframe><h3>Dependency</h3><p>Before using reflection in your Kotlin project you have to add the following dependency to your build.gradle file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c2e64fab731588ae8d0b60d582e4989/href">https://medium.com/media/8c2e64fab731588ae8d0b60d582e4989/href</a></iframe><h4>Reflection in action</h4><p>We will begin by defining a dummy class that would let you taste reflection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d2c6c53a86d72303e3b2b7879c97ff/href">https://medium.com/media/c6d2c6c53a86d72303e3b2b7879c97ff/href</a></iframe><p>We can, now, instantiate the class itself either from the class name or from the object of that class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad78b599a973224cd564d0151c7f87ef/href">https://medium.com/media/ad78b599a973224cd564d0151c7f87ef/href</a></iframe><p>As shown in the code snippet, there is two way to grab the reference of the class. We can either user className::class or objectReference::class.</p><p>To obtain the Java equivalent class you may use the className/objectReference::class.java syntax.</p><p>While these are almost the same, there are subtle differences between the types that these varying syntaxes would produce.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa10387ff173647c511bf8efd06c880d/href">https://medium.com/media/fa10387ff173647c511bf8efd06c880d/href</a></iframe><p>Why the designers of the language have decided to use two different types, i.e KClass&lt;T&gt; and KClass&lt;out T&gt; or Class&lt;T&gt; and Class&lt;out T&gt;, is beyond the scope of this article.</p><p>If you are familiar with Kotlin’s way of expressing type-variance in generics you may have already understood that the interfaces which have &lt;out T&gt; are actually implemented with declaration-site variance. If you have no idea what type-variance actually is you may later check out <a href="https://typealias.com/guides/illustrated-guide-covariance-contravariance/">this enlightening illustrated guide on Kotlin’s type variance</a>. However, you need not worry much about type-variance right now. You don’t need to learn it to understand reflection.</p><h4>Accessing the member functions</h4><p>It is time that we do something with the class reference. Let’s start with something simple — print the name of all the member functions of that class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0294cec095d72bf3ed1c3cf4bdac580d/href">https://medium.com/media/0294cec095d72bf3ed1c3cf4bdac580d/href</a></iframe><p>The memberFunctions property returns a list of all the member functions of a given class. If you are wondering where do the methods, that we haven’t explicitly declared, namely equals hashCode and toString, came from here is the explanation. These three methods are declared in Kotlin’s Any class which all other classes — by default — inherit from unless stated otherwise.</p><h4>Invoking the member functions</h4><p>This is how we can invoke the member functions using the KClass&lt;out Dummy&gt; variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f28062782f03602d2092c22af1914b/href">https://medium.com/media/f5f28062782f03602d2092c22af1914b/href</a></iframe><p>The only thing to notice here is whenever we want to invoke a function using a reference that is of KFunction&lt;*&gt; type we need to pass an object that is an instantiation of the corresponding class while using the call function. The reason is straightforward, a class is just a blueprint it cannot behave independently. Hence, an object is needed.</p><h4>Invoking a private function</h4><p>Up until now, we have only worked with public functions from that class. However, as I have mentioned that private functions and property can also be accessed here is an example of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1202a286009af6164244c4d96583e490/href">https://medium.com/media/1202a286009af6164244c4d96583e490/href</a></iframe><p>To access a private function there is an extra step. We need to explicitly set the isAccessible property of that KFunction&lt;*&gt; variable as true. Failing to do that would inevitably welcome an IllegalAccessException at runtime.</p><h4>Accessing properties (private)</h4><p>Here is how you can access the properties of the class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d1633b4e479696cef12303e0524441/href">https://medium.com/media/14d1633b4e479696cef12303e0524441/href</a></iframe><p>As you can see the process is really similar to the previous demonstrations. Just like the private functions, it is necessary to explicitly make private properties accessible. The type of the properties, in this case, i.e KProperty1&lt;out Dummy, *&gt; , is a bit cumbersome. Although, you need not worry about it too much if you could not grasp it right away. The KProperty type has a couple of variants designed for different properties. You may learn more in the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property/">Kotlin API reference for </a><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property/">KProperty</a>.</p><h4>Manipulating property values</h4><p>To manipulate the values of the properties we need to cast the property into the KMutableProperty type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2b3f059d2b6a5e65f5ee52ef3e813e5/href">https://medium.com/media/a2b3f059d2b6a5e65f5ee52ef3e813e5/href</a></iframe><p>In the shown code-snippet we have modified the value of the property before the getter actually accessed it. Thus the output is different.</p><h3>A Brief Summary</h3><ol><li>Reflection enables us to introspect or manipulate the behavior of a class or interface at runtime.</li><li>Using reflection we can even access the properties and functions marked with the private access-modifier.</li><li>Reflection is heavily utilized in a library or framework.</li><li>It can be found whether any class or its members were marked with some predefined annotations so that a library or framework can act accordingly.</li><li>Reflection is not a very fast process. Therefore, heavy frameworks or libraries seldom implement intermediate compilers.</li><li>Reflection gives us enormous power. So, utmost care must be taken while using it.</li></ol><h3>Wrapping-Up</h3><p>We will be wrapping up here for today. Hopefully, you have gained a basic level of understanding of reflection. You also have a general idea about what goes on under the hood while our code uses a framework or library.</p><p>Although, well will not simply end our quest here. In the next article, we will be building a simple annotation processor. We would define our very own annotations. The end result will be a dummy string parser that would encode/decode JSON data. Annotation and reflection go hand in hand. So, I would urge you to stay tuned for the next one.</p><p>Thank you so much for making it thus far. I would really appreciate a couple of words on your thought ✏️.</p><p>You can support my work by <a href="https://www.buymeacoffee.com/nilTheDev">buying me a cup of coffee</a>. ☕</p><p><a href="https://www.buymeacoffee.com/nilTheDev">Nilanjan 🌱🌱 is writing programming-related articles</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5874bf63010" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-reflection-using-kotlin-a5874bf63010">Understanding Reflection using Kotlin</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion for Dummies]]></title>
            <link>https://levelup.gitconnected.com/recursion-for-dummies-bb66f0e60a9e?source=rss-9154a21eb659------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb66f0e60a9e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Nilanjan ]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 01:24:05 GMT</pubDate>
            <atom:updated>2021-08-08T06:16:28.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>Recursion is a fundamental construct in computation. You should not freak out by seeing it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOk2ZiBX1V4VQ2INJe6y-Q.gif" /></figure><p>Some problems are hard. It is challenging to form a mental model for those. Nevertheless, we have a powerful tool at our disposal. Recursion! It is a robust idea.</p><p>Say you were solving a problem. You got something in your mind. It is something iterative but fuzzy — not so clear. Still, you feel that could be the solution. However, you can’t implement it. Well, there is a pretty good margin that the solution would be recursive.</p><p>This piece is intended for beginners who learned some looping and function kind of stuff here and there. It would be better if you have already been introduced to the idea, recursion, but you did not find it too intuitive.</p><p>I will be using python here, because, well, pretty much everyone does that. What I want you to do is run each piece of code as you see it. I would prefer that you type it all instead of copy-pasting.</p><p><strong>After going through this article you would gain</strong></p><ol><li>Understanding on what is recursion</li><li>Practice by solving four recursive problems</li><li>Elegance vs Performance</li><li>Why do you need to write recursive functions</li></ol><h4>What the heck recursion even means?</h4><p>Informally, a recursive function is something that has a base case and a recursive call that means calling the function itself. That&#39;s it. No more no less.</p><h4>Problem 1</h4><p>Write a function, power, that takes a number num and a positive integer pow— it returns the value of raising num to the power of pow.</p><p>To illustrate,</p><ol><li>power(2, 3) would return 8</li><li>power(5, 5) would return 3125</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1354d53b2e44b59aebaeb66db8f8ba70/href">https://medium.com/media/1354d53b2e44b59aebaeb66db8f8ba70/href</a></iframe><p>To discover the base case let us first understand what it formally means to raise num to the power pow.</p><p>It is,</p><p>num * num * num * num (pow times) . For instance, 5 ^ 3 = 5 * 5 * 5 = 125</p><p>But there is a catch. Any number when raised to the power 0 would equate to 1. Perfect! This could be a pretty solid base case. In the code, we would be saying that when the function is called with a pow value of 0 we would be returning 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec3adc5bffaa7613814b66c59d154f7f/href">https://medium.com/media/ec3adc5bffaa7613814b66c59d154f7f/href</a></iframe><p>Now, we have to define the function in terms of the same function.</p><p>5 ^ 3 = 5 * 5 ^ 2 or pow(5, 3) = 5 * pow(5, 2) .</p><p>In general, n ^ p = n * n ^ (p-1) .</p><p>As we have done defining the function in terms of itself we can now code it up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e04968537e5e6b0c1bc8d0ee27c02c4/href">https://medium.com/media/1e04968537e5e6b0c1bc8d0ee27c02c4/href</a></iframe><p>Now, write it yourself. Run it. Try to understand it before moving to the next problem. Alternatively, you may try this nice <a href="http://pythontutor.com/visualize.html">visualization tool</a>.</p><h4>Problem 2</h4><p>Define a function that would take a positive integer num and return the factorial of it.</p><p>If you have never heard of factorial before <a href="https://www.mathsisfun.com/numbers/factorial.html">check out this awesome primer to factorial</a>.</p><p>Factorial of a positive integer N is defined as follows,</p><p>N! = N * (N-1) * (N-2) * … * 2 * 1</p><p>So, to make the recursive call, we need to define the function in terms of itself. In the case of factorial, it would be pretty easy as N! = N * (N-1)! . Again, if you don’t get this please check the guide on factorial linked above.</p><p>Can you think of the base case? It comes straight out of the definition as the factorial of zero is defined as one. ( 0! = 1 )</p><p>It would be impressive if you try to write the code on your own using the information and the example of the first problem.</p><p>Step 1: Coding up the base case</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dcee13f4c9deb235aa327247f950166/href">https://medium.com/media/1dcee13f4c9deb235aa327247f950166/href</a></iframe><p>Step 2: Making the recursive call</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d3adad22ac46e28f66ba56cb805279b/href">https://medium.com/media/8d3adad22ac46e28f66ba56cb805279b/href</a></iframe><p>If you have made it this far congratulations! Now, you are a bit more confident writing recursive functions. Let’s try to write some more recursive functions to solidify your understanding.</p><h4>A more structured mental framework</h4><p>As I have told before recursion is actually a mathematical construct. Therefore, it has some formal definition and proof kind of stuff. To save your nice little brain from getting baffled you may follow the following steps whenever you are solving a recursive problem.</p><p><strong>Step 1: The base case</strong></p><p>The base case is the most crucial part of a recursive function. It needs to be rock solid. If there was any leak in that — meaning if your recursive call never hits the base case — you have risked your code to throw an exception widely known as the <strong>StackOverflow</strong> exception. Under the hood, your program makes infinite recursive calls, and thus a stack gets created for each call. The stack memory is limited. Hence the base case is the key for a recursive function.</p><p><strong>Step 2: The recursive call</strong></p><p>The recursive call is difficult to get right. Running a recursive call back on your mind would be painful.</p><p>However, you could simply do this instead,</p><ol><li>Assume the function works for all the other inputs. That means you have to assume your recursive call works.</li><li>Now, make the function work for the current input</li></ol><p>This is actually the way through which recursive proof works. It is called <strong>proof by induction.</strong> However, it is not necessary to learn it to solve problems recursively.</p><h4>Problem 3</h4><p>Define a function that would take a positive integer num and return a list containing the elements from this range [N,1] .</p><p>For instance,</p><ol><li>makeList(5) would return [5, 4, 3, 2, 1]</li><li>makeList(1) would return [1]</li></ol><p>Can you see the base case here? It is the second example. Whenever our function is called with an argument of 1 it would simply return a list containing that argument i.e [1] .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f9a1f300187481b909dd90f4bcc74ae/href">https://medium.com/media/6f9a1f300187481b909dd90f4bcc74ae/href</a></iframe><p>The base case is solid. No matter what valid input the function is thrown, if the recursive call is constructed accurately, it would inevitably resort to the base case thus avoiding the <strong>StackOverflow</strong> exception.</p><p>For the recursive call, we would take a slightly different approach. First, we would store the result of the recursive call in a variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d03162aa5e1b9ed0691b26a06982e9d3/href">https://medium.com/media/d03162aa5e1b9ed0691b26a06982e9d3/href</a></iframe><p>As per the recursive mental framework I have stated above at this point we are done with the base-case and the recursive-call . We would assume the recursive call does its job as we have assumed that the function works for all other inputs.</p><p>Now, we have to only make it work for the current input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b340cefaf3c64a63ba73eda483332624/href">https://medium.com/media/b340cefaf3c64a63ba73eda483332624/href</a></iframe><p>We are done.</p><h4>Problem 4</h4><p>It would be the last problem we will be seeing for today. It’s similar to the last one. So, you, if haven’t already, may try to get your hands dirty on this one.</p><p>Define a function that would take a list of integerslst and the length l as parameters and would return the sum of all the elements of the list.</p><p>To illustrate,</p><ol><li>sumList([1, 2, 3, 4, 5], 5) would return 15</li><li>sumList([9], 1) would return 9</li></ol><p>The base case is straightforward as I have already shown that to you in the example cases. Whenever the length of the list is 1 the function would simply return the first element, effectively the only element, of the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e2301de8b76012077152b006a1636cd/href">https://medium.com/media/5e2301de8b76012077152b006a1636cd/href</a></iframe><p>Let’s think about the recursive call. Think it this way, the sum of all the elements of an integer list of length N would equate to the first element of the list added with the sum of the rest of the elements of the list. That is the key to framing the recursive call. Defining the function in terms of the same function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41faab5e68e46ce8fa3fa4b416350aad/href">https://medium.com/media/41faab5e68e46ce8fa3fa4b416350aad/href</a></iframe><h4>Elegance vs Performance</h4><p>Once you get familiar with writing recursive functions you would really appreciate how elegant the recursive implementation can be as compared to the iterative implementation. If you follow the said mental framework recursive code would be so easy to read.</p><p>However, recursive functions are not as performant as iterative ones. As it involves creating a stack-frame for each recursive call. Although, there is an idiomatic way of writing tail-recursive functions. Tail-recursion is not common in the imperative paradigm but has first-class support in functional languages. A tail-recursive function can get the job done with only one stack and thus becoming equally performant with the iterative one.</p><h4>Do you need to write recursive functions?</h4><p>One obvious question that may come to your mind is whether you need to write recursive functions at all. Since all the code that I have shown so far can easily be implemented with a simple for loop. Well, actually all these examples operated with either sequential math functions or linear data structures. It is true that in these particular use cases an iterative implementation would be fine.</p><p>However, let me remind you that these were really basic instances of recursive functions to orient you with the concept. You would only realize the true power of recursion when operating with tree-like data structures. Tree-like data structures are fundamentally designed to be recursive.</p><p>I appreciated recursion for the first time when I stumbled upon the classic <strong>Towers of Hanoi</strong> problem. I would urge you to check the following video out. It is a mesmerizing manifestation of a simple-looking but insanely difficult problem. After learning about the solution make sure to think about the iterative implementation. I can’t even imagine how ugly it would be.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Frf6uf3jNjbo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Drf6uf3jNjbo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Frf6uf3jNjbo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/169a2ff510f56c3fa417aa757357802b/href">https://medium.com/media/169a2ff510f56c3fa417aa757357802b/href</a></iframe><h4>Summary</h4><p>Here is the summary of the whole piece,</p><ol><li>Recursion is powerful</li><li>Any iterative construct can be implemented recursively</li><li>A recursive function needs a solid base case. Otherwise, you may run into the StackOverflow exception.</li><li>For the recursive call, you have to define the function in terms of the same function.</li><li>When writing the recursive call, assume that the function works for all other inputs. Then make it work for the current input.</li><li>Arguably, recursion is more elegant as compared to iteration.</li><li>Recursion can be less performant as compared to iteration because it involves creating a new stack for each operation.</li><li>The performance issue can be avoided by writing an idiomatic construct known as tail-recursion. It has widespread support in the functional paradigm.</li><li>For sequential math functions and linear data structures iterative implementations are usually readable and simple.</li><li>For tree-like data structures recursion is more suitable as these data structures are fundamentally recursive.</li><li>To appreciate recursion, for the first time, you may check out the <a href="https://www.youtube.com/watch?v=rf6uf3jNjbo&amp;t=1s"><strong>Towers of Hanoi</strong></a> problem.</li></ol><p>I am glad that you have made it thus far. Hopefully, now you are a bit more familiar with recursive-constructs that you may have avoided for so long. Enjoy your journey with recursion.</p><p>I would really appreciate a couple of words on your thought.✏️</p><p>You can support my work by <a href="https://www.buymeacoffee.com/nilTheDev">buying me a cup of coffee</a>. ☕</p><p><a href="https://www.buymeacoffee.com/nilTheDev">Nilanjan 🌱🌱 is writing programming-related articles</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb66f0e60a9e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/recursion-for-dummies-bb66f0e60a9e">Recursion for Dummies</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript’s __proto__ vs prototype]]></title>
            <link>https://levelup.gitconnected.com/javascripts-proto-vs-prototype-a21ec7f25bc1?source=rss-9154a21eb659------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21ec7f25bc1</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nilanjan ]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 20:29:43 GMT</pubDate>
            <atom:updated>2021-08-03T13:19:32.203Z</atom:updated>
            <content:encoded><![CDATA[<h4>Javascript is confusing. And among all the mysterious stuff, the difference between __proto__ and prototype stands out uniquely. It confuses most programmers who try to learn the object-oriented aspect of the language.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCCI0qNGTaLR9NaeGeM7DQ.png" /></figure><p>This article is for developers who have a basic understanding of object-oriented programming in general and exploring Javascript’s way of doing this.</p><p><strong>Let’s start afresh with the following points:</strong></p><ol><li>Everything in Javascript is an object (except the primitive types)</li><li>Every object has a prototype</li><li>The default prototype of an object is Object.prototype</li><li>When a property is accessed on an object, the object looks at its own properties. If not found then it looks at its prototype’s properties. And it continues to do so unless either the property is found or it reached the Object.prototype. If the property is not found in the Object.prototype, undefined is returned.</li></ol><p>If these are unclear to you, you may check out the <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">MDN documentation for prototypes in Javascript</a>.</p><ol><li><strong>What is </strong><strong>__proto__ and what is its purpose?</strong></li></ol><p>To better understand this let’s continue with some examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*x41v2yfTb6xiAsA6e27NOw.png" /></figure><p>person is a simple object that has three properties name, age and, gender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*s7YzKa7cz_sWtUBOLNsdpQ.png" /></figure><p>Upon using console.dir on that person object we can see that it has a __proto__property.</p><p>The __proto__ property is a default property added to every object. This property points to the prototype of the object.</p><p>The default prototype of every object is Object.prototype. Therefore, the __proto__ property of the person object points to the Object.prototype.</p><p>If whatever I said is actually true then the illustration would look something like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*A5dyLBG-d2S3DbBbwgrdsw.png" /></figure><p>Let’s verify what I’m claiming is actually true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*t7rBVXoGwZddbabW2qN6dg.png" /></figure><p>As you can see that the __proto__ property of the person object is indeed equal toObject.prototype.</p><p>Now, I want to create another object teacher. That object would have the same properties and values as the person object. Only one additional property — subject — will be added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*mgxCFdbKnmdS5XXcWSOJjw.png" /></figure><p>By default, the teacher’s __proto__ property would point to the Object.prototype object.</p><p>And the illustration would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Otz_3dVSupsKS8Nch7LvNA.png" /></figure><p>Can you see the problem here?teacher and person has three common properties with the same values. It would be really nice if we could somehow inherit teacher’s properties from person.</p><p>To do that let’s first abandon the current teacher object. And create a new one with only the subject property because we will inherit other properties from the person object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*d5Ma8pCypSGgiN4PqS3T6Q.png" /></figure><p>Now, the structure looks something like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnxfSAkydqePHn_jSp93KA.png" /></figure><p>Notice that the new teacher’s __proto__ property still points to theObject.prototype object. To inherit, we have to maketeacher’s __proto__ property point toperson.</p><p>We can do the using the Object.setPrototypeOf function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2zyGtoBxvV01OCm3dgy_eg.png" /></figure><p>The illustration, now, looks something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ciqJxJ_cCINO_WwI-n72w.png" /></figure><p>teacher’s __proto__ property points to the person object and person’s __proto__ property points to Object.prototype object.</p><p>Let’s verify whether teacher’s __proto__ property actually points to the person object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*8HQb1_DBwEAaXP_s2bvTTw.png" /></figure><p>We’ve successfully inherited the properties of the person object through prototype chaining.</p><p>Now, we can access the properties from the teacher object. If the property is found in the object itself it would return that. Otherwise, it would ask its prototype and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noqCTklLjSSv-W-1o-7WKQ.png" /></figure><p>One important thing to notice is that the __proto__ is just a reference to the prototype and not an instantiation. Hence, if we modify any property in the prototype object, it would affect the child objects as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*ag0Ir6fxAGLrL-ok5JKPvw.png" /></figure><p>See how modifying person’s property changes the __proto__ property of the teacher as well.</p><p>Therefore, it could be safely said that the term <strong>prototypal inheritance</strong> is not entirely accurate. It is more of a <strong>delegation</strong> than actual inheritance!</p><p>In nutshell, the __proto__ property of every object points to the prototype of the object.</p><p><strong>2. What is </strong><strong>prototype property in constructor functions and what is its purpose?</strong></p><p>Let’s begin with examples as it helps to understand the topic more smoothly.</p><p>What if we had to create a bunch of person objects with the same properties, but different values?</p><p>We can easily create a constructor to meet the purpose.</p><p>A constructor is a special type of function. It is like a blueprint of an object. You can use the constructor to create objects with the same properties but different values.</p><p>The constructor would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*YJkV_P96VBqA5o1YGaKI7w.png" /></figure><p>As functions are also objects, it would have a __proto__ property that would point to the prototype of the function.</p><p>Functions are special types of objects. Function’s __proto__ property points toFunction.prototype as opposed to Object.prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*BVsOEGzuoVmS70F84NtpCw.png" /></figure><p>However, apart from the __proto__ property, constructor functions also have a prototype property.</p><p>Notice the __proto__ property nested inside the prototype property of thePersonconstructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*YyBdTWnBmPL6lRzmAG94VQ.png" /></figure><p>It turns out that the nested __proto__ property actually points toObject.prototype .</p><p>The diagram looks something like that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuO2C7INLqTvM-MbVaNJeQ.png" /></figure><p>And let’s verify whether the diagram is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*unTqzpuUdalfYqFtlBVw4Q.png" /></figure><p>But what is the purpose of the prototype property in the Person constructor?</p><p>It turns out that whenever we instantiate an object with the Person constructor, the constructor makes the __proto__ property of the new object point to the same object as its prototype property.</p><p>This might not make a lot of sense.</p><p>Let’s see some real examples.</p><p>Let’s instantiate a new object named mySelf using the Person constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*W3EnUbCYu3UxjvL_yRcmXQ.png" /></figure><p>And notice how the constructor makes the __proto__ property of mySelf point to Person.prototype .</p><p>The final illustration looks something like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6a1Isvzz_mXKHIgNbHkS4g.png" /></figure><p>Therefore, the sole purpose of the prorotype property of a constructor function is to initialize the __proto__ property of the objects that get instantiated using that constructor.</p><p><strong>Conclusion</strong></p><p>Hopefully, I didn’t confuse you more than you already were. And now you understand a little bit more about the difference between __proto__ and prototype .</p><p>It’s undoubtedly a bad design that confuses a lot of programmers. But as you know, Javascript is more of a revolved language than a well-designed one. So, we have to make peace with it sooner or later.</p><p>I am glad that you have finished reading the article. I would really appreciate a couple of words on your thought. ✏️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21ec7f25bc1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/javascripts-proto-vs-prototype-a21ec7f25bc1">Javascript’s __proto__ vs prototype</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>