<?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 Paras Raba on Medium]]></title>
        <description><![CDATA[Stories by Paras Raba on Medium]]></description>
        <link>https://medium.com/@parasgadhvi12345?source=rss-1ae65d5a4b55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OevkcJ0m3jqLW8mW</url>
            <title>Stories by Paras Raba on Medium</title>
            <link>https://medium.com/@parasgadhvi12345?source=rss-1ae65d5a4b55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:25:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parasgadhvi12345/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[Writing a JSON Parser for Fun!]]></title>
            <link>https://towardsdev.com/writing-a-json-parser-for-fun-81cc529796f7?source=rss-1ae65d5a4b55------2</link>
            <guid isPermaLink="false">https://medium.com/p/81cc529796f7</guid>
            <category><![CDATA[lexer]]></category>
            <category><![CDATA[coding-challenge]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[Paras Raba]]></dc:creator>
            <pubDate>Mon, 20 May 2024 15:21:38 GMT</pubDate>
            <atom:updated>2024-05-22T17:22:38.732Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the things that I have been most fascinated since I started programming was who wrote the programs that runs my program, and how does that work?</p><p>The first programming language that I got interested in was Python, so I looked into how Python worked, how does me writing a code like below</p><pre>print(&quot;hello world&quot;)</pre><p>is executed. What does the Python interpreter do to run the code, and then I found out that how Python interpreter is written in C and C++. So I got deeper into rabbit hole, how does the C and C++ code works and then I got into this rabbit hole that is called <a href="https://en.wikipedia.org/wiki/Bootstrapping_(compilers)#:~:text=In%20computer%20science%2C%20bootstrapping%20is,that%20it%20intends%20to%20compile.">Bootstrapping</a>. And the thing is that I get the gist of what is what and how it works, but I am just awed by the fact that there are programs that run the program that shitty developer like me write, and I sort of well and truly understand this notion of “we are standing on the shoulders of giants” .</p><p>My admiration of people who write the programming language is immense, to name a few would be <a href="https://en.wikipedia.org/wiki/Dennis_Ritchie">Dennis Ritchie</a> (One of the core contributor in writing C compiler), <a href="https://en.wikipedia.org/wiki/Rob_Pike">Rob Pike</a> (One of the core contributor in writing Go compiler), <a href="https://en.wikipedia.org/wiki/Guido_van_Rossum#:~:text=Guido%20van%20Rossum%20(Dutch%3A%20%5B,position%20on%2012%20July%202018.">Guido van Rossum</a> (One of the core contributor of Python) and there are few more.</p><p>So when I heard of this book called <a href="https://amzn.in/d/diOg9Fr">Writing An Interpreter In Go</a>, as any good and lazy programmer, I immediately added it into my todo list (I would like to assure my readers, I am someone who does eventually follow up on my todo list, but emphasize on the word eventually). So I was listening to <a href="https://open.spotify.com/episode/7hFPc5WywryUvQRwzvtTBd?si=EdXzkj6gSy6rIQuNZXFBTg">this</a> podcast while cooking my meal, and they had a episode where guest was <a href="https://thorstenball.com/">Thorsten Ball</a> who is the author of the book that I just mentioned, my spidey senses tingled from there onward and I got to learn about how programming languages are not rocket science and one could build one for themselves.</p><p>One of thing that Mr. Ball pointed out was it is not really necessary to directly write your own programming language, one could start from writing a simple Parser for a particular use case and that could get them going.</p><p>And I thought, well I don’t have any use case in my mind, but then I stumbled upon <a href="https://codingchallenges.fyi/challenges/challenge-json-parser">this challenge</a>. And I was like ok this is my calling, I need to write a JSON parser and solve this challenge.</p><p>Now let us get to the point, see there are some hoops through which a compiler/interpreter has to go before it can start to excute a program. For brevity I would be using the term compiler more but this also applies for interpreter.</p><p>So for an example a compiler will need to ensure that the syntax is valid, and invalid syntax must return some coherent error message to user. E.g. the infamous missing &#39;;&#39; at the end of line 69 or Python version would be IndentationError: Expected indentation at line 420...</p><p>Now A naive approach would be to read the input line by line, and check for all the rules of language and if it is valid syntax then feed it to compiler to deal with. But that is not how it works, in every programming language there are some special grammar rule to adhere, each character does not have the same weightage, some have special meaning according to grammar.</p><p>Now to deal with that, the compiler will do what is called Lexical Analysis in which it would read the input program line by line, and create this tokens. So for an example here’s my token implementation for JSON parser</p><pre>// tokenType represents the different JSON tokens<br>//<br>//go:generate stringer -type=tokenType<br>type tokenType int<br><br>const (<br> INVALID tokenType = iota<br><br> // curly braces for object<br> LEFT_CURLY_BRACES  tokenType = 1<br> RIGHT_CURLY_BRACES tokenType = 2<br><br> // square brackets for arrays<br> LEFT_SQUARE_BRACKET  tokenType = 3<br> RIGHT_SQUARE_BRACKET tokenType = 4<br><br> // separator tokens<br> COLON tokenType = 5<br> COMMA tokenType = 7<br><br> // primitive types tokens<br> STRING       tokenType = 8<br> FLOAT_NUMBER tokenType = 9<br> INT_NUMBER   tokenType = 10<br> BOOLEAN      tokenType = 11<br> NULL         tokenType = 12<br><br> // special End of file token<br> EOF tokenType = 13<br>)<br><br>// Token containing the value and type of the token, and current pos in the<br>// input<br>type Token struct {<br> Value string    // Value of the token<br> Type  tokenType // The type of the token<br> Pos   int       // Position of the token<br>}<br><br></pre><p>Now as you can see there are different token types in JSON, there is ‘{‘, ‘}’ as they have special meaning, same goes for ‘[‘ and ‘]’, and to represent the primitive types I have string, bool and all of that classic stuff, just to distinguish between int and floats I have created two seperate tokens INT_NUMBER and FLOAT_NUMBER to represent the JSON Number type.</p><p>Now this are all just types of token, actual token will consist of the Value of token, they type of the token and the position of the token in our input stream. We could have added line number in Token struct to even represent the line number of the input, but I don’t want to deal with that now.</p><p>Now our Lexer would do only one thing, and that is read the input character by character and when asked upon, generate a Token out of it.</p><p>Here’s the function signature of indicating the same</p><pre>func (l *Lexer) nextToken() Token<br></pre><p>It internally uses the the method to read the next character from input and peek a character from the input. So in short that is the job of the lexer, i.e. read the byte array or string of the input and then throw out tokens.</p><p>Now comes our parser, Parser’s job is to read the tokens that it obtains from the Lexer, and check if it fits the grammar or not, if it does not then throw some sensible error and if it does then create a Abstract Syntax Tree or AST in short. You can read more about AST’s on <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Wikipedia</a> as I am not going to explain it due to the fact that even I don’t understand them quite well.</p><p>So here’s my Parser’s code snippet</p><pre>func (p *Parser) Parse() (JSONObj, error) {<br> obj := JSONObj{}<br> if p.currToken.Type != LEFT_CURLY_BRACES {<br>  return obj, newJSONParseError(&quot;Expected &#39;{&#39; at the start of the json&quot;, p.getPos())<br> }<br> p.nextToken()<br><br> for p.currToken.Type != RIGHT_CURLY_BRACES {<br>  // try and parse the key<br>  if p.currToken.Type != STRING {<br>   return obj, newJSONParseError(&quot;Expected string for key&quot;, p.getPos())<br>  }<br><br>  // currently to handle the trailing commas not supported, we are keeping<br>  // track of these flag `wasPreviousComma` which should be set to true<br>  // on encountering the comma and otherwise to false<br>  p.wasPreviousComma = false<br>  key := p.currToken.Value[1 : len(p.currToken.Value)-1]<br>  p.nextToken()<br><br>  // After parsing the key, we must have a colon<br>  if p.currToken.Type != COLON {<br>   return obj, newJSONParseError(&quot;Expected &#39;:&#39;&quot;, p.getPos())<br>  }<br>  p.wasPreviousComma = false<br>  p.nextToken()<br><br>  // try and parse the value corresponding to current key<br>  value, err := p.parseValue()<br>  if err != nil {<br>   return obj, err<br>  }<br><br>  obj.pairs = append(obj.pairs, KeyValue{Key: key, Value: value})<br>  p.nextToken()<br><br>  if p.currToken.Type == COMMA {<br>   p.nextToken()<br>   p.wasPreviousComma = true<br>   continue<br>  }<br><br>  if p.currToken.Type == EOF {<br>   p.wasPreviousComma = false<br>   break<br>  }<br><br>  if p.currToken.Type != RIGHT_CURLY_BRACES {<br>   return obj, newJSONParseError(&quot;Expected } or ,&quot;, p.getPos())<br>  }<br> }<br> if p.wasPreviousComma {<br>  return obj, newJSONParseError(&quot;trailing commas are not supported&quot;, p.getPos())<br> }<br> return obj, nil<br>}</pre><p>So if you read it carefully, hopefully you would understand that it enforces the JSON logic, so first it checks for ‘{‘ then it checks if the key was string or not, then it looks for ‘:’ token and then next should be the value corresponding to the key, and then if there is ‘,’ then it continues and it does so till it finds the ‘}’ token. There is also some more nasty business going on but feel free to read that and ask me if you don’t understand it.</p><p>Now what does the parser returns, it returns the JSONObj which is in a way my AST for the JSON in the world of Go. Here’s what it looks like</p><pre>// JSONObj represents a valid json object in the Go world<br>type JSONObj struct {<br> pairs []KeyValue<br>}<br><br>// Value implements jsonVal.<br>func (j JSONObj) Value() any {<br> return j.pairs<br>}<br><br>var _ jsonVal = JSONObj{} // compile time check<br><br>// KeyValue is the key and value of each field of json object<br>type KeyValue struct {<br> Key   string<br> Value jsonVal<br>}<br><br>// jsonVal interface must be satisfied by the each primitive value of key value pair of<br>// json object<br>type jsonVal interface {<br> Value() any<br>}</pre><p>in Summary JSONObj is list of KeyValue which is just Key a string and Value a jsonVal which is a way to represent dynamic values obtained from JSON into Go (which has static types).</p><p>Now my Parser does not create a meaningful AST, because it is less of parser and more of validator, since all I am doing is validating if my JSON is valid or not. If suppose I were to be creating a tool like jq which just does not validates JSON but can perform operation on it, then my AST would need something better to operate upon, But that is not my goal and I am quite happy with only this much.</p><p>Now to validate my Parser, the test JSON files were provided in the challenge itself, and I wrote a single test case to iterate through those files and check validate my parser/validator.</p><p>Now at the end of this ordeal there are few questions that I must answer</p><ol><li>Was this hard? Not at all</li><li>Is it better than existing one? Not at all</li><li>Does it support the JSON specification ? Nope</li><li>Do I plan to enhance it? Not that much</li><li>Was it a fun exercise? Absolutely</li><li>Did I learn something new? Absolutely</li></ol><p>DISCLAIMER: This is just my understanding of Lexers and Parser, I might be very much wrong, so don’t trust me blindly on this one.</p><p>The source code for the above code for anyone interested, is linked <a href="https://github.com/ParasRaba155/json-parser">here</a>. Thank you for reading this far, have a nice day reader.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81cc529796f7" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/writing-a-json-parser-for-fun-81cc529796f7">Writing a JSON Parser for Fun!</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I aced the Google Cloud Platform ACE Exam]]></title>
            <link>https://medium.com/@parasgadhvi12345/how-i-aced-the-google-cloud-platform-ace-exam-f9d50c4dea92?source=rss-1ae65d5a4b55------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d50c4dea92</guid>
            <category><![CDATA[gcp-certification]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[associate-cloud-engineer]]></category>
            <category><![CDATA[cloud-certification]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Paras Raba]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 17:49:23 GMT</pubDate>
            <atom:updated>2024-04-19T17:49:23.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello readers, 10 days ago on April 09th I appeared for my GCP ACE (Associate Cloud Engineer) Certification Exam and I passed it. I want to share my experience through this blog and share the path that I took to pass the exam.</p><p><a href="https://www.credly.com/badges/32ff9cd4-906f-4976-a1a0-bde86d67f2d3/public_url">Associate Cloud Engineer Certification was issued by Google Cloud to Paras Raba.</a></p><p>I had no prior experience with any Google Cloud services so I went through the course by <a href="https://www.udemy.com/share/104aBM3@H9Q31TjDeWlwUTMEJhpwyn1MkUc3NHLtJk3lLBkrFoYj3nt0ECvO8qfLCXNR2oxuEQ==/">Ranga Karnam</a>. I would suggest taking your time with the course and getting your hands dirty with playing around the services as much as you can, and don’t rush through the process.</p><p>After I completed the course I was feeling very confident and gave a mock exam. It is funny looking at the result of that test, because I failed miserably, I only got 22 out of 50 correct, and my confidence went up in the flames. It took me some time for me to recover from that, but that is when I realised something we can’t rush through. So I went and re read the course material, reviewed my weak points from the test. Gave myself additional 3 weeks before even thinking of Mock tests.</p><p>After sometime I started the mocks by <a href="https://www.udemy.com/share/107RQQ3@0PqpqtuhT7_r5Z0Wft_TEf4PzNC5BDULzOI4jxsBJxzp6AFaqOq_Im0wAHOfm-pTAQ==/">Sayyam</a>. Out of 6 mocks in this course, I passed 2 and failed 4, but failures were all above 30 out of 50 questions, so that was a boost for me. Keep in mind that the mocks are for confidence boost of your strong areas and keeping track of your weak areas. After completing a mock, review all the right and wrong questions. Keep track of how many questions from particular service you are getting wrong or how many questions of particular type you are getting wrong. Read the google docs for those topics, if you are fine with video material than watch the course section for those topics, but just try and sort out those weak areas.</p><p>In my second or third goes through the mocks I was passing all the mocks with more than 40 questions. And that is when I scheduled my exam, and please do not rush for scheduling the exam. Only do it once you are confident enough. I scheduled on location proctored exam rather than relying upon my mediocre network. But keep in mind GCP does not have that many centers for proctored exam (As of now). So for example in my state there are only 3 or 4 centers and all of them are in city around 3 hours bus ride from me.</p><p>So schedule your exam timing carefully as a no-show means failure in these exams. And also, do not expect that every question in the examination will be from mocks. In fact, for my exam, the very first 5 questions were from my weak areas, and somehow I had not seen any of those in mocks, but I kept my composure (somehow) and kept on, and after that questions were reasonably good and once I gained my confidence I looked at those earlier questions and was able to solve those.</p><p>So in conclusion, the exam is not easy and it is not very hard also. My suggestions are just sensible suggestions for any exams i.e. practice in right way, do not rush, keep reviewing the weaker area. And yeah you should be able to do it.</p><p>If you have any queries, feel free to comment….</p><p>Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d50c4dea92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep this in mind when testing the bufio Writer]]></title>
            <link>https://blog.stackademic.com/keep-this-in-mind-when-testing-the-bufio-writer-bf42680bce96?source=rss-1ae65d5a4b55------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf42680bce96</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[bufio-package]]></category>
            <category><![CDATA[buffer-read-write]]></category>
            <dc:creator><![CDATA[Paras Raba]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 04:49:48 GMT</pubDate>
            <atom:updated>2024-01-11T00:59:04.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*34TpDcnKyUGRkfYZ" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So here’s something that I stumbled upon while testing my code and thought I should share with my fellow <a href="https://go.dev/blog/gopher">Gophers</a>. I wouldn’t be writing lengthy theoretical part in this blog. I will walk you through the problem and solution through code itself.</p><p>Below is the sample code that recreates the problem</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5051c5077cc3af6b761a564b88bacaf/href">https://medium.com/media/d5051c5077cc3af6b761a564b88bacaf/href</a></iframe><p>As you can see we have defined a wrapper struct around *bufio.Writer which will keep track of error occurred during writing and number of bytes written totally.</p><p>Here’s our write() method which just calls the *bufio.Writer.Write() method internally</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ba9ba92de0ba2200f9ba6d73ae74f48/href">https://medium.com/media/1ba9ba92de0ba2200f9ba6d73ae74f48/href</a></iframe><p>I want to emphasize once more that the code I’m presenting is purely for demonstration purposes and does not represent any actual implementation.</p><p>Now I wanted to test the error path of *myWriter.write() path, i.e. when error is not nil, it should log the error and should update the mw.err = err</p><p>To get the error from the bufio.Writer I created a stub of my own for testing which will always throw an error and it implemented the io.Writer interface. Below is the code for the same</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70a565ba5dc418b13ae256dafae629ec/href">https://medium.com/media/70a565ba5dc418b13ae256dafae629ec/href</a></iframe><p>And here’s the test case that I wrote</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f2c9dde67f52304c51f81b7c70b41a/href">https://medium.com/media/e8f2c9dde67f52304c51f81b7c70b41a/href</a></iframe><p>I know I have bombarded you with lots of code snippets, but bare with me, read the above code and it should be readable and clear in conveying the objective that I am try to achieve.</p><p>Now if you look at glance, this all looks good and my above code should pass as *myWriter will call it’s underlying *bufio.Writer which will call it’s underlying io.Writer,and since we have setup the underlying io.Writer to always return error, we should see something like this.</p><pre>ok      &lt;file&gt;       0.002s</pre><p>But instead of that I got the following</p><pre>--- FAIL: TestMyWriterWrite (0.00s)<br>    main_test.go:34: expected 0 bytes written got: 2<br>    main_test.go:38: expected new mock write error error got: &lt;nil&gt;<br>FAIL<br>FAIL    &lt;file&gt;      0.001s<br>FAIL</pre><p>And that is the point where I reran my program “N” number of times in the hopes that something would change, but as we all know miracles are miracles for reason, they don’t just happen by rerunning our programs.</p><p>Now to solve this I used my goto debug method and that is logging/print statements, and that did not work in my case at-least not to satisfactory conclusion, all I found out was that the error returned by the line</p><pre>  n, err := mw.bufWriter.Write(p)</pre><p>was nil when it shouldn’t be, so I used the actual debugger and after it debugging countless times what I found out was, It was calling the bufio.Writer.Write([]byte) method but not the underlying io.Writer.Write([]byte) method.</p><p>Here’ s the source code for the bufio.Writer.Write() method</p><pre>// Write writes the contents of p into the buffer.<br>// It returns the number of bytes written.<br>// If nn &lt; len(p), it also returns an error explaining<br>// why the write is short.<br>func (b *Writer) Write(p []byte) (nn int, err error) {<br>  for len(p) &gt; b.Available() &amp;&amp; b.err == nil {<br>  var n int<br>  if b.Buffered() == 0 {<br>     // Large write, empty buffer.<br>     // Write directly from p to avoid copy.<br>     n, b.err = b.wr.Write(p)<br>    } else {<br>   n = copy(b.buf[b.n:], p)<br>   b.n += n<br>   b.Flush()<br>  }<br>  nn += n<br>  p = p[n:]<br> }<br> if b.err != nil {<br>  return nn, b.err<br> }<br> n := copy(b.buf[b.n:], p)<br> b.n += n<br> nn += n<br> return nn, nil<br>}</pre><p>Were you able to spot the reason for that bufio.Writer not calling the underlying io.Writer took my dumb brain help of 2 people to spot it and correct my test case accordingly.</p><p>Don’t worry if you too were not able to spot it, read the code again and see b.wr.Write is only called inside the for loop, with guard clause len(p) &gt; b.Available and b.err == nil</p><p>Now in our case b.err == nil is true, but we need to satisfies the condition lep(p) &gt; b.Available.</p><p>As can be seen in the line n := copy(b.buf[b.n:],p)the buffered writer will only call the underlying writer if the number of bytes to write exceeds the buffer that is available in the buffered writer. Otherwise, it will copy the byte array directly.</p><p>So I re-wrote my test case as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4d6bd6197f89f52694eae965e01a64/href">https://medium.com/media/5a4d6bd6197f89f52694eae965e01a64/href</a></iframe><p>And that returns the desired result of passing test case, and I saw the beautiful message by go test.</p><pre>ok      &lt;file&gt;       0.002s</pre><p>So In conclusion when testing any underlying implementation do not assume it will work as you think, because in my head the bufio.Writer will always call the underlying io.Writer but if I had just used fraction of my brain then that is clearly counter intuitive , the bufio.Writer will only call underlying Writer if there is not enough space in the buffer otherwise it will just copy the byte array the into its buffer.</p><p>If anyone was still confused from my barrage of code snippets feel free to ask questions in the comments, I would be glad to clarify any confusions in the blog. Thanks for taking your time in reading the blog, hope you have a nice day.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf42680bce96" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/keep-this-in-mind-when-testing-the-bufio-writer-bf42680bce96">Keep this in mind when testing the bufio Writer</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the proverb: ‘Errors are values’ In Go Programming Language]]></title>
            <link>https://medium.com/@parasgadhvi12345/understanding-the-proverb-errors-are-values-in-go-programming-language-1dc588bb0b57?source=rss-1ae65d5a4b55------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc588bb0b57</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Paras Raba]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 07:29:53 GMT</pubDate>
            <atom:updated>2023-09-15T07:29:53.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Gopher icon" src="https://cdn-images-1.medium.com/max/512/1*eZvOYSecLNX78c8TVaWhLA.png" /><figcaption>Gopher</figcaption></figure><p><em>“Errors are values.” </em>is one of the <a href="https://go-proverbs.github.io/">proverbs of Go programming language</a> and I always think I understand the point of what means and yet I do not think I understand it even after 1 year of being a professional Go developer.</p><p>But recently I had a moment when I think I understood what it means and I thought why not my first blog be exactly that, and then I can share the blog and hope that I can get reviews and thus strengthening my concept further.</p><p>So let us first understand what it means. It means exactly what it says, and that is “<em>Errors are values.</em>” and in other words errors in Go errors are just like any values in language, specifically it is a any value that implements the error interface which is defined in builtin.go:</p><pre>type error interface {<br>    Error() string<br>}</pre><p>Here’s an example how this will work:</p><pre>func doSomething() error {<br>    if !succesfull {<br>      return fmt.Errorf(&quot;error in doing somthing&quot;)<br>      // OR<br>      return errors.New(&quot;error in doing something&quot;)<br>    }<br>    return nil<br>}<br><br>// and the caller of the doSomething can check for error as follow<br>err := doSomething() <br>if err != nil {<br>  // handle the error here<br>}</pre><p>NOTE: It is not necessary that we always use fmt.Errorfor errors.New for creating errors we can have custom data type which can implement the error interface and we can use that too.</p><p>Now all of this is something that I believe everyone new to Go understands fairly quickly. Let us now talk about the if err != nil code, this line of code is something that I have to write a lot in my day to day programming and I wanted to decrease the verbosity of it, the repetition in itself is not problem but for some reason when I have to write code like this I don’t feel all that comfortable.</p><pre>user, err := GetUser(id)<br>if err != nil {<br>  // handle the error<br>}<br><br>err = StoreUserSession(user.ID, user.Name)<br>if err != nil {<br> // handle the error<br>}<br><br>userResponse := user.ToResponse()<br>resp, err := json.Marshal(userResponse)<br>if err != nil {<br>  // handle error<br>}<br>// send response</pre><p>And this is all good till now but you see how the line if err != nil pops up after writing 2–3 lines of code. So to eliminate this thing I did extensive amount of research and by that I meant reading few medium blogs and <a href="https://www.reddit.com/">Reddit</a> posts &amp; I stumbled upon this <a href="https://go.dev/blog/errors-are-values">fantastic piece of article</a> by none other than Rob Pike (One of the co-author) of Go.</p><p>I am not going to explain what Rob Pike wrote, I think he explains it much better than I can. But the short of all of this is that errors are values like any other type so we can store it in struct, we can change it, manage that using some method on that struct. And I know most of you did not understand what I just wrote, but believe me that is the gist of it. Now let me demonstrate how the method suggested by Rob Pike helped me decrease the verbosity of my code.</p><p>So I had to create a code where my Handler would throw error to client, explaining which of the URL Queries the request was missing.</p><p>So my first implementation was something like this</p><pre>func Handler(w http.ResponseWriter, r *http.Request) {<br>    params := r.URL.Query()<br>    <br>    if params.Get(&quot;q1&quot;) == &quot;&quot; {<br>        W.WriteHeader(http.StatusBadRequest)<br>        w.Write([]byte(&quot;query &#39;q1&#39; does not exist&quot;))<br>        return <br>    }<br><br>    if params.Get(&quot;q2&quot;) == &quot;&quot; {<br>        W.WriteHeader(http.StatusBadRequest)<br>        w.Write([]byte(&quot;query &#39;q2&#39; does not exist&quot;))<br>        return <br>    }<br>    <br>    // and so on and so on<br>}</pre><p>So to improve this I wanted to write a helper function which would just isolate the query checking part of the Handler and should return bool</p><p>So I wrote the following code</p><pre>func queryExistsIn(p url.Value, q string) bool {<br>    return p.Get(q) != &quot;&quot;<br>}<br><br>func Handler(w http.ResponseWriter, r *http.Request) {<br>    params := r.URL.Query()<br>    <br>    if !queryExistsIn(params, &quot;q1&quot;){<br>        W.WriteHeader(http.StatusBadRequest)<br>        w.Write([]byte(&quot;query &#39;q1&#39; does not exist&quot;))<br>        return <br>    }<br><br>    if !queryExistsIn(params, &quot;q2&quot;) {<br>        W.WriteHeader(http.StatusBadRequest)<br>        w.Write([]byte(&quot;query &#39;q2&#39; does not exist&quot;))<br>        return <br>    }<br>    <br>    // and so on and so on<br>}</pre><p>But this still does not reduce the verbosity by lot, so I wanted to create a helper function which shall throw error of the missing query in the given URL params. And that is when I recalled <a href="https://go.dev/blog/errors-are-values">this</a> article. I thought I have the same problem of repetition by same operation and I will be throwing the same kind of error so this is the perfect opportunity to try this out.</p><p>Now before I write the code let’s make few things clear, the type of params is URL.Value which is alias for map[string][]string so what I ended up writing is, helper struct for key exists in a map or not.</p><pre>// mapHelper is used to check if given key exist if it does not then it<br>// will store the error in err<br>type mapHelper[k comparble, v any] struct{<br>    m map[k]v<br>    err error<br>}<br><br>// keyExists check if key of type k exists, if it does not<br>// then it will store error in h.err<br>func (h *mapHelper[k,v]) keyExists(key k) {<br>    _, ok := h.m[key]<br>    if ok {<br>      return<br>    }<br>    e.err = fmt.Errorf(&quot;key &#39;%v&#39; does not exist&quot;)<br>}<br><br>func Handler(w http.ResponseWriter, r *http.Request) {<br>    params := map[string][]string(r.URL.Query())<br>    paramChecker := mapHelper {<br>        m: params,<br>    }<br>    <br>    paramChecker.keyExists(&quot;q1&quot;)<br>    paramChecker.keyExists(&quot;q2&quot;)<br>    // and so on<br>    if paramChecker.err != nil {<br>        // handler this<br>    }<br>    <br>}<br></pre><p>this would reduce lot of the <a href="https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88"><em>unhappy path</em></a><em> </em>from the Handler. Where I was checking for 6 query params.</p><p>Now there is one problem with the above code, which is it only preserves only the, last not found query and nothing else, but do not worry there is easier fix for that, which is using error wrapping.</p><pre>// ....<br>// ....<br><br>// keyExists check if key of type k exists, if it does not<br>// then it will store error in h.err<br>func (h *mapHelper[k,v]) keyExists(key k) {<br>    _, ok := h.m[key]<br>    if ok {<br>      return<br>    }<br>    if e.err != nil {<br>      // if there is already a error recoreded, then wrap it<br>      e.err = fmt.Errorf(&quot;%w, key &#39;%v&#39; does not exist&quot;, e.err, key)<br>      return<br>    }<br>    e.err = fmt.Errorf(&quot;key &#39;%v&#39; does not exist&quot;)<br>}<br><br>// ....<br>// ....</pre><p>And now in my handler I can tell the client side precisely which query parameters it is missing.</p><p>On personal level, this experience helped me truly understand the proverb that errors in Go are just values, and just like any other values. I can wrap it in custom struct, encapsulate them and retrieve them as needed. Does this approach works everywhere? The answer is plain NO!!! but there are some cases where this might work very well.</p><p>I hope you got to learn something from reading my article, and if I there is something that needs further clarification feel free to reach out. Have a great day readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc588bb0b57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>