<?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 Jude Dutton on Medium]]></title>
        <description><![CDATA[Stories by Jude Dutton on Medium]]></description>
        <link>https://medium.com/@judedutton?source=rss-320bc87a8a8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cz4gmPZ8cRhJ8LCV_ltVYg.jpeg</url>
            <title>Stories by Jude Dutton on Medium</title>
            <link>https://medium.com/@judedutton?source=rss-320bc87a8a8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:56:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@judedutton/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[Recursion: A story about itself]]></title>
            <link>https://medium.com/@judedutton/recursion-a-story-about-itself-e7df4aa5a474?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7df4aa5a474</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 17:27:25 GMT</pubDate>
            <atom:updated>2018-11-02T17:27:25.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCKTbrpwXcNmxp335VNBbQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ne-97EhFXyQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anton Darius | @theSollers</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Learning recursion was by far one of the most terrifying concepts for me to face when I learned to build algorithms to solve complex computer science conundrums. However, I don’t think that necessarily has to be the case.</p><p>Recursion is often hailed as one of the integral parts of a software engineer’s tool-belt and it truly can be handy. Today, let’s solve a problem using recursion and pull back the curtain a bit on this helpful, but intellectually elusive concept.</p><h4>Step 1: What is recursion again?</h4><p>Recursion is the art of reapplying a set of logic to itself to eventually reach a solution. It is generally accepted that there are two key components to recursion:</p><p>The <strong>Base Case</strong> is the condition at which recursion stops and a solution is returned. It is your guard against stack overflow, so don’t forget it!</p><p>The <strong>Recursive Case</strong> or <strong>General Case</strong> is one (<em>or more</em>) condition(s) which contain the bulk of the function’s logic and a recursive call to the function itself.</p><p>In computer science, recursion operates based on the idea of a stack. Consider a stack of plates in your cupboard. Usually, the last plate that you put into the stack (which is now the plate on top) is the first plate you take out later. Recursion sets up this whole call stack based on the initial call of the function and then works backwards to evaluate that stack of nice clean plates in order from top (last in, first out) to last.</p><h4>Step 2: An Obligatory, Contrived Example.</h4><p>Let’s make a recursive function that prints out the string ‘DONE’. For demonstrative purposes, we will actually have the program print out…</p><pre>D<br>DO<br>DON<br>DONE</pre><p>…all using recursion. Let’s identify the key parts of this small program. Now that we’ve reviewed the key components of recursion, we know this means we will need a <strong>Base Case</strong> and one or more <strong>Recursive Cases</strong>. Our program will be centered around one parameter, that will have a default argument of the string “D”:</p><ul><li><strong>Base Case</strong>: If string is equal to &#39;DONE&#39; print the string to the console and return, thus ending the program.</li><li><strong>Recursive Case 1</strong>: Otherwise, if string is equal to &#39;D&#39; print the string as is, then concatenate &#39;O&#39; onto the end of it, and call the function again.</li><li><strong>Recursive Case 2</strong>: Otherwise, if string is equal to &#39;DO&#39; print the string as is, then concatenate &#39;N&#39; onto the end of it, and call the function again.</li><li><strong>Recursive Case 3</strong>: Otherwise, if string is equal to &#39;DON&#39; print the string as is, then concatenate &#39;E&#39; onto the end of it, and call the function again.</li></ul><p>These cases should be enough to get us the results that we want. The cases used in recursion are most often implemented as some sort of branch logic: case statements, if statements, etc. We will use basic if/elsif statements in Ruby for this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f55736eb96177d2dad1bac4f034c07b/href">https://medium.com/media/2f55736eb96177d2dad1bac4f034c07b/href</a></iframe><p>Try adding this into an .rb file and running the code, you should see the expected output as recursion sets up the stack and knocks it down. If you have issues or questions about this example, please let me know in the comments 😃</p><h4>Step 3: Let’s Get Real</h4><p>You ever wonder how automated cash registers know how to give you change? How does it know currency? How does it decide what type of change to give me? Why 4 quarters instead of 10 dimes or 100 pennies?? Yikes, the things we take for granted 😅.</p><p>Anyway, the answer is most likely software engineers showing their hand in our daily lives, and it is entirely possible that they solved this issue with recursion. Here’s the scenario — you’re given a string that represents the dollar and cents amount of change to be given. Our machine cannot vend bills (don’t ask, it’s a long story), so let’s figure out the smallest number of coins we can give back to the customer and get them their shiny change and on their way.</p><ul><li>Given &#39;1.25&#39;, return {quarters: 5} (In other words, 5 quarters).</li><li>Given &#39;1.26&#39;, return {quarters: 5, pennies: 1}</li><li>Given &#39;10.00&#39;, return {quarters: 40} (missing those bills now 😧)</li><li>Given &#39;1.73&#39;, return {quarters: 6, dimes: 2, pennies: 3}</li></ul><p>Sound good? If not just let me know in the comments below👇</p><blockquote>Also, thanks to my mentor early on in Turing, Robert Gu, who brought this problem to my attention!</blockquote><h4>Step 4: Tests — that’s right, tests.</h4><p>What? Did you think we’d skip testing?? How else are we supposed to know that we have the right answers 😂</p><p>The focus of this post is not testing with rspec, but I will briefly go over how I setup tests. If you are using another language and you’re curious how to test / you run into issues with these brief instructions, just let me know and I’ll be happy to help if I can!</p><p>Start by setting up a directory structure. I would recommend creating a folder called ruby_challenges (there may be more of these in the future 😉) with a lib folder inside of it:</p><pre>mkdir -p ./ruby_challenges/lib &amp;&amp; cd ruby_challenges</pre><p>Next, if you have never installed rspec, run gem install rspec to get the latest version installed for global use. In the same directory, after successfully installing rspec, initialize it:</p><pre>rspec --init</pre><p>This command should create a spec folder, a spec_helper file, and an .rspec configuration file. I would recommend adding the following line to .rspec to improve the output of rspec:</p><pre>--format=documentation</pre><p>Fantastic, in the spec folder, create a file called change_calculator_spec.rb and add the following test code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11aed6e0a5ea7cad23e5a322e7fb397e/href">https://medium.com/media/11aed6e0a5ea7cad23e5a322e7fb397e/href</a></iframe><p>Let’s go ahead and outline our class and method structure so our test will <em>fail</em> rather than error out. Put this scaffold in a file called change_calculator.rb in the lib folder we created previously:</p><pre>class ChangeCalculator<br>  def self.smallest_combination(args)<br>    # This is where our code will go<br>  end<br>end</pre><p>Finally, run rspec in the terminal that is sitting in the ruby_challenges directory and you should see a failing test. If so, perfect. Move right along. Otherwise, you know what to do!</p><h4>Step 5: Time for Some Outlining</h4><p>Working in the same, change_calculator class, lets outline our conditions. We will keep track of coin amounts, starting with our largest cents value, the quarter (25) and move down from there. Here are our cases:</p><ul><li><strong>Base Case</strong>: We’re going to keep track of our given change value, and a counter. When the change value (in cents) and counter (also in cents) equal each other, we need to return our result and stop the function: cents == count</li><li><strong>Recursive Case 1</strong>: If the current count plus one more of the current coin value is less than the cents value, we can keep going. We will add to our count to keep working towards cents and call the function again.</li><li><strong>Recursive Case 2</strong>: If the current count plus one more of the current coin value (next_value) is greater than the cents value, we’ve gone too far. We will not add to count instead we will move to our next smallest coin value by increasing our index value that is tracking which coin in the array of values we would like to test against. This will make more sense in context.</li></ul><p>Those are all of the cases! We have some general code challenge housekeeping tasks to do to set up the context for this recursive branch logic. First, let’s determine our local variables:</p><ul><li>We will have an array that contains our bank of possible cents values (pun intended): [25, 10, 5, 1]. We will call this possible_coin_values.</li><li>We will have a cents value that will contain the given string value, formatted into an integer that represents cents.</li><li>We will also have a dynamic local variable called next_value. It will be set to the current count, plus one more of the current coin value.</li></ul><p>Our local variables all set up will look like this:</p><pre>class ChangeCalculator<br>  def self.smallest_combination(args)<br>    possible_coin_values = [25, 10, 5, 1]<br>    cents = (dollar_value.to_f * 100).to_i<br>    next_total = count + possible[index]</pre><pre>    # The rest of our code<br>  end</pre><p>Wait. Something is weird here. Where did dollar_value, count, and index come from? They are a look at the future arguments that will really make this recursion cook. Let’s look at those arguments injected into context right away:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de18591c64b0e868175439d2c356658/href">https://medium.com/media/7de18591c64b0e868175439d2c356658/href</a></iframe><p>Notice the parameters that we have now defined as part of the smallest_combination method:</p><ul><li>dollar_value is the string that we receive as input that represents the dollar and cents amount of change needed.</li><li>count is our current running total <em>prior</em> to adding on a new possible coin value. This is how we will generate next_value and check our progress.</li><li>record is how we will keep track of the coins that we know will be a part of our end result. We will update record every time that we check next_value and it is less than or equal to cents. That would be <strong>Recursive Case 1</strong> and the <strong>Base Case</strong>.</li><li>Finally, index is how we will keep track of which coin we are on in the possible_coin_values array. This index will be updated in the event of <strong>Recursive Case 2</strong> when we go over the cents value and need to move on to the next smaller coin value.</li></ul><h4>Step 6: Take a Pomodoro Break</h4><p>Yep, that’s right — take a break! That’s a lot of information. Give it some time to process. I’ll see y’all in five minutes. If you’re unfamiliar with Pomodoro breaks, lovingly referred to as ‘poms’, take five minutes to <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique">read up on them</a>.</p><h4>Step 7: Time for Some Recursion</h4><p>We’re going to write this all in one method which is going to be a lot of code. But let’s get our test passing (green) and then we will refactor as review. Let’s go over what we need:</p><ul><li>We need a method with four arguments, three of which have default values: dollar_value, count = 0, record = {}, index = 0.</li><li>We need some local variables to track possible_coin_values, the dollar value as cents, and our dynamically updated next_value.</li><li>We will need a set of branch logic that represents our <strong>Base Case</strong> and two <strong>Recursive Cases</strong>.</li><li>We will need some logic to make sure that our record is getting updated appropriately.</li></ul><p>Here is how I would accomplish this in addition to some copious comments. Please take a look at this and then try this on your own. Please bear in mind that this is pre-refactor and should not be emulated — it is strictly for demonstrative purposes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b23ab89ac152c5578145d81f09a79e68/href">https://medium.com/media/b23ab89ac152c5578145d81f09a79e68/href</a></iframe><p>Whoa! That really is a nasty bit of code, but let’s hold on to this for reference as we refactor and make sense of this. The first code smell that I sense here is an infraction of the single-responsibility principle (SRP). See how we have that huge case statement for updating record twice? That could be its own class method.</p><ol><li>Let’s do that.</li><li>Let’s also remove the comments.</li><li>Pull out an additional method for converting the string dollar_value into cents.</li><li>Finally, see how we use possible_coin_values[index] everywhere? Not only is that too verbose, it’s inefficient. Let’s create a new dynamic local variable to hold that value for each recursive call and change it only as needed.</li></ol><p>Here’s the updated code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3aab6960f6da94ce40ec06f89b9ce8/href">https://medium.com/media/3f3aab6960f6da94ce40ec06f89b9ce8/href</a></iframe><p>Much better right? Let’s go through this again step by step.</p><ul><li>Line 3: That’s a class-level instance variable. We are working with class methods, so it needs to be <em>outside</em><strong><em> </em></strong>of a call to initialize, but also available in our class methods.</li><li>Our new local variable current_coin is updated when we change the index value in the case of <strong>Recursive Case 2</strong> and our remaining local variables are the same.</li><li>We should <em>always</em> consider our <strong>Base Case </strong>first, that way we are not skipping our base case and risking stack overflow. So in the event that our next_total is equal to cents we know we’ve found our solution. Update the record one last time and return ending the recursion. (lines 10 -12)</li><li><strong>Recursive Case 1</strong> is next in line. If our next_total is less than cents we know we can continue with our current_coin value, so we add it to count, update the record (using our fancy new update_record method that DRY’ed up our code), and recursively call the method with updated arguments passed in. Notice we don’t update index, this is so we keep the current_coin value as is.</li><li><strong>Recursive Case 2 </strong>is up next. If our next_total goes over our cents amount we know we’ve gone too far, we need to keep the count and record right where they are, but we need to update index. We will then recursively call the method, passing in the <em>unchanged </em>count and record arguments, as well as our updated index.</li><li>The methods outside of smallest_combination are just helper methods that DRY (<strong>D</strong>on’t, <strong>R</strong>epeat, <strong>Y</strong>ourself) up our code. update_record handles the updating of our record whenever we need it, and get_cents handles the conversion of our string dollar/cents input to the clean cents integer that we use throughout our main recursive method.</li></ul><p>Run your tests with rspec and enjoy the results!</p><h4>Step 8: Rejoice!</h4><p>You did it 🎉 , that’s recursion and our example in a nutshell! If you would like another challenge let me know what you’re looking for by adding a comment below. Have ideas? Concerns? Critiques? Questions? Just let me know! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7df4aa5a474" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FizzBuzz in MySQL Using Stored Procedures]]></title>
            <link>https://medium.com/@judedutton/fizzbuzz-in-mysql-using-stored-procedures-a097f7ca337b?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a097f7ca337b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Sat, 27 Oct 2018 22:59:07 GMT</pubDate>
            <atom:updated>2018-10-30T21:04:18.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psUl5KT0bTuzVreoYOkCLw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/98ZPPbp7mIc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/soda?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>FizzBuzz is a common coding challenge that deals mainly with branch/conditional logic and, depending on the language, data type manipulation. The general idea is this: Given a series of concurrent integer values (i.e. 1–100), print out all of the numbers adhering to the following conditions.</p><ul><li>If the number is divisible by 3, print out ‘Fizz’.</li><li>If the number is divisible by 5, print out ‘Buzz’.</li><li>If the number is divisible by 3 <em>and </em>5, print out ‘FizzBuzz’.</li><li>Finally, if the number is not divisible by 3 or 5, print out the number.</li></ul><p>Given the numbers 1–15 the output (as a comma separated list) would look something like this:</p><pre>1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz...</pre><p>Got it? If not, feel free to comment and I can explain it in more detail 😄</p><p>It is quite common to complete this challenge in a generalized computing/scripting language like C++, Ruby, JavaScript, or Python. Today, we will do this using SQL, specifically using MySQL.</p><h3>But, Why?</h3><p>I get this question a whole lot, especially when I start nerd-ing out about the importance of SQL and bypassing an Object Relational Mapper’s query builder to other backend engineers. If you are dealing with data at any point, then you will need to understand how to manipulate and retrieve this data. As of today, relational databases are the status quo for storing and otherwise dealing with data. It is important as a coder who is responsible for the data to understand the details of the query that you are creating and the stability of the data that you are handling. Using raw SQL to interface with your data is as close as you can get to the data without jumping the proverbial canyon that separates you from things like machine-language, assembly, and binary 😁</p><p>So, today we will accomplish one of the most common coding challenges in raw SQL. It’s gonna be fun, I promise.</p><h3>Getting Set Up With MySQL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-lOLFIlgxwwBti7wwq2Jg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/s8OO2-t-HmQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hunter Haley</a> on <a href="https://unsplash.com/search/photos/tools?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>First and foremost, you will need MySQL installed. We will go the quick route below, but for more details, please check out <a href="https://medium.com/@judedutton/its-gonna-be-okay-my-intro-to-mysql-1677c3f4901f">my blog post about getting started with MySQL</a>.</p><h4>Step 1: Install MySQL</h4><p>Let’s go ahead and use the best package manager created so far for UNIX and install MySQL using Homebrew. (If you need to install Homebrew, <a href="https://brew.sh/">go here</a> and follow the latest installation instructions).</p><p>After you’ve installed Homebrew, run the following command in your Terminal to install MySQL for use in your command line:</p><pre>brew install mysql</pre><p>After the installation completes, start the service:</p><pre>brew services start mysql</pre><p>Any issues? Comment and let me know 😄</p><h4>Step 2: Access MySQL Console</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wChtZ64zkPw_nQQa9cu_8A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/IL1qSqEMNBo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nhu Nguyen</a> on <a href="https://unsplash.com/search/photos/keyboard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now we need to log in to MySQL. We are going to go ahead and log in as root and, frankly, skip user account configuration. Not generally a good idea, so if you want to setup your user account and secure it and the root account, check out <a href="https://medium.com/@judedutton/its-gonna-be-okay-my-intro-to-mysql-1677c3f4901f">my blog post about it</a>.</p><p>Run this command to log in as root:</p><pre>mysql -u root -p</pre><p>You will be prompted for a password, just press return and log in. There should be no password unless you’ve set one up. You should now be logged in and see the following prompt:</p><pre>mysql&gt; </pre><p>If you see this, you are good to go! If not, well, comment and let me know 😄</p><h4>Step 3: End Goal and Setting Up the Database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJQdo_YHi_lWSLPl70E4wQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/qZQriezeRcc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Orlova Maria</a> on <a href="https://unsplash.com/search/photos/finish-line?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>One of the most important things to understand when completing a coding challenge is, what the input/output will be. We already know that our input will be a range of numbers. We will assume that we are always starting from one and that we are simply provided the upper limit of the range. So given 30, we will FizzBuzz all the numbers between 1 and 30.</p><p>The output will be a table that we create will be a table with two columns. The first column will be an auto-incremented id just like the primary key on a normal table of records and column called output that will take in a string of no more than 80 characters.</p><p>An edge case here would be trying to insert any numeral over 80 characters long (because it’s technically a string) but that’s a bit out of scope for this post. Here’s what the end result should look like given a max range of 15:</p><pre>+----+----------+</pre><pre>| id | output   |</pre><pre>+----+----------+</pre><pre>|  1 | 1        |</pre><pre>|  2 | 2        |</pre><pre>|  3 | Fizz     |</pre><pre>|  4 | 4        |</pre><pre>|  5 | Buzz     |</pre><pre>|  6 | Fizz     |</pre><pre>|  7 | 7        |</pre><pre>|  8 | 8        |</pre><pre>|  9 | Fizz     |</pre><pre>| 10 | Buzz     |</pre><pre>| 11 | 11       |</pre><pre>| 12 | Fizz     |</pre><pre>| 13 | 13       |</pre><pre>| 14 | 14       |</pre><pre>| 15 | FizzBuzz |</pre><pre>+----+----------+</pre><p>Got it? If not, you know what to do 😄</p><p>Let’s create a database called Fizz_Buzz for this exercise and then switch into that database:</p><pre>mysql&gt; CREATE DATABASE Fizz_Buzz;<br>...<br>mysql&gt; USE Fizz_Buzz;</pre><p><em>Don’t forget to terminate SQL commands with semicolons!</em></p><p>Now let’s create the table that will hold our results — because I like practicality and non-obfuscated database names, we’re going to name the table the creative name of results:</p><pre>/* In the database Fizz_Buzz */</pre><pre>mysql&gt; CREATE TABLE results (id SERIAL, output CHAR(80));</pre><p>The terms SERIAL and CHAR(80) are assignments of data types to the columns id and output respectively. SERIAL is an alias for a lot of data types chained together but it’s great for primary keys because some key components include that the data is an integer (BIGINT(20) to be specific), unsigned (never negative), auto-incremented, not null, and unique. CHAR(80) is much more straightforward, it is basically a ‘string” (really a set of characters) exactly 80 characters long.</p><blockquote>Side Note: If you ever want to see all of the columns (fields) and their data types, you can run DESCRIBE &lt;TABLE_NAME_HERE&gt;; to see that information. For our example: DESCRIBE results;.</blockquote><p>Phew! 😅 Okay, now let’s make sure this table works by inserting some data, specifically one record using the output column directly, to make sure this all works. We will use the INSERT INTO SQL syntax to do so:</p><pre>mysql&gt; INSERT INTO results (output) VALUES (1);</pre><p>… and then let’s check out work:</p><pre>mysql&gt; SELECT * FROM results;</pre><pre>+----+--------+</pre><pre>| id | output |</pre><pre>+----+--------+</pre><pre>|  1 | 1      |</pre><pre>+----+--------+</pre><p>Remember: We used the data type CHAR(80) for output, so why does inserting a number work? Well, it’s assumed to be a character or set of characters even though it visibly looks like an integer. We are using this to our advantage because we will need to add ‘numbers’ as well as strings like ‘Fizz’ and ‘Buzz’ in the same column. Always know your field data types!</p><p>Let’s go ahead and clear out that table using the following command (we will need this later as well I promise). This will clear out that table’s data <em>and </em>reset the auto-increment sequence for the id column:</p><pre>mysql&gt; TRUNCATE TABLE results;</pre><p>Fantastic! Wasn’t that great? Now that we have the basics down, we are ready to dive into the concept of a stored procedure.</p><h4>Step 4: Understanding Stored Routines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4x8Zuht2TaQ87ZhwYcLUqQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/xe-e69j6-Ds?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chad Kirchoff</a> on <a href="https://unsplash.com/search/photos/engine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Stored routines refers to the general concept of stored procedures and stored functions. A stored routine is a set of logic saved to a database to be used and run as part of that databases’s data set. In other words, creating a stored routine is like defining a method, function, lambda, or proc in most generalized programming languages. This will be the beating heart of our FizzBuzz challenge, so let’s try a smaller example first.</p><p>One quick note: the difference between stored <em>procedures</em> and stored <em>functions</em> is that a stored procedure is much like an expression, where it is a set of logic defined to basically perform an action. In the context of a database it is designed to operate on data without returning a value.</p><p>Stored functions? You guessed it, they do return a value, and as such employ much more complicated data type declarations. Today, we will used stored procedures because that’s all we need.</p><h4>Step 5: Creating a Simple, Familiar Stored Procedure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf7N3m39Qtuez9Lr6E_big.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/pfSNx3Z12K8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Taelynn Christopher</a> on <a href="https://unsplash.com/search/photos/paint-brush?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Remember those two commands we used to create a row of data (INSERT INTO)and then basically reset the table (TRUNCATE TABLE)? We will now create a procedure that does those two commands for us in one procedure.</p><blockquote>In case you need it, here is the MySQL (8.0) documentation for <a href="https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html">the </a><a href="https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html">CREATE PROCEDURE syntax</a>.</blockquote><p>We will go ahead and create this procedure in the MySQL console. This can be difficult because of the way that code completion is managed. In other words, as we type in the console, incomplete statements will be preceded by a small arrow -&gt; instead of the mysql&gt; prompt. If you mess up a line and move to the next line, you will need to use the command \c to clear the input and try again.</p><p>If you create the procedure and it’s broken you will need to delete the procedure DROP PROCEDURE &lt;procedure_name_here&gt; and recreate it. While this latter issue will remain, we will make the code writing much simpler in the next section, but for now let’s use the console.</p><p>We will first need to change the ‘delimiter’ or in other words, the character that tells the console that the sequence is terminated. This is so that we can use the proper semicolon delimiter to define the procedure in the console and then change it back to the semicolon later:</p><pre>mysql&gt; DELIMITER //</pre><p>This just means that we will need to add // at the end of our full statement to tell MySQL ‘OK, we’re all done’.</p><p>We’re going to call our procedure goodbye_data_hello_data — it will reset the table first and then add in the data:</p><pre>mysql&gt; CREATE PROCEDURE goodbye_data_hello_data(value CHAR(80))<br>    -&gt; BEGIN<br>    -&gt;   TRUNCATE TABLE results;<br>    -&gt;   INSERT INTO results (output) VALUES (value);<br>    -&gt; END //</pre><p>We should now be able to call this procedure and pass it any argument that is a set of one or more characters less than 80 characters in length. The fourth line is the really dynamic part of this procedure. It uses the value argument to insert whatever character(s) is/are passed in when the procedure is called.</p><p>We can now change our delimiter back, and call our procedure using the CALL syntax:</p><pre>mysql&gt; DELIMITER ;<br>mysql&gt; CALL goodbye_data_hello_data(2);</pre><p>After we call the procedure, using the query SELECT * FROM results; should return to us a table with one row, with an id of 1 and an output of 2. Try running the procedure again using an argument of ‘Fizz’: CALL goodbye_data_hello_data(&#39;Fizz&#39;). What happens?</p><h4>Step 6: Moving Out of Console as Things Get More Complex</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VwIQRT_Mb3i1HMz4w9_5g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ULLAHtAzvog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Senor Sosa</a> on <a href="https://unsplash.com/search/photos/intricate-art?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Wouldn’t it be easier if we could type our procedure and not have to worry about messing up one line and having to re-type the whole thing? Sure! Let’s use a text editor (I’m going to use <a href="https://code.visualstudio.com/">Visual Studio Code</a>, but <a href="https://atom.io/">Atom by GitHub</a> is also another great option).</p><p>Let’s create a new file in our text editor called goodbye_data_hello_data.sql. Make sure that you take note of where on your computer the file is saved. This file will do three things for us:</p><ol><li>Drop the procedure if it exists: DROP PROCEDURE IF EXISTS goodbye_data_hello_data;.</li><li>Create the procedure (same procedure syntax as above without the prompts).</li><li>Call the procedure with an argument: CALL goodbye_data_hello_data(&#39;Buzz&#39;).</li></ol><p>Here’s what it will looks like altogether (with appropriate delimiter statements):</p><pre>DROP PROCEDURE IF EXISTS goodbye_data_hello_data;</pre><pre>DELIMITER //</pre><pre>CREATE PROCEDURE goodbye_data_hello_data(value CHAR(80))<br>BEGIN<br>  TRUNCATE TABLE results;<br>  INSERT INTO results (output) VALUES (value);<br>END//</pre><pre>DELIMITER ;</pre><pre>CALL goodbye_data_hello_data(&#39;Buzz&#39;);</pre><p><em>I would recommend not copying and pasting from the code snippet, just in case hidden characters used for formatting cause unforeseen headaches.</em></p><p>Cool, now we can use the source command in MySQL console back in Terminal to run the file. Most IDEs have the option to copy the absolute path to the file, use that if you have it and run this command:</p><pre>source &lt;path_to_file&gt;</pre><pre>/* For example */</pre><pre>source /Users/jude/working/fizz_buzz/goodbye_data_hello_data.sql</pre><p><em>Don’t forget the file extension </em><em>.sql or it won’t work.</em></p><p>We can now create a new file and easily alter our method using this new source file concept, instead of potentially messing up a pretty long run of SQL in the MySQL console.</p><h4>Step 6: Inserting Numbers via Loops</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2oKgoo2hjt1r6AIIuBT0Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/u2d0BPZFXOY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tine Ivanič</a> on <a href="https://unsplash.com/search/photos/loop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>First, set up the source file similar to the one above (create a new file called fizz_buzz.sql), leaving out the code in CREATE PROCEDURE block — like so:</p><pre>DROP PROCEDURE IF EXISTS fizz_buzz;</pre><pre>DELIMITER //</pre><pre>CREATE PROCEDURE fizz_buzz(max INT UNSIGNED)<br>  /* Code will go here */<br>END//</pre><pre>DELIMITER ;</pre><pre>CALL fizz_buzz(15);</pre><p>Let’s go ahead and make this procedure do one thing and progressively enhance it from there. Let’s make the procedure add all of the ‘numbers’ (don’t forget, they’re actually CHARs) from the range created by the given max value argument. We will need to use a loop to do this, otherwise we cannot know how many INSERT INTO statements we need. WHILE syntax in SQL generally looks like this:</p><pre>WHILE &lt;condition&gt; DO<br>  /* code to execute */<br>END WHILE;</pre><p>Sound good? In the case below we add all numbers between 1 and 30:</p><pre>DROP PROCEDURE IF EXISTS fizz_buzz;</pre><pre>DELIMITER //</pre><pre>CREATE PROCEDURE fizz_buzz(max INT UNSIGNED)<br>BEGIN  <br>  DECLARE counter INT UNSIGNED DEFAULT 1;<br>  TRUNCATE TABLE results;<br>  WHILE counter &lt;= max DO<br>    INSERT INTO results (output) VALUES (counter);<br>    SET counter = counter + 1;<br>  END WHILE;<br>END //</pre><pre>DELIMITER ;</pre><pre>CALL fizz_buzz(30);</pre><p>That’s a lot. Let’s unpack this.</p><ul><li>Lines 1–6 look familiar the only change was the addition of the max argument as a positive integer instead of value.</li><li>DECLARE is new! It’s how we declare local variables in a procedure. It takes a data type(s) and a default value which we set as one as the beginning of our range. <em>Local variables have to be declared at the top of the procedure before anything else.</em></li><li>Our WHILE loop begins, and we insert the value of counter and add one to counter (using SET) and repeat until counter equals max.</li></ul><p>The result of SELECT * FROM results; should now be two columns of the numbers 1–30 for both id and output.</p><p>Did this work for you? Great 😁, you can move on to the next step! Nope? Comment and let me know 😃.</p><h4>Step 7: FizzBuzz: Branch Logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DciL2Ojb3wvnh0OP6b-a_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/u0vgcIOQG08?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jens Lelie</a> on <a href="https://unsplash.com/search/photos/forked--path?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You’ve made it. We’re ready to insert our FizzBuzz branch logic and complete this challenge. Using the same source file you created for the section above, let’s add branch logic to our loop. Branch logic syntax in SQL generally looks like this:</p><pre>IF &lt;condition&gt; THEN<br>  /* Code Here */<br>ELSEIF &lt;condition&gt; THEN<br>  /* Code Here */<br>ELSE<br>  /* Code Here */<br>END IF</pre><p>Sound good? Let’s finish this challenge:</p><p>We need to add branch logic for FizzBuzz to our while loop so that what’s inserted is correct based on the values divisibility, and we need to do this for all numbers in the range we are given. As a brief reminder of the rules:</p><ul><li>If the number is divisible by 3, print out ‘Fizz’.</li><li>If the number is divisible by 5, print out ‘Buzz’.</li><li>If the number is divisible by 3 <em>and </em>5, print out ‘FizzBuzz’.</li><li>Finally, if the number is not divisible by 3 or 5, print out the number.</li></ul><p>Here’s what it would look like:</p><pre>DROP PROCEDURE IF EXISTS fizz_buzz;</pre><pre>DELIMITER //</pre><pre>CREATE PROCEDURE fizz_buzz(max INT UNSIGNED)<br>BEGIN  <br>  DECLARE counter INT UNSIGNED DEFAULT 1;<br>  TRUNCATE TABLE results;<br>  WHILE counter &lt;= max DO<br>    IF (counter % 3) = 0 AND (counter % 5) = 0 THEN<br>      INSERT INTO results (output) VALUES (&#39;FizzBuzz&#39;);<br>    ELSEIF (counter % 3) = 0 THEN<br>      INSERT INTO results (output) VALUES (&#39;Fizz&#39;);<br>    ELSEIF (counter % 5) = 0 THEN<br>      INSERT INTO results (output) VALUES (&#39;Buzz&#39;);<br>    ELSE<br>      INSERT INTO results (output) VALUES (counter);<br>    END IF;<br>    <br>    SET counter = counter + 1;<br>  END WHILE;<br>END//</pre><pre>DELIMITER ;</pre><p>I’ve left the CALL statement off because we can call it directly after we call our source file to create the procedure, let’s create the procedure now:</p><pre>source /Users/jude/working/fizz_buzz/fizz_buzz.sql</pre><p>Finally, let’s call the procedure (use whatever upper range you want, I will use 30) and then check the results table:</p><pre>mysql&gt; CALL fizz_buzz(30);<br>...<br>mysql&gt; SELECT * FROM results;</pre><p>Your results (if you used 30) should look something like this:</p><pre>+----+----------+</pre><pre>| id | output   |</pre><pre>+----+----------+</pre><pre>|  1 | 1        |</pre><pre>|  2 | 2        |</pre><pre>|  3 | Fizz     |</pre><pre>|  4 | 4        |</pre><pre>|  5 | Buzz     |</pre><pre>|  6 | Fizz     |</pre><pre>|  7 | 7        |</pre><pre>|  8 | 8        |</pre><pre>|  9 | Fizz     |</pre><pre>| 10 | Buzz     |</pre><pre>| 11 | 11       |</pre><pre>| 12 | Fizz     |</pre><pre>| 13 | 13       |</pre><pre>| 14 | 14       |</pre><pre>| 15 | FizzBuzz |</pre><pre>| 16 | 16       |</pre><pre>| 17 | 17       |</pre><pre>| 18 | Fizz     |</pre><pre>| 19 | 19       |</pre><pre>| 20 | Buzz     |</pre><pre>| 21 | Fizz     |</pre><pre>| 22 | 22       |</pre><pre>| 23 | 23       |</pre><pre>| 24 | Fizz     |</pre><pre>| 25 | Buzz     |</pre><pre>| 26 | 26       |</pre><pre>| 27 | Fizz     |</pre><pre>| 28 | 28       |</pre><pre>| 29 | 29       |</pre><pre>| 30 | FizzBuzz |</pre><pre>+----+----------+</pre><p>Hooray! You did it 🎉 This has been a bit of a marathon, so if you have any questions or comments please feel free to leave a comment below. Happy coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqWlZo6dhUt83fcKvi8SSg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/rkjsSXImi2A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lawrence Walters</a> on <a href="https://unsplash.com/search/photos/path-sunlight?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a097f7ca337b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s Gonna Be Okay: My Intro to MySQL]]></title>
            <link>https://medium.com/@judedutton/its-gonna-be-okay-my-intro-to-mysql-1677c3f4901f?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1677c3f4901f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-development]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 16:05:14 GMT</pubDate>
            <atom:updated>2018-10-16T16:05:14.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUif8A5X81bOpkLssOTbcg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1ZZ96uESRJQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shane Rounce</a> on <a href="https://unsplash.com/search/photos/network?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you’re a backend software engineer you remember your first database engine. Mine was PostgreSQL and after <a href="https://turing.io/">7 months at an immersive coding school</a> utilizing mainly PostgreSQL I was reluctant to expand to other engines for my projects.</p><p>MySQL is widely used and is a beneficial tool for any software engineer seriously into designing their own database systems. It is important to me to always continue learning, so I decided to dive right in.</p><p>Like most new toolsets, I initially started by reading through <a href="https://dev.mysql.com/doc/">MySQL’s documentation</a> and skimming <a href="https://dev.mysql.com/doc/refman/8.0/en/tutorial.html">the top-level tutorial</a> to check and see if I could cognitively plan my direction to self-onboard the new toolset. As it so often is with new software I needed to decide how I was going to install and configure MySQL. What follows are the steps I took for installing and initially configuring MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfD23UF6TP22htpIdMS-WQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/NL_DF0Klepc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Cesar Carlevarino Aragon</a> on <a href="https://unsplash.com/search/photos/tool?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I started by downloading MySQL Community Server, this would be the core interface that I would be interacting with in Terminal. Whenever I need to install a toolset my first step is always to check <a href="https://brew.sh/">Hombrew</a> to see if they offer an installation formula for the process. They certainly do, so let’s first install MySQL via Homebrew:</p><blockquote>Note: If you do not have Homebrew installed, please <a href="https://brew.sh/">go here</a> and follow the latest instructions available to install my favorite package manager of macOS. If you have Homebrew installed, you can get the latest version by running brew update. You can check your installed version of Hombrew by running brew -v.</blockquote><p>Once you have Homebrew installed, run the following command to install the latest version of MySQL available from Homebrew:</p><pre>brew install mysql</pre><h4>Quick Side Note: Why Use Homebrew?</h4><p>In brief, I highly recommend utilizing Homebrew for installing all software tools whenever needed because this provides a level of consistency when acquiring new software. It provides an automated and standard approach to installing and updating the tools that you need. It’s a package manager at its finest and will save you a lot of headaches dealing with installation details. You’ve got enough to worry about 😉</p><h4>Getting up and running in Terminal</h4><p>Some developers are fans of applications that provide graphic user interfaces for interacting with database servers like PostgreSQL or MySQL; however, I will be focusing on how to get up and running with macOS’s built-in terminal. I prefer to interact with my database engine as closely as possible, so that is what we will do.</p><p>I’m going to toss out a ‘gotcha’ to all thepsql fans out there, let’s try starting the MySQL console by running mysql…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETLepv92oLQkqzYd0ypF5w.png" /></figure><p>Uh-oh. If you’re seeing something like this, then MySQL <em>is</em> working correctly. Upon closer inspection it appears that the issue is a matter of access. Just running mysql will try to start the MySQL Console with a default user, but that user needs a password. But how do you create a password for a user account you cannot access?</p><h3>Creating a User</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6sEQiUjGfgIUt1x-Hq68g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/SSAbwzqz2Kc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/lock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We will want to create a user that:</p><ol><li>Has the privileges of an admin.</li><li>Is password protected because, well, see point 1.</li></ol><p>We will leverage the default root admin user to create and alter the default user account. We will also password protect the root user while we are here, otherwise anyone with terminal access to the MySQL console can alter your databases. Here’s how:</p><p>First we will need to open the console as the root user:</p><pre>$&gt; mysql -u root</pre><p>If you’re prompted for a password, just press return — there should not be a password yet. Once you have access to the console via the root user, I would recommend setting a password using the statement below:</p><pre>mysql&gt; ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;yOuRp@sswordHERE!&#39;</pre><p>Once you have done this, use the same statement to add a password to your default account. Your default account name is most likely your user account name for your computer. If you don’t know — refer to the error that occurred after running mysql earlier. Here’s an example:</p><pre>mysql&gt; ALTER USER &#39;jude&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;thisisnotarealpassword&#39;</pre><blockquote>For more information on altering the root/other user accounts, <a href="https://dev.mysql.com/doc/refman/8.0/en/default-privileges.html">check out the docu</a>.</blockquote><p>Finally, while we are here, let’s give our default user account the ability to have admin privileges (make sure to replace <em>jude </em>with your user account name):</p><pre>mysql&gt; GRANT ALL ON *.* TO &#39;jude&#39;@&#39;localhost&#39;;</pre><p>You can then check that this has worked by showing all of the grants for your default user:</p><pre>mysql&gt; SHOW GRANTS FOR &#39;jude&#39;@&#39;localhost&#39;;</pre><p>We should be all done with the root user now. Let’s quit the console and re-enter it as our new default user for the next section 🎉</p><pre>mysql&gt; \q</pre><pre>$&gt; mysql -u jude -p<br>Enter your password: *</pre><h3>Some Basic Operations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vS7DRyeH2oILr3X76gnjMA.jpeg" /></figure><p>There are a handful of high-level operations that you will want to do immediately. Let’s try creating a new database and a table to test out our configuration. Make sure you are logged in to your account and then use the command below to make a database for a grocery list app:</p><pre>mysql&gt; CREATE DATABASE grocery_list;</pre><p>And then connect to this database:</p><pre>mysql&gt; USE grocery_list; </pre><p>And finally let’s make a table:</p><pre>mysql&gt; CREATE TABLE groceries (<br>    -&gt; name VARCHAR(80)<br>    -&gt; category VARCHAR(20)<br>    -&gt; quantity INT);</pre><p>At any point, you can check which databases you have created as well as what tables have been created using the commands below:</p><pre>mysql&gt; SHOW DATABASES;<br>...<br>mysql&gt; SHOW TABLES;</pre><p>If all goes well, then your user should be configured and good to go! Here are some documentation resources that I used when doing this myself for the first time:</p><ul><li><a href="https://dev.mysql.com/doc/refman/8.0/en/default-privileges.html">Altering the Root and default users and adding passwords</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/creating-database.html">Creating a database</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/creating-tables.html">Creating a table</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/tutorial.html">Introductory tutorial</a></li></ul><p>This has been a lot of information, and I can only imagine that it’s easier blogged than done, so let’s leave this here. Stay tuned for Part 2, ‘Inserting Data and MySQL Data Types’ and Part 3 ‘Stored Procedures and Stored Functions’ — coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1677c3f4901f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Rubyist’s First Impression of TypeScript]]></title>
            <link>https://medium.com/@judedutton/a-rubyists-first-impression-of-typescript-214a75d2805d?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/214a75d2805d</guid>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 15:49:10 GMT</pubDate>
            <atom:updated>2018-10-10T15:49:10.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u15mPeqqjktZAm1oQ7eFlg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/VfZOC3kV6sM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/typewriter-red?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Contrary to the title, my first love was JavaScript and/or Python, it’s really unclear, but let’s say JavaScript. My job prior to software engineering was in Customer Success and in my project times I was tasked with updating and maintaining our support site. This meant dealing with a three-file monolith inside of a multi-tenant application that served our support site. Okay, that sentence sounded grumpy, but it was actually a great experience. I had no concept of modularization or even really build processes at the time, so I was all about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SusEVm7AoKRuez04rQdLtA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/3kZpELkaxHc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/search/photos/spilled-coffee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>All of this to say that my biggest challenge was dealing with JavaScript. As I was developing our single script file for this support site I was running into progressively more difficult hurdles that I only identified as normal coding challenges for a newbie like me. While the newbie status was real, my actual nameless obstacles were type coercion and variable scope. I confirmed this later during my time in <a href="https://turing.io/">an immersive coding school</a>.</p><p>Fast forward about a year and I am now a Rubyist/JavaScripter web engineer learning new things everyday. My latest adventure takes me into the realm of <a href="https://www.typescriptlang.org/">TypeScript</a>. What attracted me to this particular superset of JavaScript was the concept of type annotations. If your familiar only with dynamically typed languages like Ruby or JavaScript, type annotations may not mean anything to you. In essence TypeScript‘s type annotations give you the ability to define what data type a variable or a function argument should be, as well as allowing you to define the return value of a something like a function or method. It also includes support for <a href="https://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers">defining public methods explicitly</a>, <a href="https://www.typescriptlang.org/docs/handbook/jsx.html">namespacing for JSX</a>, and <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">so much more</a>.</p><p>What does this do for us? By defining types explicitly, and not relying solely on type coercion to make your choices, you take control back from the dark corners and edges of your application’s runtime, and illuminate exactly what should be going on. While I agree that type coercion is handy, defining your data types is far more stable.</p><p>Coming from Ruby where a lot of the magic is abstracted away in a powerful suite of methods built over two decades, writing JavaScript naturally makes me want to build my own library of these methods. (Side Note: Everyone who is screaming internally about there being another JS toolset out there in the world, no worries — it’s not real…Yet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*494Zt3R4wuX6jGEE93bGyg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/HH4WBGNyltc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jaredd Craig</a> on <a href="https://unsplash.com/search/photos/books?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I was uncomfortable undertaking this task in JavaScript because of the amount of potential issues that different inputs into such methods could cause. In reality, writing JavaScript takes a lot of mental gymnastics to make sure that the types of inputs that you are taking in will produce the output you want. Preemptively protecting against type coercion edge/corner cases can be an extremely difficult task. There’s nothing wrong with that, but the potential of building with TypeScript where types are declared seems to be a more certain path forward.</p><p>My first real experience with TS was going through a <a href="https://mherman.org/blog/developing-a-restful-api-with-node-and-typescript/">blog about building an API using Express and TypeScript.</a> Though it takes more effort to code with TypeScript, I have to admit that I found the process even more enjoyable than building Express-based APIs with vanilla JS!</p><p>All in all, TypeScript is great so far. The configuration is straightforward, and not too daunting even to someone who’s used to setting up files with a single robust CLI command (see rails new). If you are curious about TypeScript, as a documentation purist I would recommend first checking out <a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html">TypeScript in 5 Minutes</a> and then perusing <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html">the official handbook</a> as needed.</p><p>Best to all of you who venture into the realm of ECMAScript and its auxiliaries. It’s exciting, scary, and exhausting all at the same time, but what great adventure ever wasn’t? 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214a75d2805d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contributing to Open Source]]></title>
            <link>https://medium.com/@judedutton/contributing-to-open-source-400c7be3b626?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/400c7be3b626</guid>
            <category><![CDATA[turing-school]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Sat, 01 Sep 2018 21:19:58 GMT</pubDate>
            <atom:updated>2018-09-01T21:19:58.372Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: It’s important to me that I do not false advertise or misrepresent an organization’s values, so for the entirety of this blog I will refer to the organization that I worked with as the “Awesome People”.</em></p><p>I’m new to software engineering; however, the career path has already turned into one of those terminal-express-lateral escalator contraptions that we all wanted to sprint down as kids. So, after a year or two of getting my feet wet with JavaScript, and <a href="https://turing.io/">7 months of intensive training</a> with Ruby/Rails, NodeJS/Express, and Elixir/Phoenix I’m happily in a place where I can confidently call myself a software engineer.</p><p>One important aspect was missing though: contributing to open source. I’ve heard of this as a trendy thing to do; however, I wasn’t sure what the real value or appeal was. It just so happens that we had a project coming up towards the end of my time studying at Turing that necessitated we do just that.</p><p>I had found some companies that I figured would invite open source contributions, but it wasn’t until I found the Awesome People that I really felt comfortable reaching out and contributing. It was the detail with which the Awesome People provided material for their contributors and their assertion that they moderated pull requests and contributors with feedback and care.</p><p>The issue in question affected almost every page in one of the major sub-sections of their app, but it was a small change to some CSS. That being said, the real benefit for me was not in the fix, but in the surmounting of different obstacles all along the way:</p><ul><li>A dependency was preventing the development application server from working.</li><li>The actual files were on a sub-repo to the main app, which was my mistake for not noticing.</li><li>The issue itself was not a problem in development, but was an issue in production.</li></ul><p>When deciding how to handle the dependency issue, it was important to me to not just updated everything to its latest version as I was unaware of what versioning dependencies were necessary. So it took me a couple of tries, but I was eventually able to overcome the issue by specifically installing only the minor version update that I needed.</p><p>The files that were actually causing the styling issue were actually outside of the main app repository, so I had to make sure I went and cloned the right repo. This only occurred to me after I had been searching for awhile 😅. In my mind this exemplifies the experience of becoming familiar with open source software that you are just getting to know!</p><p>Finally, once I got the development environment all setup, it turns out that the mis-render was, well, <em>not</em> mis-rendering in development which was a challenge. As I investigated possible solutions, I had to make sure that my changes also worked in production since I could not trust the results in development for this particular issue. This was accomplished with a combination of trial and error utilizing browser inspectors and such tools.</p><p>Once that was all said and done, it was smooth sailing. Tests passed, everything looked green across browsers, and I was ready to submit my PR. I am thoroughly grateful to the Awesome People for providing such a wonderful first experience contributing to open source software, no matter how small the fix actually was. I highly recommend getting into open source contributions — it was some of the most rewarding coding I’ve done in a long time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=400c7be3b626" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Code (Part 1): Where do I even start?]]></title>
            <link>https://medium.com/@judedutton/designing-code-part-1-where-do-i-even-start-d5fb3e448247?source=rss-320bc87a8a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5fb3e448247</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jude Dutton]]></dc:creator>
            <pubDate>Wed, 06 Jun 2018 22:15:26 GMT</pubDate>
            <atom:updated>2018-06-06T22:18:49.179Z</atom:updated>
            <content:encoded><![CDATA[<p>The most difficult part about writing code is getting started.</p><p>As a “good” software engineer I was all for starting with Test (or Behavior) Driven Development and dive right into building out my feature set using RSpec and some serious will to get the thing done. However, as with all things that seem exciting and compelling, the thing was easier said then done. Inevitably I was stuck at a point of impasse; where was I supposed to even start?</p><p>So I dug into my brand new knowledge about the MVC (Model, View, Controller) web architecture and guessed, “Okay, I’ll start with the View”. Well that turned out to be a tangled mess, the abyss of controller actions and models yawned ahead of my feature tests and I wanted to sit down and give up.</p><p>Well, it turns out I knew right where to start all along — I just needed to know the problem I needed to solve (which I hadn’t even thought to consider) and then start with the smallest cog in the machine. By identifying first the big picture and quite literally pencil-sketching it (okay, it was actually pen) and then identifying the most integral cog in the machine I could map my path forward, and take one step after toward my end goal.</p><p>Alright, so what are we actually going to do? I thought, arbitrarily so, it would be fun to build a really simple CRUD app designed for something that doesn’t quite exist yet — interplanetary trade. The point of this blog post (and possible subsequent posts) is not to be a tutorial for this app, but to highlight how you can design your code by understanding the expectation for a small piece of functionality first and then write the code to meet it. In doing so, we then realize how we can design our code and in a way build a map for ourselves to follow.</p><p>Okay, so I will use Ruby on Rails and RSpec for the rest of this time (along with the Capybara and Launchy gems for testing); however, I will not go into the details of the RSpec testing framework. I’m also going to assume working knowledge of Rails and hopefully can come back to this and link to a introductory Rails tutorial! I would recommend getting familiar with how RSpec works in Rails (and how to configure it) before continuing, or just following along and learning by seeing what works and what doesn’t!</p><p>So, where do we actually start. Well, I would first like to see how our app is supposed to work. This is the big picture, the overall (but not permanent) scaffold into which we will build our app. Here is the general idea:</p><ul><li>The app will keep track of the planets that are part of this interplanetary economy and allow users to view the resources that each planet sells.</li><li>We will also be keeping track of the spaceports for each planet</li></ul><p>Let’s just start there. Applications can get really complicated really quickly, so let’s keep things simple! Here are what the relationships will be like:</p><ul><li>A planet will have_many spaceports.</li><li>A spaceport will belong_to a planet.</li><li>A planet will have_many resources.</li><li>A resource can also be have_many planets.</li></ul><p>We’ve already got four data relationships here, and a many-to-many relationship (between planets and resources) which will require a joins table so a total of five database tables. Let’s just build out the very first relationship planets to spaceports.</p><p>I hope that, as a beginner student of software engineering you are feeling a little lost at this point, because that is exactly the sentiment that I was trying to deal with when tackling this problem. Let’s see how to start.</p><p>First, let’s make a Rails app — this article assumes you have Rails installed.</p><p>Go ahead and run the following command in a new directory in your terminal (wherever you keep projects) to get started:</p><pre>rails new interplanetary_economy -T -d=postgresql --skip-turbolinks --skip-spring</pre><p>This should generate a new folder that holds your entire Rails application called interplanetary_economoy.</p><p>And that’s it! No. Just kidding, that’s not it at all. Here we go:</p><p>When thinking about building any application, there is a choice to be made of starting from the bottom (the smallest component) and working your way up, or by starting from the feature itself, the user’s interaction, and working your way down.</p><p>I prefer and will utilize the former method. This will not only help us define the steps that we need to take, it will help us avoid over-implementation. In other words, we won’t build anything more than what we need!</p><p>In my mind, I would like to start with the simplest piece of the puzzle, the Planet model. We will start with a model test.</p><p><em>Side note: As Rails is highly dependent on convention, pay attention to things like, what’s capitalized, what’s pluralized, etc.</em></p><p>What do model tests do for us? They define or in other words, design, our models for us. By setting these expectations, we can fail them and then build out the minimum amount of functionality needed to meet those expectations. This harkens to a common Test Driven Development paradigm often referred to as Red-Green-Refactor, meaning that we will write our tests first, watch them fail (Red), implement what we need to get them to pass (Green), and then later we can clean up and optimize our code (Refactor), making sure we are back to Green when all is said and done.</p><p>Here is an example of my model test for my Planet model:</p><pre><a href="https://github.com/jude-lawson/interplanetary_economy/blob/1aa571ca0977282729b5e564109111fc26b11d69/spec/models/planet_spec.rb#L1-L7">https://github.com/jude-lawson/interplanetary_economy/blob/1aa571ca0977282729b5e564109111fc26b11d69/spec/models/planet_spec.rb#L1-L7</a></pre><p>After running this test (run rspec in your Terminal to run tests), you should see an error like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*US1HNPFEVtaSFlzEQJ1QZw.png" /></figure><p>It’s an error, but it’s totally what we need — it tells us what to do next and now we know where to start! We need to make our database. Rails gives us some Rake commands that allow us to create databases (which Rails has already kindly configured for us in config/database.yml ) so we can just run rake db:create to create our database.</p><p>After successfully creating the database, let’s run rspec again and receive the error below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Fuf9e2z1_HA7jmLia5eSQg.png" /></figure><p>Our test is trying to test that our Planet model is only valid if a name is present; however, it can’t even find the Planet model yet. Given this error we know we have to create the model. Here’s an example of how I would create the model including the validation:</p><pre><a href="https://github.com/jude-lawson/interplanetary_economy/blob/6314f9b9faa6c57707d5c037b3423f4352f848ee/app/models/planet.rb#L1-L3">https://github.com/jude-lawson/interplanetary_economy/blob/6314f9b9faa6c57707d5c037b3423f4352f848ee/app/models/planet.rb#L1-L3</a></pre><p>Let’s run our tests once more for this article, and see what error we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*t-UlVeQZ75DmoRP-gd5pzA.png" /></figure><p>This big, scary-looking error is really just saying, “Hey, looks like you need a table called ‘Planets’ in your database…”. To which I would respond, “Thanks for telling me exactly the next step to take!” and then write a migration to create the database. Rails again has a great generator for migrations so I will run the following in my Terminal:</p><pre>rails g migration CreatePlanets name:string</pre><p>…and then run rake db:migrate to add in that new table.</p><p>Okay, I know I already said that we’ve run our test for the last time, but let’s run rspec one <em>final</em> time…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*kCoR9j6bAYh845xG6F9v-w.png" /></figure><p>…and see our confirmed, successful, wonderful, tiny, singularly responsible, &lt;enter whatever fun adjectives you wish&gt;, piece of functionality. We’ve effectively created the very first cog in our soon to be complex machine and have gathered momentum to continue with the next cog and the next cog and the next…</p><h3>Review</h3><p>So, what’s the point? As a Rails developer you could possibly be thinking to yourself that it’s wonderful that you’ve created this super tiny piece of functionality, but why is that good or important at all?</p><p>Here’s why:</p><ul><li>The assumption of this post is that you are a software engineer, working at building a web application, and wondering where in the myriad of entry points to start? This method of starting small, testing first, meeting expectations, is <em>one</em> concise way of designing your code that I find to be manageable and scalable as you move forward.</li></ul><p>To abstract the process, here’s what we did:</p><ul><li>Identified the big picture. White-boarding or sketching is my recommended method.</li><li>Distilled the functionality down to the smallest possible components.</li><li>Wrote a test to design that piece of functionality.</li><li>Wrote the code to meet that expectation.</li></ul><p>This is just the beginning we’ve made one simple part of the whole app; however, <em>we actually built something</em> and that’s the best way to get momentum — one step at a time.</p><h3>What’s up next?</h3><p>Looking forward to writing Part 2 about the cycling through building the individual pieces that make up the most basic features in a Rails app using the method above. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5fb3e448247" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>