<?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[Pulkit-Kumar - Medium]]></title>
        <description><![CDATA[Golang and mobile, Developer @ Freshworks. - Medium]]></description>
        <link>https://medium.com/pulkit-kumar?source=rss----78e70cd6bd76---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Pulkit-Kumar - Medium</title>
            <link>https://medium.com/pulkit-kumar?source=rss----78e70cd6bd76---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:06:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/pulkit-kumar" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design in GoLang for OOP languages developers (Part 4)]]></title>
            <link>https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-4-e3f3168e36dc?source=rss----78e70cd6bd76---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3f3168e36dc</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Pulkit Kumar]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 09:56:11 GMT</pubDate>
            <atom:updated>2018-08-18T02:55:21.110Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the 4th part of the series of me learning design in GoLang. The 3rd part is linked below.</p><p><a href="https://medium.com/@itzme.pulkit/design-in-golang-for-oop-languages-developers-part-3-e4562957715a">Design in GoLang for OOP languages developers (Part 3)</a></p><h3><strong>Packages should provide concrete types, not interfaces.</strong></h3><p>Libraries (or modules) in languages like <em>Java </em>often provide types wrapped in interfaces (even if there is just one implementation of it), not by concrete types. One of the reasons for that is the user of the library may want to mock the responses from the values (objects) provided by the library for testing.</p><p>Let’s take an example of a User HTTP client. The UserClient gets and posts a User to the server.</p><pre>type UserClient struct{}</pre><pre>func (c *UserClient) Get(id string, u *User) {<br>    // http get user into u<br>}</pre><pre>func (c *UserClient) Post(u *User) {<br>    // http post u to server.<br>}</pre><p>From my java experience, I would provide the UserClient from my package in the following way.</p><pre>type IUserClient interface {<br>    Get(u *User)<br>    Post(u *User)<br>}</pre><pre>func NewUserClient() IUserClient {<br>    return &amp;UserClient{}<br>}</pre><p>In GoLang I don’t need the interface here. I can simply provide user client as following.</p><pre>func NewUserClient() *UserClient {<br>    return &amp;UserClient{}<br>}</pre><p><em>But, in this case how does the user of my package mock </em><em>UserClient for testing?</em></p><p>A major difference in GoLang and other languages is that interfaces in GoLang are satisfied implicitly. A type implementing the interface need not explicitly specify the interface it is implementing.</p><p>So, the user of my package can use it via an interface if it needs to. We can use the inline interfaces for this, as shown below.</p><pre>type UserApplication struct {<br>    Client interface {<br>        Get(u *User)<br>        Post(u *User)<br>    }<br>}</pre><pre>func SomeApplicationFunc() {<br>    app := UserApplication{Client: userApi.NewUserClient()}<br>}</pre><p>Here UserClient from my package implicitly satisfies the Client interface defined by the user of my package in the UserApplication struct.</p><p>This gives the caller of my package the flexibility to create an interface if needed, instead of callee providing the interface. The value provided by the callee would implicitly implement the interface defined by the caller.</p><p>And now, for testing, I can create a MockClient and provide it to UserApplication and unit test the UserApplication behaviour based on mock responses.</p><pre>type MockClient struct{}</pre><pre>func (c *MockClient) Get(u *User) {// handle mock behavior}</pre><pre>func (c *MockClient) Post(u *User) { // handle mock behavior}</pre><pre>func TestSomeApplicationFunc(t *testing.T) {<br>    app := UserApplication{Client: &amp;MockClient{}}<br>    // test user application<br>}</pre><p>The other advantage with this is that, if the caller of my package only uses the Get method, we can simply create an interface which only has the Get method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f3168e36dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-4-e3f3168e36dc">Design in GoLang for OOP languages developers (Part 4)</a> was originally published in <a href="https://medium.com/pulkit-kumar">Pulkit-Kumar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design in GoLang for OOP languages developers (Part 3)]]></title>
            <link>https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-3-e4562957715a?source=rss----78e70cd6bd76---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4562957715a</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <dc:creator><![CDATA[Pulkit Kumar]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 09:55:46 GMT</pubDate>
            <atom:updated>2018-08-14T12:29:27.720Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the 3rd part of the series of me learning design in GoLang. The 2nd part is linked below.</p><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-2-a59f083ce348">Design in GoLang for OOP languages developers (Part 2)</a></p><h3><strong>Errors are not Exceptions.</strong></h3><p>Errors in GoLang are values not exceptions in most other languages. So, we need to get away from the try catch idiom and start treating errors as any other value.</p><p>There are often cases where errors are very common, such as IO and network errors. These are not exceptional cases, but errors cases which we need to handle in our code, hence GoLang treats them as values.</p><p>Error in GoLang is an interface</p><pre>type error interface {<br>    Error() string<br>}</pre><p>Any struct which has the Error() string method, implicitly implements the error interface.</p><p>If there is a possibility of error in a function, it is a general convention that the last return of the function is of error type .</p><p>The easiest way to create a new error value is by just creating an errorString type using errors.New(&quot;Error String&quot;) function. Let’s see how it has been used in the standard library.</p><pre>// ErrUnexpectedEOF means that EOF was encountered in the<br>// middle of reading a fixed-size block or data structure.</pre><pre>var ErrUnexpectedEOF = errors.New(&quot;unexpected EOF&quot;)</pre><pre>// ErrShortBuffer means that a read required a longer buffer than was provided.</pre><pre>var ErrShortBuffer = errors.New(&quot;short buffer&quot;)</pre><p>The above code is from the io package in Go standard library. The two errors ErrShortBuffer &amp; ErrUnexpectedEOF are constant values in the io package.</p><p>Let’s take an example of a function that returns both the errors in different cases.</p><p>In the io package the ReadAtLeast function returns (int, error). The documentation says that error can be ErrShortBuffer, ErrUnexpectedEOF or some other error in different cases.</p><p>Handling these errors is easy. Since, these errors are just values, we can check for equality and react accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47195b0c70a62c79b16db65cc643dd04/href">https://medium.com/media/47195b0c70a62c79b16db65cc643dd04/href</a></iframe><p>But, there are more complex cases. Where the error of a certain type is not constant. For example, <em>Network</em> errors. We need to have more context to react on it, like</p><ol><li>If the error was an authentication error.</li><li>If the access to the resource is denied.</li><li>If it was a resource not found error.</li><li>If it was a server error.</li></ol><p>and many more.</p><p>Also there can be cases, where a function can return more than one type of error, such as <em>Network</em> error and <em>Invalid Url</em> error.</p><p>Since error is just an interface, any struct can implement it. So, we can solve this by creating custom types which implement the error interface. Here is an example of custom <em>Network</em> and <em>Invalid Url</em> error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa41815be0374b380e66e676c4fa7f4d/href">https://medium.com/media/fa41815be0374b380e66e676c4fa7f4d/href</a></iframe><p>Since both NetworkError and InvalidUrlError have the Error() string function, both implement the error interface, and can be used as errors.</p><p>To handle errors from a function that can return both NetworkError and InvalidUrlError. We can take advantage of the <strong>type switch</strong> in GoLang. Here is an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/020707b65ad3315cad4848b3986d2c26/href">https://medium.com/media/020707b65ad3315cad4848b3986d2c26/href</a></iframe><p>In the above code makeRequest(&quot;url&quot;, &quot;GET&quot;) can return errors of type NetworkError and InvalidUrlError.</p><p>We can handle this using the <strong>type switch </strong>block. With this we can handle NetworkError and InvalidUrlError in different cases of the type switch.</p><p>Further, the different cases of NetworkError like auth error, server error can be handled in the NetworkError case.</p><p>Another difference in error and exception is that it is not mandatory for error to record stacktrace.</p><p>But there are cases where we may need the stacktrace information of the error. For example, if we need to pass an error up the function hierarchy, and caller function may expect more context on the reasons of error for logging.</p><p><em>How to do it?</em></p><p>We can use errors.Wrap(err) function to wrap errors. The Go doc for errors.Wrap(err) is following.</p><pre>The errors.Wrap function returns a new error that adds context to the original error by recording a stack trace at the point Wrap is called, and the supplied message.</pre><p>To get the original error which was wrapped using errors.Wrap(err) can be extracted errors.Cause(err).</p><p>errors.Cause(err) will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause.</p><p>Here is an example of getting the cause of the erro from GoDoc.</p><pre>switch err := errors.Cause(err).(type) {<br>case *MyError:<br>        // handle specifically<br>default:<br>        // unknown error<br>}</pre><blockquote>Errors are just values based on which we need to react in our code.</blockquote><blockquote>Any struct can implement the error interface to provide more context about the error.</blockquote><blockquote>We can choose to record stacktrace if we need to, by wrapping errors using errors.Wrap(err). If we can react to the error right away, we need not record it’s stacktrace.</blockquote><p>Here is the next part of the series.</p><p><a href="https://medium.com/@itzme.pulkit/design-in-golang-for-oop-languages-developers-part-4-e3f3168e36dc">Design in GoLang for OOP languages developers (Part 4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4562957715a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-3-e4562957715a">Design in GoLang for OOP languages developers (Part 3)</a> was originally published in <a href="https://medium.com/pulkit-kumar">Pulkit-Kumar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design in GoLang for OOP languages developers (Part 2)]]></title>
            <link>https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-2-a59f083ce348?source=rss----78e70cd6bd76---4</link>
            <guid isPermaLink="false">https://medium.com/p/a59f083ce348</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pulkit Kumar]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 05:21:38 GMT</pubDate>
            <atom:updated>2018-08-13T11:41:56.279Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the 2nd part of the series of my learnings. The first part is linked below.</p><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-630bd746ad85">Design in GoLang for OOP languages developers. (Part -1)</a></p><h3>Readable functions with pointers</h3><p>GoLang has pass by value semantics. All function parameters and returns are copied from/to the caller function.</p><p><em>But, what if we have to share a value between two functions?</em></p><p>The answer is simple, we use pointers for that. Even with pointers, we can write the code in many ways to share a value between functions, not all are readable. But, before exploring the different ways, we need to understand something.</p><p>When go runtime creates a value, it lives either in the heap, or the stack<strong> </strong>frame. By default all values created in a function exist in the stack<strong> </strong>frame. But, Go has a program called <strong>escape analysis</strong>, which decides what should be put on the heap.</p><p><strong>Escape Analysis</strong> makes a graph of function returns and parameters, to check if pointer semantics<em> </em>are being used for some values. If so, it makes sure that the value using pointer semantics is created in the heap, not in the stack frame, so that it can be <em>shared</em> across different functions. We can say, that such value <strong><em>escapes to the heap</em></strong>.</p><p>Let’s take a simple example. We need to read a User from a http api in one function, and modify the Email of the user in another function.</p><p>Here is one way to do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6446b09b8bd763253c1e36003874b83/href">https://medium.com/media/f6446b09b8bd763253c1e36003874b83/href</a></iframe><p>In the above code, the fetchStruct() function can be written in two ways.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8233c98a5c3127f87dae5bc1f2e9a7c/href">https://medium.com/media/c8233c98a5c3127f87dae5bc1f2e9a7c/href</a></iframe><p>There are readability issues in the above code, it is not clear where the value u is going to live, heap or stack frame. In <em>line 7</em> of <em>return_address_of_val.go</em>, it seems that u is going to live in the stack frame but since it is being <em>shared </em>to the caller function, it <em>escapes to heap</em>.</p><p>Similarly, in the other implementation of fetchStruct() (<em>line 11 </em>of <em>return_address_variable.go</em>), there is a readability issue. It seems that the function is returning a copy, while our intent is to <em>share</em> the value of type User with the caller function.</p><p>To understand where u is going to live in both the above cases, we need to look at the function hierarchy. Which may get more complex with deeper hierarchies and more function calls.</p><p>The reasons the above examples are not readable are,</p><ol><li>The integrity of the variable u is compromised, while it is created for sharing, there are functions which treat it differently.</li><li>As code gets distributed in multiple packages, it is important that we can understand if the value will live in heap or stack frame without reading the packages it is being used in.</li></ol><p>Here is a more readable way of doing this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0b930e23005a32a141380e327df2cd0/href">https://medium.com/media/f0b930e23005a32a141380e327df2cd0/href</a></iframe><p>In the above code at <em>line 25,</em> I am creating a variable of type User, and at <em>line 26</em>, I am <em>sharing</em> it with the function Fetch(). And later I am sharing it with modifyEmail() function.</p><p>While reading the main()<em> </em>function, it is clear that the variable u is going to live in the heap. Because we are sharing it with the Fetch() function.</p><p>The fetch function is also readable, as it is just modifying the value at the pointer u.</p><p>The integrity of variable u is maintained, it is meant to be used within the main() function and is <em>shared</em> with functions which can modify it.</p><p>Using such code style, we can make sure that the reader of the function can easily identify if a value is going to live in the heap or stack frame.</p><blockquote>Pointer variables should be defined at a hierarchy from where it can be shared with all the functions that can modify the value it points to.</blockquote><p>For deeper understanding of <strong>escape analysis</strong>, use this <a href="https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-escape-analysis.html">link</a>.</p><p>Here is part 3 of my learnings.</p><p><a href="https://medium.com/@itzme.pulkit/design-in-golang-for-oop-languages-developers-part-3-e4562957715a">Design in GoLang for OOP languages developers (Part 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59f083ce348" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-2-a59f083ce348">Design in GoLang for OOP languages developers (Part 2)</a> was originally published in <a href="https://medium.com/pulkit-kumar">Pulkit-Kumar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design in GoLang for OOP languages developers. (Part -1)]]></title>
            <link>https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-630bd746ad85?source=rss----78e70cd6bd76---4</link>
            <guid isPermaLink="false">https://medium.com/p/630bd746ad85</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <dc:creator><![CDATA[Pulkit Kumar]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 18:18:29 GMT</pubDate>
            <atom:updated>2018-08-17T09:35:37.714Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently moved from working on object oriented programming languages (Java &amp; Kotlin) to working on GoLang.</p><p>Initially I wanted to design my application as I used to do in Java, everything was an object, The dependencies of objects were some other objects. These object exposed some behaviour using methods. Usually I had some interfaces which were implemented by the classes (structs). And then I wrote some factory functions to create the objects of the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*gjyhqdy5jXjd7L0ILzu5qA.jpeg" /></figure><p>When I tried to do the same in GoLang, it did not seem idiomatic, neither was it in the same style as the standard library code 😕. What could I be doing wrong? So I tried to understand the design philosophy in GoLang.</p><p>After reading some texts on it (mostly authored byBill Kennedy of <a href="https://github.com/ardanlabs/">Ardan Labs</a>). I had a better understanding of the GoLang design philosophy.</p><p>So I decided to write a series of medium blogs explaining aspects of my learning.</p><p>This is the first part of the series. The next parts of the series are :</p><ul><li><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-2-a59f083ce348">Readable functions with pointers</a>.</li><li><a href="https://medium.com/@itzme.pulkit/design-in-golang-for-oop-languages-developers-part-3-e4562957715a">Errors are not Exceptions.</a></li><li><a href="https://medium.com/@itzme.pulkit/design-in-golang-for-oop-languages-developers-part-4-e3f3168e36dc">Packages should provide concrete types, not interfaces.</a></li></ul><h3><strong>1. Functions are more readable than methods.</strong></h3><p>In most OOP languages, we use <strong>methods</strong> (<em>tied to a an object or class</em>) and not <strong>functions</strong> (<em>not tied to object or classes</em>). It is also easier to work with methods over functions in most OOP languages.</p><p>But GoLang offers us both functions an methods, and the standard library has a lot of functions and some methods too. We are often in dilemma, what should we use, methods or functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6We996wo18Drq9llFRnlcA.jpeg" /></figure><p><em>Let’s start by understanding what difference does it make if we use a function or a method?</em></p><p>In GoLang, functions and methods are the same to the compiler. It considers <em>receiver (struct)</em> of the method as the first parameter to the function. Weather we use a method or a function, it does not make a difference to how it is going to be executed on the machine, or the way compiler treats it.</p><p><em>But, from readability prospective</em>, with a function, we know from it’s signature, the parameters needed to execute it.</p><p>With a method, we may be using all the fields enclosed in the receiver struct, or a subset of it. Which may lead to some pollution in the code. The methods which only need a subset of fields, have access to other fields too.</p><p><em>Let’s look at an example illustrating this,</em></p><p>With most OOP languages, we use classes to also logically group some behaviour, such as the following example of a <em>UserRepository</em> where I can read and write <em>Users</em> from a source. So, here is how I converted my java code to GoLang. I tied the behaviour to a struct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b03cd5bbc612ea72034510ef55340d/href">https://medium.com/media/40b03cd5bbc612ea72034510ef55340d/href</a></iframe><p>Are there readability issues with the above code?</p><p>The method Read() only uses reader, but effectively takes DefaultUserRepository as a parameter. Which contains both reader and writer. This is something which we can not determine from the method definition, hence the readability is compromised.</p><p>This also allows further pollution in the interface, when more features are added to it, which use a subset of the fields present in the struct.</p><p>How do we solve this?</p><p>If we need to logically group some functions, we don’t need to tie it to a struct, we can use the <strong>packages</strong> in Go for such use cases.</p><p>This is how my code looks, if I use packages instead of methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ac82b96ef64c21a884651c2ffe1f3ec/href">https://medium.com/media/5ac82b96ef64c21a884651c2ffe1f3ec/href</a></iframe><p>This is more readable. It is clear from the function signature that we are only going to use reader in the Read() function, and writer in the Write() function.</p><p>There are more advantages to using functions,</p><p>Each package in go is compiled as a library and can be used by importing the package. Go does not allow cyclic imports of any two packages. (like modules in java). <br>Developers must think of each package as a library that provides some behaviour or operations, based on the data provided to it.</p><p><strong>BottomLine:</strong></p><blockquote>Structs in Go should only be used to store data, not to logically group behaviour.</blockquote><blockquote>Methods should be used only when we are operating on the data which is stored in the receiver struct.</blockquote><blockquote>Behaviour or Operations can be provided by packages instead.</blockquote><p>Here is the link to the next part of the series</p><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-part-2-a59f083ce348">Design in GoLang for OOP languages developers (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=630bd746ad85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pulkit-kumar/design-in-golang-for-oop-languages-developers-630bd746ad85">Design in GoLang for OOP languages developers. (Part -1)</a> was originally published in <a href="https://medium.com/pulkit-kumar">Pulkit-Kumar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>