<?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 Kacper Madej on Medium]]></title>
        <description><![CDATA[Stories by Kacper Madej on Medium]]></description>
        <link>https://medium.com/@kmadej?source=rss-1a963f04d78b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VL75zw57gVS4jpks.</url>
            <title>Stories by Kacper Madej on Medium</title>
            <link>https://medium.com/@kmadej?source=rss-1a963f04d78b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:57:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kmadej/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[Interviewing in Ruby: a Minimal Assembly Interpreter]]></title>
            <link>https://medium.com/@kmadej/interviewing-in-ruby-a-minimal-assembly-vm-3486d113c4e9?source=rss-1a963f04d78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3486d113c4e9</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Kacper Madej]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 13:45:51 GMT</pubDate>
            <atom:updated>2018-03-20T22:04:05.467Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re applying for a Ruby Developer position at Company XYZ.</p><p>You successfully passed all previous interviews and you’re heading for the final one, which you know will be strictly technical.</p><p>You enter XYZ’s office where you’re warmly greeted by their office manager. They show you the way to a room where your interviewer waits for you.</p><p>At first, you’re feeling a bit nervous. But after a small chit-chat with the recruiter your stress level drops and you start feeling more comfortable.</p><p><em>“Okay, let’s get down to business,” </em>he says and hands you over a piece of paper with the following content:</p><pre>MOV A 10 # Store 10 in register A<br>MOV B A # Copy value from register A to register B<br>ADD A B # Add register A and B and store the result in register C<br>JMP 7 # Jump to line #7<br>JNZ 7 # Jump to line #7 if the value in register C is non-zero<br>MUL A B # Multiply values stored in registers A and B and store them in register C</pre><p>“<em>Oh sh*t, it’s Assembly!” </em>you think. Your hands started shaking, but you try to look cool.</p><p>“<em>Let’s implement a small Assembly interpreter that can execute instructions similar to those on this piece of paper” </em>the interviewer explains.</p><p>This is a real story that happened to a friend of mine.</p><p>Since I think this is an interesting problem I decided to take a stab at it myself.</p><p>Here’s the deal.</p><p>I’ll be writing this blog post as I progress through the solution. In a perfect scenario, I’d like to limit coding to somewhere between 60–90 minutes.</p><p>But because at the same time I’ll be writing down my way of thinking, I have to trust my gut feeling how long it’d take coding.</p><p>Of course, it won’t be the same experience as an actual interview. I’ll be missing constant feedback from an interviewer. And I’ll be sitting comfortably in my apartment with a low level of stress.</p><p>So, my dear reader, imagine we’re in this interview together. Go grab a cup of coffee and let’s get that job!</p><h4>Preparation</h4><p>Let’s get started! We’ll use Ruby and Minitest (though normally I prefer RSpec).</p><p>Before we write any code though, let’s try to come up with concepts related to this task. You know, naming is the hardest thing in computer science. That’s why I’d like to spend time coming up with decent names first.</p><p>Normally, we can speak with clients, product owners, or other domain experts to learn how they call things in the domain of interest.</p><p>In our case, we could search for the necessary concepts in the computer science literature (or ask Google). But for the sake of this exercise, let’s come up with something instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3Ur4nX3_ib8vpewao22Aow.jpeg" /></figure><p>So we have an <strong>Assembly language</strong>. It has <strong>instructions</strong> that we <strong><em>execute</em></strong>. How to call a set of instructions? An <em>instruction set</em>? <em>Instruction sequence</em>? I know! A <strong>Program</strong>! Sometimes obvious things hide in plain sight.</p><p>We’ll <strong><em>parse</em></strong> the <strong>code</strong> of the <strong>program</strong> in order to understand its <strong>instructions</strong>. Then using our <strong>interpreter </strong>we’ll <strong><em>execute</em></strong> these <strong>instructions</strong>. We also have 3 <strong>registers</strong>: A, B, C, that can <strong><em>store</em></strong> <strong>numerical values</strong>.</p><p>We just came up with our dictionary — the nouns and verbs marked in bold.</p><p>I think this dictionary is big enough for now. Although we may discover new concepts later, I’m comfortable enough to start coding.</p><h4>First steps</h4><p>Let’s come up with a basic test — executing an empty program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f72d8f7cd101a9327277a9afb8ee8b6a/href">https://medium.com/media/f72d8f7cd101a9327277a9afb8ee8b6a/href</a></iframe><p>Yeah, I like to give my projects cheesy names.</p><p>The code isn’t in any way smart — executing an empty program should result in having 0&#39;s in all our registers.</p><p>We could later decide to refactor register to a separate class. For the time being we’ll keep it simple and treat each register as a key, value pair in a <strong>Hash</strong> though.</p><h4>Implementing the MOV instruction</h4><p>Okay, let’s try to modify the content of register A by implementing the MOV instruction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f499c4ee41dd614a16fab01fb738e24/href">https://medium.com/media/2f499c4ee41dd614a16fab01fb738e24/href</a></iframe><p>The tests are passing.</p><p>We assume our program can only consist of one line of code, but we’ll fix this later.</p><p>We can either refactor now or cover some corner cases. I prefer to cover corner cases first. It makes me more comfortable with refactoring later. I also find it easier to think of any edge cases as soon as possible.</p><p>So what happens when the instruction looks like this: MOV A , MOV , or MOV A asdasd ?</p><p>Or what if someone wants to use a register that doesn’t exist: MOV D 7?</p><p>These are all things we should guard against.</p><p>So let’s add tests and start throwing some errors!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b9df431896aeb203be0dc05a17a8f9/href">https://medium.com/media/01b9df431896aeb203be0dc05a17a8f9/href</a></iframe><p>Yay! I’m feeling much more comfortable now. But the code doesn’t look pretty. Let’s do some refactoring!</p><h4>First Refactoring</h4><p>Let us to extract some domain concepts into separate classes.</p><p>What should we start with?</p><p>Parameter validation in execute method looks suspicious. I think it doesn’t belong there. The whole code block inside the if statement looks like an <strong>Instruction</strong>. So let’s try to refactor out an instruction.</p><p>Also, this made me realize that the command variable has an incorrect name. It really should be called instruction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb6aecce11abbe8be9c0adbafad18ac/href">https://medium.com/media/bcb6aecce11abbe8be9c0adbafad18ac/href</a></iframe><p>That’s much more elegant and all our tests still pass!</p><p>We still have a conditional instruction in Assemrby.parse and some hard-coded strings though. Let’s leave them for now and implement more requirements instead.</p><h4>Handling Multiple Lines of Code</h4><p>I think it’s high time our library could parse more than one line of Assembly code. The change should be easy. Let’s write a test that uses the MOV instruction multiple times and implement the required changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2561277eb7e1aede9d88dea8ddc848dc/href">https://medium.com/media/2561277eb7e1aede9d88dea8ddc848dc/href</a></iframe><p>That was easy!</p><p>It also made me realise one more thing: we should raise an error when we don’t recognise an instruction. Lets continue with our requirements!</p><h4>Handling ADD and MUL Instructions</h4><p>So let’s implement ADD and MUL instruction and handle the case when we don’t recognise the instruction.</p><p>Be aware that we can do the following: ADD 10 A , ADD 10 15 , or ADD A B. We have a lot of cases to cover.</p><p>Below we implement all these test cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caebd39924073bd15b09892f8904d5c9/href">https://medium.com/media/caebd39924073bd15b09892f8904d5c9/href</a></iframe><p>This test file really starts looking like a mess. We should do something with it.</p><p>Here’s the plan.</p><p>First, we’ll extend the previous if-statement to a case-statement. We’ll handle the new MUL and ADD instructions. We’ll raise error when we don’t recognise the instruction.</p><p>Then we’ll refactor the new code.</p><p>Finally, we’ll refactor our tests.</p><p>So let’s continue coding! First, the raw code that passes all tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5d7b71c44e108f6a5bc9393a95fc6f/href">https://medium.com/media/be5d7b71c44e108f6a5bc9393a95fc6f/href</a></iframe><p>Those new instructions have a lot in common. I copy-pasted code from one to the other, so they’re really similar.</p><p>And they’re both <em>really</em> ugly.</p><p>I didn’t even bother to change variable names. I hope you don’t commit code that looks like this :).</p><p>On the other hand, our tests are passing. We can safely refactor this monstrosity.</p><p>The worst part of this code is that we have to treat numerical values and register references differently. Plus we have to do it in both classes.</p><p>We’ll try to extract a nice interface that will let us forget about this.</p><p>Then we’ll see if it makes sense to remove the remaining duplication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02f0cbd8a7be83d03ed2e09c44b03d51/href">https://medium.com/media/02f0cbd8a7be83d03ed2e09c44b03d51/href</a></iframe><p>It looks much better now!</p><p>I’m not super proud of the names we came up with though. Assemrby::Value#value doesn’t sound good and might be confusing.</p><p>On the other hand, I think that Add and Mul got handled well. They still look quite similar but this time I won’t remove the duplication.</p><p>When I was a junior developer I thought that code duplication is wrong and has to be fought immediately. However, with experience I learned it’s not always a bad thing.</p><h4>Cleaning Up Tests</h4><p>I guess if I haven’t been writing my thoughts down, I’d already hit either 60- or 90- minute mark. Let’s clean up the tests and finish. After this we’ll have a moment of reflection on the code.</p><p>We have a lot of tests that exercise different instructions. I believe we should move them to test files specific to each instruction. So here we go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd35565c44cb8dfe3a2f075ae59d595f/href">https://medium.com/media/dd35565c44cb8dfe3a2f075ae59d595f/href</a></iframe><p>And I think we can stop here. We didn’t implement all the features but I think we went quite far for a blog post.</p><p>What we’re missing are the JUMP instructions. How would we implement them?</p><p>We’d have to store a value of an <strong>Instruction Pointer</strong>. An Instruction Pointer would store the line number we’re currently executing. We would have to pass the instruction pointer to Instruction#execute along with registers.</p><p>The way I’d approach it would be first extracting a separate class that would store both the registers and the Instruction Pointer.</p><p>How would we call the new class? ExecutionEnvironment perhaps? Or simply Environment. Then we could safely pass an object of this class around.</p><p>Also, the JUMP instruction could potentially jump into a yet unparsed line of code.</p><p>Because of this, it’d be simpler to first parse all the code and build the Instruction objects first with Instruction#build.</p><p>Then, we could store these objects in an <strong>Array</strong>. An Instruction Pointer would simply be an index of this array.</p><p>Then, we would perform an execution phase, where we’d simply iterate over the Array and call Instruction#execute on every object.</p><p>Again, here’s the whole code for reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b503c25256d1a51895e84d109416cb79/href">https://medium.com/media/b503c25256d1a51895e84d109416cb79/href</a></iframe><h4>Summary</h4><p>What could be improved in the current code?</p><p>I’d certainly want to spend more time on having clear error messages when raising errors. This helps tremendously in debugging later on.</p><p>Also, I don’t like the way Instruction objects are being built. We have a case statement that’d grow with every new instruction added. We could have an Instruction registry and have each Instruction class register in it instead. The registry would then have a factory method that’d build Instruction objects.</p><p>I like how Assembry::Value let’s you forget about what kind of thing you’re dealing with, but I believe we should spend some time thinking about proper names there.</p><p>I also have mixed feelings about passing registers everywhere but I can’t think of any solution. Maybe that’s just the way it is?</p><p>We’re also explicitly calling registers[&#39;C&#39;] in Add and Mul. However, I’m not sure this is that bad in this case.</p><p>We could also spend some time extracting small private methods to keep the abstraction level consistent.</p><p>And we could add several more tests. For example, we didn’t cover any cases in which we should throw errors in neither ADD nor MUL. And we only covered Registry-Numeric case, but we didn’t cover Numeric-Registry case. See the difference: ADD A 2, ADD 2 A.</p><p>I also think we failed to come up with clear names a few times. Do you really build an Instruction? Shouldn’t it be called parse instead? We talked about programs before, but this concept isn’t anywhere in our code.</p><p>So that’s it! I hope you’ve enjoyed it.</p><p>I’m really interested in how you would approach this problem.</p><p>What would you do differently?</p><p>What do you like/dislike about my solution?</p><p>I hope we’ll have an interesting discussion in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3486d113c4e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Violating The Principle of Least Surprise Can Introduce Subtle Bugs to Your Code]]></title>
            <link>https://medium.com/u2i-blogs/how-violating-the-principle-of-least-surprise-can-introduce-subtle-bugs-to-your-code-8902cc51dc29?source=rss-1a963f04d78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8902cc51dc29</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Kacper Madej]]></dc:creator>
            <pubDate>Tue, 26 Sep 2017 08:17:22 GMT</pubDate>
            <atom:updated>2017-09-26T14:57:22.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*to5bgHjNQpBwP6mdj-JQCA.jpeg" /></figure><p>If you were to name one common thing to all software developers working in various domains and languages what would it be? I would say <strong>bugs</strong>! Bugs and a career in software development are inseparable. You introduce bugs, you discover bugs and you fix bugs introduced by others. Most of them are obvious and easy to fix but some are a nightmare to track down and can cause a lot of harm. And one of the reasons such bugs are introduced are APIs that violate the <strong>Principle of Least Surprise</strong>.</p><p>The Principle of Least Surprise (or the Principle of Least Astonishment) is a general design rule which states that your design should match the mental model of your expected audience. In the domain of API design your audience consists of the developers that will have to work with the code you wrote. <br>There’s a <a href="https://www.destroyallsoftware.com/talks/wat">great talk</a> by Gary Bernhardt about various Javascript features that don’t follow this principle. I highly recommend you to watch it.<br>I’d like to tell you a story about how we were hit by this principle after migrating a gigantic Ruby on Rails monolith to Rails 4.</p><p><em>“But there’s already Rails 5!”</em> you might say — undoubtedly there is. But with such a large codebase it’s not trivial to always be up to date with the technology, especially given that most of our work is development.</p><p>The system I’m writing about has 180k lines of code and 125k lines of tests in one Rails App. Plus we also have other services living in different codebases. We’ve been building this whole ecosystem from scratch for 7 years; and for the last 3 years we’ve had 20+ developers constantly involved in it.</p><p>The application tracks various things on the Internet and generates various reports on them. For the purpose of this blog post let’s refer to the things we track as Records and additional information related to them as Metadata.</p><p>After we deployed the new version of the system to production it turned out that we had a very serious bug lurking in our code. From the outside it looked like the number of records we tracked dropped by around 30%. This is all because of a small change in our codebase related to an API which violated the Principle of Least Surprise. We were really surprised when we found it because the code itself had nothing to do with our tracking system and it wasn’t in the code’s intent to make any database changes.</p><p>It turned out that the faulty part lied in one of our data exporters. The code flow is pretty obvious:</p><p>1. Fetch the records from the database<br>2. Have some business logic filter out some of the records we don’t want to export<br>3. Serialize them<br>4. Export the data to S3</p><p>I will simplify the code just to show you the point. The real code is a bit more complicated and the faulty part of it was changed more than once. Here’s the simplified version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91de57465cf99572366c13c6156f7b4c/href">https://medium.com/media/91de57465cf99572366c13c6156f7b4c/href</a></iframe><p>Now, what could possibly go wrong? Below is the original version of filter_exportable_records:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a67ee9dd6e027b6ca7d2155ce26f8e4/href">https://medium.com/media/7a67ee9dd6e027b6ca7d2155ce26f8e4/href</a></iframe><p>In Rails 3 if you inspect record.metadata.class it is a plain Array. But in Rails 4 it&#39;s an instance of ActiveRecord::Associations::CollectionProxy which doesn’t have the select! method. So a straightforward way to upgrade the code is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc8e3e04a5cd713a6c980d2e7b7f3e86/href">https://medium.com/media/cc8e3e04a5cd713a6c980d2e7b7f3e86/href</a></iframe><p>When reading this blog post it should be now pretty obvious to you, but in case it’s not: we’re reassigning something to an ActiveRecord relation, which… makes a database call and removes metadata that do not conform to some_business_condition? from the database! But all of the metadata is crucial to our tracking system!</p><p>But anyway we weren’t able to catch it despite having quite a rigorous release process. We had two experienced developers pair-programming on this task and two more reviewing the pull request. Those four people had years of experience with Rails. So it’s neither obvious when you change the code nor when you look at the diff. And it couldn’t be caught with tests because you simply don’t expect a piece of code that exports some data to alter the database in any way. It just has to be observed on a living system. And unfortunately nobody noticed this issue on staging so we had a lot of fire to extinguish on production.</p><p>We all know that assigning an Array to an ActiveRecord relation makes a database call, but as I’ve just shown you sometimes it’s just too easy to miss. In my opinion either the = method shouldn’t make a database call or it shouldn’even exist at all.</p><p>But it’s highly improbable that this behavior will change in the future. How can we live with it and protect ourselves against this kind of bugs? I can think of only one solution. Do not mutate ActiveRecord objects when you have no intent of actually modifying your database. So the original code would have to extract all the data it needs into some Plain Old Ruby Objects and not mess with the AR objects themselves. But it requires more code and is not as convenient.</p><p>What can we do as developers in general? I believe we should design our APIs in a way that they are simple but not too simple. We should strive to keep a balance between expressiveness and explicitness. Too much expressiveness will lead you to bugs like the one described in this blog post; too much explicitness will make your APIs inconvenient to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8902cc51dc29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/u2i-blogs/how-violating-the-principle-of-least-surprise-can-introduce-subtle-bugs-to-your-code-8902cc51dc29">How Violating The Principle of Least Surprise Can Introduce Subtle Bugs to Your Code</a> was originally published in <a href="https://medium.com/u2i-blogs">u2i’s lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>