<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: kevhines</title>
    <description>The latest articles on Forem by kevhines (@kevhines).</description>
    <link>https://forem.com/kevhines</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F560667%2F2d7308ce-de66-4fca-9a3f-cf0b535b89a0.png</url>
      <title>Forem: kevhines</title>
      <link>https://forem.com/kevhines</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kevhines"/>
    <language>en</language>
    <item>
      <title>Background: Updating a Dice Rolling App</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Tue, 19 Oct 2021 19:49:17 +0000</pubDate>
      <link>https://forem.com/kevhines/background-updating-a-dice-rolling-app-2ii6</link>
      <guid>https://forem.com/kevhines/background-updating-a-dice-rolling-app-2ii6</guid>
      <description>&lt;p&gt;One of my favorite parts of coding is getting to dig into existing code. Adding functionality. Debugging. Really getting to figure out how a piece of code works. It's been a while since I have done that but recently I got a chance to flex that muscle.&lt;/p&gt;

&lt;p&gt;No code in this post, this is just about the project. It's a small one but this will explain what I had to do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background: Role Playing Games and Dice
&lt;/h2&gt;

&lt;p&gt;My friends and I casually play different role playing games over slack. If you haven't played role playing games it's kind of like playing pretend, you create a character with certain skills and you interact in a world and with other players to explore that world. Often there are times when you need to bring luck into play (are you able to defeat someone in battle, hack into a computer, recognize a dialect) and when that happens you roll dice.&lt;/p&gt;

&lt;h2&gt;
  
  
  More Background: Rolling
&lt;/h2&gt;

&lt;p&gt;Slack has a nice app for rolling dice that you can use. You type /roll to start the slash command and then list out the specific dice you want to roll.&lt;/p&gt;

&lt;p&gt;So like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZT3U6cCK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gz9v4vq4znrhg1p4ljhi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZT3U6cCK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gz9v4vq4znrhg1p4ljhi.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This works great. But my friends and I play games that use dice a little differently. So when we started needing dice to roll differently a friend of mine built a custom dice rolling app for Slack to do the job. For example this code rolls percentiles where you can ask it to roll an extra die for a bonus. The bonus die replaces the tens place if it's lower helping you get a low roll. Like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--no7dhTA8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slh4yku20ytj4zi1rh96.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--no7dhTA8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slh4yku20ytj4zi1rh96.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a custom app so we aren't using the built in /roll slash command but our own /r slash command. The c signifies that it's using the percentiles roll for this different game. The b signifies roll a bonus die. You can also roll a penalty die with a p. And this app also rolls normal dice like the built in app so we don't need to go back and forth between applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background: a new game
&lt;/h2&gt;

&lt;p&gt;So we started playing a new game. In this game the dice exploded. That means if you rolled a max value, you had to roll the die again and the total was what you rolled. So if you roll a 6 on a 6 sided die you can roll again and if you get a 3 that time your actual roll was a 9. The built in roll app can do this, so we considered going back to that built in app. But after a little playing we realized it doesn't handle multiple rolls the way we wanted it to.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--31Npr3FK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5dbsom4mbi5l82ibx9mv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--31Npr3FK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5dbsom4mbi5l82ibx9mv.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So it rolls both dice, and explodes them nicely BUT it gives you a total of both dice when we frequently found we wanted two separate subtotals.&lt;/p&gt;

&lt;p&gt;So it was decided we should update our custom app. My friend who wrote the code didn't have time to update it but offered to share the javascript code with me so I could update it. In my next post I'll step through how I attacked this fun job.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Algorithms: Spotting Resource Hogs</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Sat, 21 Aug 2021 19:22:13 +0000</pubDate>
      <link>https://forem.com/kevhines/algorithms-spotting-resource-hogs-156a</link>
      <guid>https://forem.com/kevhines/algorithms-spotting-resource-hogs-156a</guid>
      <description>&lt;p&gt;When looking for a tech job you are probably spending some time practicing writing algorithms (on LeetCode or HackerRank or some site like that). &lt;/p&gt;

&lt;p&gt;Writing a good algorithm often comes down to two parts.&lt;br&gt;
1) writing the code (this one is obvious)&lt;br&gt;
2) being aware of it's order of complexity (less obvious)&lt;/p&gt;

&lt;p&gt;In an ideal world you'll write code that's quick, doesn't use a lot of resources, and solves the problem. But these problems you are attempting to solve are tricky. Sometimes that solution has lots of edge cases you need to take into account. And sometimes these problems lend themselves to solutions that eat up resources and are complex. Maybe O(n^2) or O(n^3) or even O(2^n) - for more on what those O's mean, read &lt;a href="https://stackoverflow.com/questions/20688720/what-is-order-of-complexity-in-big-o-notation"&gt;the answers to this stack overflow question.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I just want to talk, very quickly about being aware before you even start the problem that it is going to lead to a large order of complexity.&lt;/p&gt;
&lt;h2&gt;
  
  
  Fibonacci
&lt;/h2&gt;

&lt;p&gt;The classic example of a problem that leads to a very high complexity solution is a function that takes a number and returns the Fibonacci number that you get in that position. &lt;/p&gt;

&lt;p&gt;The Fibonacci Sequence is a sequence of numbers that equals the total of the previous two numbers in the sequence, with the sequence beginning with 0,1. So F(2) is F(0) + F(1) which equals 1.  Then F(3) = F(2) + (F1) which equals 1 as well. But after that is starts expanding. The early part of that sequence is 0,1,1,2,3,5,8...&lt;/p&gt;

&lt;p&gt;Here is a simple looking recursive function that determines the fibonacci number at the place in the sequence that is provided:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function fib(n) {
    if ( n === 0 || n === 1) {
        return n
    } else {
        return fib(n-1) + fib(n - 2)
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a solution you might come up with if you aren't worried about complexity. But the complexity of this solution is O(2^n). That is an &lt;strong&gt;exponential time&lt;/strong&gt; which is way too complex. Large numbers will become untenable for this function. &lt;/p&gt;

&lt;p&gt;Take a look at that function. Every time you call it, it COULD call the function twice more. That's a signal that it could get out of control really fast. So you should begin thinking about a better solution. One that is not as short and neat, but will avoid the terrible run time this function creates.&lt;/p&gt;

&lt;p&gt;Ideally you don't want your function to be called more than once for every element it checks. In this case, if I send a 10 in, I don't want the function run more than 10 times. (in this case it will run over 100 times!). So you need to start thinking of a better solution.&lt;/p&gt;

&lt;p&gt;This blog entry is not about a better solution, but if you are curious about seeing a better way to solve this problem I'd recommend &lt;a href="https://www.youtube.com/watch?v=jCh7majQGdg&amp;amp;ab_channel=SWE%2B%2B"&gt;this video.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Searching for Anagrams
&lt;/h2&gt;

&lt;p&gt;So the other day I was practicing algorithms on LeetCode and I had a problem that asked me to &lt;em&gt;accept a string, and return the longest palindromic substring within it&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;My first thought was this pseudo code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Accept a string s of n characters
//check if s[0] is an anagram
//Then check if s[0] + s[1] is an anagram
//continue checking until s[0]+s[1]+...s[n]
//then check s[1] and follow the same track until I check:
//s[1]+s[2]+...s[n]
//keep doing that until I check s[n]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's a surefire way to be certain I check every possible substring of s. But my memory of that Fibonacci problem started getting triggered. For a string of length n I need to check n different substrings, plus n-1 substrings, plus n-2 substrings.... uh oh. That starting to sound real bad. If you have to run through an array (or a string in this case) more than once for every element (or character) you are getting to a bad place. &lt;/p&gt;

&lt;p&gt;Turns out that solution is O(n^3) which isn't as bad as my bad fibonacci solution but it isn't great. (a string of 10 characters would loop through 55 times. A string of 11 would run 66 times. etc) &lt;/p&gt;

&lt;p&gt;So right away, if you want to solve this problem, you should be aware that you are heading towards a high complexity.&lt;/p&gt;

&lt;p&gt;If you are doing this in an interview, you might just want to give the answer you can think of. I would! But if you are aware of that complexity you can speak to that. Maybe you can solve it a better way once you get this inefficient way written out. Maybe you can't - but for some interviewers seeing that the person they are talking is aware of the issue is a huge step forward.&lt;/p&gt;

&lt;h2&gt;
  
  
  Yeah, but what's the solution?
&lt;/h2&gt;

&lt;p&gt;Again - I wrote this blog post just to talk about the idea of identifying the problem, not solving it. I really do think identifying the problem is a huge step. The easier you can see that problem the more time you have to think of alternatives. Simply recognizing the complexity quickly shows a comprehension interviewers should value. &lt;/p&gt;

&lt;p&gt;But you want an answer. I get it. So did I. And I couldn't figure out how to solve this efficiently on my own. But after some reading I did find a solution. I'll present my version of it here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var longestPalindrome = function(s) {

    if (s.length &amp;lt;= 1) return s;
    let start = 0
    let maxLen = 0
    for (let i = 0; i &amp;lt; s.length; i++) {
      const len1 = expandSearch(s, i, i);
      const len2 = expandSearch(s, i, i + 1);
      const len = Math.max(len1, len2);
      if (len &amp;gt; maxLen) {
        start = Math.ceil(i - (len-1) / 2);
        maxLen = len
      }
    }

    return s.slice(start, start + maxLen);
  };

  function expandSearch (s, left, right) {
    let L = left,
      R = right;
    while (L &amp;gt; -1 &amp;amp;&amp;amp; R &amp;lt; s.length) {
        if (s[L] !== s[R]) break;
        L--;
        R++;
    }
    return R - L - 1;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What you are doing here, briefly, is taking a character (always a palindrome) and then checking on either side of it. If those characters are the same it's still a palindrome so keep checking on the next two characters around your starting spot. If it's not a palindrome stop checking. Then doing the same for two characters, because palindromes of even length have two characters in the center like hit Swedish pop band ABBA). You need to do this for every character. That's still O(n^2)... but that's better!&lt;/p&gt;

&lt;p&gt;An even better solution is &lt;a href="https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm"&gt;Manacher's algorithm&lt;/a&gt; which is a very complicated algorithm and not one I think you'd need to come up with on your own in an interview.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>A Second Pointer</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Fri, 13 Aug 2021 21:10:57 +0000</pubDate>
      <link>https://forem.com/kevhines/a-second-pointer-2di6</link>
      <guid>https://forem.com/kevhines/a-second-pointer-2di6</guid>
      <description>&lt;p&gt;A quick little post about using a second pointer when optimizing algorithms. &lt;/p&gt;

&lt;h2&gt;
  
  
  Unoptimized
&lt;/h2&gt;

&lt;p&gt;Take a look at this function that takes an array of numbers and then returns an array of those numbers squared and sorted from smallest to largest.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function squared(array) {
    let result = []
  for (let value of array) {
    result.push(value * value)
  }


  return result.sort((a,b) =&amp;gt; a - b)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function works but it's &lt;a href="https://adrianmejia.com/most-popular-algorithms-time-complexity-every-programmer-should-know-free-online-tutorial-course/"&gt;Time Complexity&lt;/a&gt; isn't that great.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;For loop&lt;/em&gt; runs once for every element in the array so that's &lt;strong&gt;O(n)&lt;/strong&gt; - a pretty fair time complexity. But then I have to run a sort, and many sort's generally time out around &lt;strong&gt;O(nlog(n))&lt;/strong&gt; - and that's basically where javascript's built-in sort method lands. That's a pretty bad result. Not much can be done about that.&lt;/p&gt;

&lt;p&gt;But what if the initial array is already sorted? Oh, now we are getting somewhere!!&lt;/p&gt;

&lt;h2&gt;
  
  
  Somewhere (i.e. Optimization!)
&lt;/h2&gt;

&lt;p&gt;So if the array that is sent to my function is already sorted I don't need to run sort() at all right? Well - no. If there are negative numbers in the array I still need to do some sorting. &lt;/p&gt;

&lt;p&gt;Take this array for instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let unsorted = [-7, -3, 2, 3, 12]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will give me the result [49,9,4,9,144]. That's not sorted! So how can I sort that without running sort()? That's where using a second pointer comes in. &lt;/p&gt;

&lt;p&gt;My &lt;em&gt;for loop&lt;/em&gt; points at one spot in the array: the current element. What if I had two pointers? One for the smallest number and one for the largest. Like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function squared(array) {
  let highest_pointer = array.length - 1
  let lowest_pointer = 0
  let result = []
  while (**some logic here**) {
      // some more logic here 
  }
  return result
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So instead of a &lt;em&gt;for loop&lt;/em&gt; we have a &lt;em&gt;while loop&lt;/em&gt; and we are manually keeping track of each index. That way we are working our way from the beginning of the array and the end of the array. &lt;/p&gt;

&lt;p&gt;Keep in mind our interior logic needs to include incrementing or decrementing the appropriate index whenever it adds something to the result array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function squared(array) {
  let highest_pointer = array.length - 1
  let lowest_pointer = 0
  let result = []
  while (**some logic**) {
     if (array[lowest_pointer] ** 2 &amp;gt;= array[highest_pointer] ** 2) {
        result.push(array[lowest_pointer] ** 2)
        lowest_pointer++
     } else {
        result.push(array[highest_pointer] ** 2)
        highest_pointer-- 
     }  
  }
  return result
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what I am doing in this above example is I am checking which number is larger, the first number squared or the second one. If the array is all positive numbers it will always be the higher indexed element. But if there are negative numbers that might not be true. -7 is smaller than 3, but -7 squared is larger than 3 squared.&lt;/p&gt;

&lt;p&gt;Once I determine which number is larger I add that to the result array and then increment (or decrement) the index. &lt;/p&gt;

&lt;p&gt;Now: When does this loop end? &lt;/p&gt;

&lt;p&gt;It ends when I have checked every element of the array. Or to put it another way if the &lt;em&gt;lowest_pointer&lt;/em&gt; is pointing to a number higher than the &lt;em&gt;highest_pointer&lt;/em&gt;. Or to put it another another way and show it as a boolean comparison:&lt;br&gt;
&lt;strong&gt;lowest_pointer &amp;gt; highest_pointer&lt;/strong&gt;&lt;br&gt;
Since I am doing a while loop let's reverse that to:&lt;br&gt;
&lt;strong&gt;while (lowest_pointer &amp;lt;= highest_pointer)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's look at the code now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function squared(array) {
  let highest_pointer = array.length - 1
  let lowest_pointer = 0
  let result = []
  while (lowest_pointer &amp;lt;= highest_pointer) {
     if (array[lowest_pointer] ** 2 &amp;gt;= array[highest_pointer] ** 2) {
        result.push(array[lowest_pointer] ** 2)
        lowest_pointer++
     } else {
        result.push(array[highest_pointer] ** 2)
        highest_pointer-- 
     }  
  }
  return result.reverse()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that I had to reverse my results. Since I was putting the highest number first that means my array was built backwards. There wasn't an easy way to find the lowest number (without increasing my function's complexity) so I put the largest number first and then reversed it.&lt;/p&gt;

&lt;p&gt;I could have also added the numbers into the front of the array (using &lt;strong&gt;unshift()&lt;/strong&gt; vs &lt;strong&gt;push()&lt;/strong&gt;) but that's actually slower than running &lt;strong&gt;push()&lt;/strong&gt; and &lt;strong&gt;reverse()&lt;/strong&gt;. Reverse is simply &lt;strong&gt;O(n)&lt;/strong&gt; unlike sort. So running the &lt;em&gt;while loop&lt;/em&gt; and then reverse is O(n + n) which becomes O(n) when you ignore the constant. &lt;/p&gt;

&lt;p&gt;Read more about time complexity &lt;a href="https://adrianmejia.com/how-to-find-time-complexity-of-an-algorithm-code-big-o-notation/"&gt;here.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;When trying to optimize a function or algorithm open your mind to multiple pointers. Sometimes manually keeping track of those pointers can help you find a way to avoid some of the more complex parts of your code.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Triggering an Error Modal in React</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Mon, 07 Jun 2021 18:41:31 +0000</pubDate>
      <link>https://forem.com/kevhines/triggering-an-error-modal-in-react-3pm9</link>
      <guid>https://forem.com/kevhines/triggering-an-error-modal-in-react-3pm9</guid>
      <description>&lt;p&gt;I decided to implement a popup modal which would display error messages in my React application.&lt;/p&gt;

&lt;p&gt;I adapted some CSS from &lt;a href="https://jsfiddle.net/kumarmuthaliar/GG9Sa/1/" rel="noopener noreferrer"&gt;Kumar Mathalier's jsfiddle page&lt;/a&gt;. &lt;br&gt;
And I adapted some code for how to create a modal from &lt;a href="https://blog.bitsrc.io/build-a-simple-modal-component-with-react-16decdc111a6" rel="noopener noreferrer"&gt;Eden Ella's code on his blog&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I really dug the look of Kumar's modal, and Eden helped direct me to the idea of hiding or showing a component based on a local state. So check those pages for details on how they did those things.&lt;/p&gt;

&lt;p&gt;However, Eden's page triggered the modal by clicking a button and I needed my modal to pop up whenever I received an error in my fetch statements. So here's what I did to make this modal appear on it's own.&lt;/p&gt;

&lt;h2&gt;
  
  
  It all starts when you get an error
&lt;/h2&gt;

&lt;p&gt;When an error occurs in my Rails backend the code sends an error object {message: "some error message"}. So in my fetch statements I need to check to see if I get that object with an error message. When that happens I call an error reducer (instead of whatever reducer I'd call if there was no errors)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 fetch(url, {
        method: "POST",
        headers: {Accept: "application/json", "Content-Type": "application/json"},
        body: JSON.stringify({sentence: body})
      }).then(r =&amp;gt; r.json())
      .then(sentence =&amp;gt; {
        if (sentence.message) {
          dispatch({type: "DISPLAY_ERROR", payload: sentence})
        } else {
          dispatch({type: "ADD_SENTENCE", payload: sentence})
        }
      })


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Redux Store and The Reducer
&lt;/h2&gt;

&lt;p&gt;My reducer does two things. It either sets an error message into my state or it clears it. My state, for purposes of this blog, looks like this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

state = {
other_aspects: {},
error: "" // error message
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  The Modal
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqq5r51eenwqz4tm8hiox.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqq5r51eenwqz4tm8hiox.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Hulk's trick is that he's always angry and the Error Modal's trick is that it's always there. But it only displays when the props.show changes to true. (Hopefully you looked at the code I linked above that Eden wrote)&lt;/p&gt;

&lt;p&gt;I opted to store that Boolean in a local state instead of in props. So this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class ErrorModal extends React.Component {

    state = {
      show: false
    };
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In Eden's code he change the value of show with a button click. I want to change that value whenever an error is found (which can happen in any of my fetch calls).&lt;/p&gt;

&lt;p&gt;As I showed when my fetch finds an error it sets error in the Redux Store's state. So I made sure to map that error message to props in my Modal Component:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

  function mapStateToProps(state) {
    return {error: state.error}
  }

  export default connect(mapStateToProps)(ErrorModal)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now whenever an error shows up this component will render again. When that happens I cam change the value of my local state. So I used &lt;strong&gt;componentDidUpdate()&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

      componentDidUpdate(prevProps) {
        if (this.props.error &amp;amp;&amp;amp; !prevProps.error) {
          this.setState({
            show: true
          });
        }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This if statement is &lt;em&gt;&lt;strong&gt;very important&lt;/strong&gt;&lt;/em&gt;. This says if there is an error message in my props AND there wasn't one before set state.show to true. If I didn't have that if statement I could get caught in a recursive loop. Let's say instead of true, I wrote it like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

          this.setState({
            show: !this.state.show
          });


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This has the same result as my code. Before it was hard coded, and this is a little more elegant. It toggles it from false to true. But now think about what happens. The error message changes props which would trigger a render, and that would change the state which would trigger ANOTHER render which would change state again which would trigger ANOTHER render which would trigger ANOTHER render... and you get it.&lt;/p&gt;

&lt;p&gt;So that if statement protects me no matter how I change that setState command.&lt;/p&gt;

&lt;h2&gt;
  
  
  Clear the error message
&lt;/h2&gt;

&lt;p&gt;Ok. The modal pops up. The user is shamed about his mistake. Excellent. They click the button to close the modal. Now we need to hide this modal again. This works almost exactly like Eden's code. His onClick function was a prop and mine is local function, but the same thought process is here:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

    onClick = (e) =&amp;gt; {
        this.setState({
          show: false
        });
      };



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The Modal is no longer visible again (it's back to being mild mannered Bruce Banner if you follow my earlier subtle analogy)&lt;/p&gt;

&lt;p&gt;I also needed to remove the error message from the Redux store's state. Changing the state causes the modal to render again but it doesn't make the modal reappear because of that if statement in &lt;strong&gt;componentDidUpdate&lt;/strong&gt; (the prevProps.error is not blank). But when I get a new error prevProps.error will still NOT be blank so the modal won't appear! So I created an action that called the case in my reducer that cleared the message in my store. I called it clearError.&lt;/p&gt;

&lt;p&gt;Now I just need to call that after setting state.show to false again.&lt;/p&gt;

&lt;p&gt;Here is the final code:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;import React from "react";&lt;br&gt;
import {connect} from 'react-redux'&lt;br&gt;
import clearError from '../actions/clearError'&lt;/p&gt;

&lt;p&gt;class ErrorModal extends React.Component {&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state = {
  show: false
};


onClick = (e) =&amp;amp;gt; {
    this.setState({
      show: false
    });
    this.props.clearError()
  };

  componentDidUpdate(prevProps) {
    if (this.props.error &amp;amp;amp;&amp;amp;amp; !prevProps.error) {
      this.setState({
        show: true
      });
    }

}

render() {
    if(!this.state.show){
        return null;
    }
  return &amp;amp;lt;div className="modal" id="modal"&amp;amp;gt;
            &amp;amp;lt;div&amp;amp;gt;
                &amp;amp;lt;a href="#close" title="Close" className="close" onClick={this.onClick}&amp;amp;gt;X&amp;amp;lt;/a&amp;amp;gt;
                &amp;amp;lt;h2&amp;amp;gt;Error Message&amp;amp;lt;/h2&amp;amp;gt;
                &amp;amp;lt;p&amp;amp;gt;{this.props.error}&amp;amp;lt;/p&amp;amp;gt;
            &amp;amp;lt;/div&amp;amp;gt;
        &amp;amp;lt;/div&amp;amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;function mapStateToProps(state) {&lt;br&gt;
    return {error: state.error}&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;export default connect(mapStateToProps, {clearError})(ErrorModal)&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Props and State changes cause your page to render so managing those values can make it very easy to know when a page will hit their lifecycle methods like componentDidUpdate.&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Using LocalStorage with React</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Mon, 07 Jun 2021 15:50:41 +0000</pubDate>
      <link>https://forem.com/kevhines/using-localstorage-with-react-226m</link>
      <guid>https://forem.com/kevhines/using-localstorage-with-react-226m</guid>
      <description>&lt;p&gt;I am working on an application that uses React and Redux and I wanted to add a login page but I didn't have time initially to create a fully secure frontend login. So, as a placeholder I used &lt;strong&gt;localStorage&lt;/strong&gt; to keep track of who was logged in. Let me show you how I did it.&lt;/p&gt;

&lt;h2&gt;
  
  
  First: Look at your REDUX Store
&lt;/h2&gt;

&lt;p&gt;After someone logs into my site I add the user to my Redux Store:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...state
user: { id: //user's ID from the database
        username: //name the user chose to login with
        ...other_data //other data I associated with a user
       }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works easily enough. As long as the state exists in the Redux store I can see who is logged in. The only issue is if someone refreshes or types a URL directly. If that happens the store has to be re-generated and the user appears to not be logged in.&lt;/p&gt;

&lt;h2&gt;
  
  
  Second: Set up props on a component
&lt;/h2&gt;

&lt;p&gt;So, I just had to use some lifecycle methods with &lt;strong&gt;localStorage&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I can't use &lt;strong&gt;componentDidMount()&lt;/strong&gt; initially because when you first come to the application the user has not logged in. So when the component mounts there won't be any user data. So instead I looked to &lt;strong&gt;componentDidUpdate()&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To make this work I had to insure that I had the user.id in props. This way when the user logged in, the user.id would change and therefore the props would change. Then this component would update allowing my &lt;strong&gt;componentDidUpdate()&lt;/strong&gt; to trigger.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function mapStateToProps(state) {
  return {user: {id: state.user.id}}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that I only retrieved the user's ID and not the entire user object from the store's state. This is because I have other data stored as an array within the user object and that data can change pretty frequently. I don't want this page to need to re-render whenever a user's data changes. I only want to re-render when the user object changes completely.&lt;/p&gt;

&lt;p&gt;This might sound obvious, but it tripped me up for a while because I didn't consider what would trigger this page to re-render.&lt;/p&gt;

&lt;h2&gt;
  
  
  Third: Use Lifecycle Methods and localStorage
&lt;/h2&gt;

&lt;p&gt;So now that I have the correct props coming in I can set up my &lt;strong&gt;componentDidUpdate()&lt;/strong&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidUpdate(prevProps) {
      localStorage.setItem('userID', this.props.user.id);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty straight forward here. When this page re-renders it grabs the ID from the props and sets it in &lt;strong&gt;localStorage&lt;/strong&gt;. That first argument is basically a variable name and the second is the value. I called it 'userID' but you can name it whatever you want.&lt;/p&gt;

&lt;p&gt;What this doesn't account for is if someone logs out. I also need to clear the &lt;strong&gt;localStorage&lt;/strong&gt; when someone logs out. I could have cleared &lt;strong&gt;localStorage&lt;/strong&gt; in the reducer or on the page where a user chooses to log out but I wanted to have all my &lt;strong&gt;localStorage&lt;/strong&gt; accessing in one place. So I added a little bit of logic to this &lt;strong&gt;componentDidUpdate()&lt;/strong&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidUpdate(prevProps) {
    let storedID = localStorage.getItem('userID');
    if (this.props.user.id &amp;amp;&amp;amp; this.props.user.id !== storedID ) {
      localStorage.setItem('userID', this.props.user.id);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now I first check &lt;strong&gt;localStorage&lt;/strong&gt; and grab the userID that is stored there. If I am coming to the application for the first time this won't find any data. That's ok. This method shouldn't run anyway since it will only run when the user.id in props changes. If you've logged out, it will find the old userID here. (&lt;em&gt;Did you know:&lt;/em&gt; the same userID should be stored in prevProps as well!)&lt;/p&gt;

&lt;p&gt;Now for that little bit of logic. If there is now a user.id in the props and that user.id is different from the what's already in the &lt;strong&gt;localStorage&lt;/strong&gt; set the &lt;strong&gt;localStorage&lt;/strong&gt; with the new user.id. If you are logging out it will set this &lt;strong&gt;localStorage&lt;/strong&gt; to a blank string.&lt;/p&gt;

&lt;h2&gt;
  
  
  Finally: Let's deal with Users who Refresh the page!
&lt;/h2&gt;

&lt;p&gt;One last thing to worry about, and truly the only reason I am using &lt;strong&gt;localStorage&lt;/strong&gt;. What if someone refreshes the page or types a URL directly instead of using my easy links? (&lt;em&gt;Why is this someone not trusting the simplicity of this SPA?&lt;/em&gt;)&lt;/p&gt;

&lt;p&gt;This is where &lt;strong&gt;componentDidMount()&lt;/strong&gt; comes into play. When this page is mounted for the first time I need to do a little checking.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  componentDidMount() {
    let userID = localStorage.getItem('userID');
    if (userID) {
      this.props.findUser(userID)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once again I tell my component to check &lt;strong&gt;localStorage&lt;/strong&gt; for a userID. If a user is already logged in it will find that stored userID. So then I just call a method (that I defined earlier with an action) to use this userID to find the user data in my database. The reducer will then log that user in as if they hadn't cruelly refreshed the website.&lt;/p&gt;

&lt;h2&gt;
  
  
  Was this a good idea: NO! but also Yes!
&lt;/h2&gt;

&lt;p&gt;Is this a secure way to store user ID's and keep track of who's logged in. NO! &lt;/p&gt;

&lt;p&gt;But it's simple and can definitely be used for less critical data. And in my case it's ke[t my program running until I can come back and add the more secure log in functionality. So it's still useful.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>redux</category>
      <category>react</category>
    </item>
    <item>
      <title>Kill Your Darlings...</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Mon, 17 May 2021 15:51:59 +0000</pubDate>
      <link>https://forem.com/kevhines/kill-your-darlings-pc4</link>
      <guid>https://forem.com/kevhines/kill-your-darlings-pc4</guid>
      <description>&lt;p&gt;I finished my last post on this blog and something began nagging at me. I wrote all about extending a JavaScript class and listed some extended methods I built. All of a sudden I realized I didn't need one of them. (go back and &lt;a href="https://dev.to/kevhines/that-javascript-has-extended-class-1aab"&gt;read the original post here.&lt;/a&gt;)&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's look back
&lt;/h2&gt;

&lt;p&gt;Here is the extended class I wrote about:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AllCards extends Deck {

    constructor() {
        super()
        this.namedCards = []
    }

    addCardtoDeck(card) {
        super.addCardtoDeck(card)
        if (card.name) {
            this.namedCards.push(card)
        }
    }

    resetNamed() {
        this.namedCards = this.unplayedCards.filter(card =&amp;gt; card.name)
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you didn't go back and read my previous post (rude) here is what's going on. I wrote a very simple card game that used a very unique deck of cards (you can't buy these cards in stores). I had built a class to keep track of different decks of cards involved. I extended playable decks (the computer's and players cards) and I also extended an &lt;strong&gt;AllCards&lt;/strong&gt; deck that kept track of every card in the game (even the ones that were not being played with) and also kept track of each card's names and rules.&lt;/p&gt;

&lt;p&gt;I needed to keep track of which cards had names and which ones didn't so I  "cleverly" extended my &lt;strong&gt;addCardtoDeck&lt;/strong&gt; class to keep track of named cards.&lt;/p&gt;

&lt;p&gt;So far so good.&lt;/p&gt;

&lt;p&gt;Then I mentioned I created a method called &lt;strong&gt;resetNamed&lt;/strong&gt; that rebuilt my named deck when a new game is started. (Many cards may have gained names while you played).&lt;/p&gt;

&lt;p&gt;I posted my blog entry and went to work on something else.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;rebuilt my named deck.&lt;br&gt;
extended class to keep track of named cards.&lt;br&gt;
rebuilt my named deck.&lt;br&gt;
extended class to keep track of named cards.&lt;br&gt;
rebuilt my named deck.&lt;br&gt;
extended class to build named deck.&lt;br&gt;
named deck.&lt;br&gt;
named deck.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Wait a second!!!&lt;/p&gt;

&lt;h2&gt;
  
  
  Not so Clever
&lt;/h2&gt;

&lt;p&gt;I wrote a nice little extended method, but then later wrote a simple method that had the same result. That's repeated work and repeated work is inefficient coding. &lt;/p&gt;

&lt;p&gt;So I got rid of the extended class (keeping the original class that builds the deck of all cards). I found the method that called on my Deck class to rebuild all the decks before a new game and leveraged that method before the original game.&lt;/p&gt;

&lt;p&gt;The only thing an original game does that repeat games does not do is fetch card data from my database. So truly that rebuilding section of code was just building decks (it didn't matter if they existed before or not)&lt;/p&gt;

&lt;p&gt;First games and new games both run a &lt;strong&gt;prepForGame&lt;/strong&gt; method (clear some bits of the DOM, make an addition to the Game Log, clear any old decks), then a first game Fetches Data and sorts that data. After that both first and new games run &lt;strong&gt;resetNamed&lt;/strong&gt; and deal cards to the User and the Computer. &lt;/p&gt;

&lt;p&gt;The end result looks so much cleaner. Instead of building my array of Named Cards in two different ways I now did it one place, in one way. Much simpler if I ever need to make future changes.&lt;/p&gt;

&lt;p&gt;So my clever extended method wasn't as clever as just not using that method at all. &lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>That Javascript has (extended) class!</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Fri, 07 May 2021 16:17:35 +0000</pubDate>
      <link>https://forem.com/kevhines/that-javascript-has-extended-class-1aab</link>
      <guid>https://forem.com/kevhines/that-javascript-has-extended-class-1aab</guid>
      <description>&lt;p&gt;Let's talk extending classes in JavaScript.&lt;/p&gt;

&lt;p&gt;I wrote a single page JavaScript game that I called Gibberish Cards. It's kinda like War... but dumber. &lt;/p&gt;

&lt;p&gt;It didn't use a typical card deck, and the names of the cards were user defined. This mean I needed a list of what cards were in the game and a subset of those cards that had names. In addition I needed to know which cards a user had in his draw pile and which cards a computer had in his draw pile. I also needed to know which cards the user and computer had in their discard pile. That's 6 arrays of card objects!&lt;/p&gt;

&lt;p&gt;So I created a Deck class.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Simple Class
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Deck {

    constructor() {
        this.unplayedCards = []
    }

    addCardtoDeck(card) {
        this.unplayedCards.push(card)
    }


    findCard(id) {
        return this.unplayedCards.find(card =&amp;gt; card.id === id)
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I called the array of cards &lt;strong&gt;unplayedCards&lt;/strong&gt; because I needed to know which cards had not already been used in the game. I had two functions in this class &lt;strong&gt;addCardtoDeck&lt;/strong&gt; which was great when the game first started as I filled in all those different decks I talked about. And occasionally I need to find a card object so the &lt;strong&gt;findCard&lt;/strong&gt; function was very useful.&lt;/p&gt;

&lt;p&gt;But I also needed to keep track of what named cards existed. The computer only ever had named cards, and I didn't need to keep the named and unnamed cards separate for the user so I only needed a list of all the named cards in the game before starting.&lt;/p&gt;

&lt;p&gt;Rather then keep track of those named cards in all Deck classes I extended the &lt;strong&gt;Deck&lt;/strong&gt; class to an &lt;strong&gt;AllCards&lt;/strong&gt; class.&lt;/p&gt;

&lt;h2&gt;
  
  
  Extending and Using super
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AllCards extends Deck {

    constructor() {
        super()
        this.namedCards = []
    }

    addCardtoDeck(card) {
        super.addCardtoDeck(card)
        if (card.name) {
            this.namedCards.push(card)
        }
    }

    resetNamed() {
        this.namedCards = this.unplayedCards.filter(card =&amp;gt; card.name)
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because this extends from &lt;strong&gt;Deck&lt;/strong&gt; I had access to the &lt;strong&gt;findCard&lt;/strong&gt; and &lt;strong&gt;addCardtoDeck&lt;/strong&gt; function. My constructor needed both an &lt;strong&gt;unplayedCards&lt;/strong&gt; array and a &lt;strong&gt;namedCards&lt;/strong&gt; array. I used the code from the Deck class by calling the &lt;strong&gt;super()&lt;/strong&gt; method in the constructor. &lt;/p&gt;

&lt;p&gt;I determined which cards were named as I filled cards into those arrays via &lt;strong&gt;AddCardtoDeck&lt;/strong&gt; so I also had to extend that function. You can see in the extended function I call &lt;strong&gt;super.addCardtoDeck(card)&lt;/strong&gt; to add a card to my &lt;strong&gt;unplayedCards&lt;/strong&gt; array but then I have new code where I add any named cards to the &lt;strong&gt;namedCard&lt;/strong&gt; array.&lt;/p&gt;

&lt;p&gt;This would be a pointless array in the user's deck and the computer's deck so I avoided the two extra array of card objects.&lt;/p&gt;

&lt;p&gt;I also created a function just in the &lt;strong&gt;AllCards&lt;/strong&gt; class called &lt;strong&gt;resetNamed()&lt;/strong&gt; which is useful after a game ends. If a user wants to play again I don't want to re-upload all the card details from the database so it recreates the &lt;strong&gt;namedCards&lt;/strong&gt; array with any cards that got named during the most recent game. &lt;/p&gt;

&lt;p&gt;There was also a lot of functions I used in the two game decks that I never needed to use for the repository of all cards so I extended another class from &lt;strong&gt;Deck&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Another Extended Class
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PlayableDeck extends Deck {

    constructor() {
        super()
        this.playedCards = []
    }

// here is where I placed all the functions 
// only applicable to this class.

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar to the &lt;strong&gt;AllCards* class this extends from **Deck&lt;/strong&gt;, uses super to create a &lt;strong&gt;this.unplayedCards&lt;/strong&gt; array but then also creates an array for game decks that keeps track of which cards have been played since the last reshuffle. A discard pile, if you will. I called that &lt;strong&gt;playedCards&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now that I had a &lt;strong&gt;PlayableDeck&lt;/strong&gt; class I was able to create a slew of functions for game play that did not need to sit in the &lt;strong&gt;Deck&lt;/strong&gt; class.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;drawCard()&lt;/strong&gt; - randomly draws an unplayed card&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;moveCardToPlayed(card)&lt;/strong&gt; - moves a card (say that card I got from drawCard()) into the playedCards array.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;removeCardFromDeck()&lt;/strong&gt; - removes a card from played. This is used when your opponent takes your card.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;totalCards()&lt;/strong&gt; and &lt;strong&gt;totalUnplayedCards()&lt;/strong&gt; to keep track of draw and discard piles. These are also critical to know when you need to reshuffle or when you've lost the game!&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;clear()&lt;/strong&gt; - this function is clearing all cards after a game ends so you can start a new game cleanly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3 Uniquely Similar Objects!
&lt;/h2&gt;

&lt;p&gt;By extending the class I was able to have 3 Deck objects used in my code that didn't have functions or arrays baked in they would never use. It made the code cleaner and made testing easier while I coded the gameplay functionality.&lt;/p&gt;

&lt;p&gt;Extend your classes! It's easy!&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Two Tables Become Three</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Sat, 03 Apr 2021 00:46:35 +0000</pubDate>
      <link>https://forem.com/kevhines/two-tables-become-three-1bna</link>
      <guid>https://forem.com/kevhines/two-tables-become-three-1bna</guid>
      <description>&lt;p&gt;Had my first experience with a model that needed a self-join.&lt;/p&gt;

&lt;p&gt;A self-join, or self-referential association, is when a model has a relationship with itself. For example maybe an HR app has an Employee model that needs to associate with itself to let you know who manage's who. Or a Social Media app has a User model that needs to associate who is friend/follower with who.&lt;/p&gt;

&lt;p&gt;In my case I have a Monster model and I need to know which Monster has fought which other Monster. &lt;/p&gt;

&lt;p&gt;We're talking Godzilla vs King Kong - The Ultimate Ruby on Rails experience!!&lt;/p&gt;

&lt;p&gt;To understand how this will work let's first pretend that I am building a Monster vs Baseball_Player app.&lt;/p&gt;

&lt;p&gt;In that case I'd have these three models with the following associations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Monster &amp;lt; ApplicationRecord
    has_many :fights
    has_many :baseball_players, through: :fights
end

class BaseballPlayers &amp;lt; ApplicationRecord
    has_many :fights
    has_many :monsters, through: :fights
end

class Fight &amp;lt; ApplicationRecord
    belongs_to :monster
    belongs_to :baseball_player
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you've done typical many to many associations this should all make sense. So when Godzilla steps on Mike Trout and then steps on Clayton Kershaw you'd have this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;godzilla = Monster.create(name: "Godzilla")
trout = BaseballPlayer.create(name: "Mike Trout")
kershaw = BaseballPlayer.create(name: "Clayton Kershaw")

fight1 = Fight.create(monster: godzilla, baseball_player: trout)
fight2 = Fight.create(monster: godzilla, baseball_player: kershaw)

godzilla.baseball_players = [trout, kershaw]
trout.monsters = [godzilla]
kershaw.monsters = [godzilla]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But we don't want our monsters fighting baseball players. It's not a fair fight! So lets just swap in monsters for baseball players and see what issues it causes. First thing we'd notice is we have two monsters, so to identify them differently in the fight model we need to call them by different names, like monster1 and monster2, instead of just monster. In fact to make it clearer lets have it be challenger and defender. So we want this to work:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;godzilla = Monster.create(name: "Godzilla")
kingkong= Monster.create(name: "King Kong")
mothra= Monster.create(name: "Mothra")

fight1 = Fight.create(challenger: godzilla, defender: kingkong)
fight2 = Fight.create(challenger: godzilla, defender: mothra)

godzilla.defenders = [kingkong, mothra]
trout.challengers = [godzilla]
kershaw.challengers = [godzilla]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So our first stab might be to set up associations like this (spoiler alert: this won't work):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Monster &amp;lt; ApplicationRecord
    has_many :fights 
    has_many :defenders, through: :fights

    has_many :fights
    has_many :challengers, through: :fights
end

class Fight &amp;lt; ApplicationRecord
    belongs_to :monster
    belongs_to :monster
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Oops! Our Fight model has 'belongs_to :monster' twice? That doesn't make sense.&lt;/p&gt;

&lt;p&gt;Remember we called them challengers and defenders instead of using monster twice, so let's fix that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Fight &amp;lt; ApplicationRecord
    belongs_to :challenger, class_name: "Monster"
    belongs_to :defender, class_name: "Monster"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We changed monsters to the names that helped differeniate them, but then we had to tell the model what the true class name is (in this case it's Monster) so it can find the appropriate table.&lt;/p&gt;

&lt;p&gt;So now we need to clear up our Monster class. You can't just say has_many :fights because ActiveRecord is going to look for monster_id in the fights table and that foreign key doesn't exist. So let's tell the Monster model what to look for.&lt;/p&gt;

&lt;p&gt;(another spoiler: not quite working yet)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Monster &amp;lt; ApplicationRecord
    has_many :fights, foreign_key: :challenger_id, class_name: "Fight" 
    has_many :defenders, through: :fights

    has_many :fights, foreign_key: :defender_id, class_name: "Fight"
    has_many :challengers, through: :fights
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I told the model to use the foreign_key challenger_id and defender_id respectively so it knew where to look. But now the has_many, through: relationship has hit a snag. Which foreign key are we using when we say through: :fights ? It's confusing! We need to distinguish our two fights relationships with unique names too. That works just it did in our Fights model&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Monster &amp;lt; ApplicationRecord
    has_many :fights_challenged, foreign_key: :challenger_id, class_name: "Fight" 
    has_many :defenders, through: :fights_challenged

    has_many :fights_defended, foreign_key: :defender_id, class_name: "Fight"
    has_many :challengers, through: :fights_defended
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Phew. That should work. Here's the final product all put together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Monster &amp;lt; ApplicationRecord
    has_many :fights_challenged, foreign_key: :challenger_id, class_name: "Fight" 
    has_many :defenders, through: :fights_challenged

    has_many :fights_defended, foreign_key: :defender_id, class_name: "Fight"
    has_many :challengers, through: :fights_defended
end

class Fight &amp;lt; ApplicationRecord
    belongs_to :challenger, class_name: "Monster"
    belongs_to :defender, class_name: "Monster"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now I can set up Godzilla and King Kong to fight. They can't wait to take advantage of this self-join!!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>DRY-ing up code with some Helper Methods</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Sat, 03 Apr 2021 00:35:07 +0000</pubDate>
      <link>https://forem.com/kevhines/dry-ing-up-code-with-some-helper-methods-1hb6</link>
      <guid>https://forem.com/kevhines/dry-ing-up-code-with-some-helper-methods-1hb6</guid>
      <description>&lt;p&gt;Here is some recent work I did DRY-ing up my code. I had these two methods in one of my controllers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class FightsController &amp;lt; ApplicationController
def new
        @monster = Monster.find_by(id: params[:monster_id])
        if my_monster?(@monster) 
            @fight = @monster.fights_challenged.build
            @monsters = Monster.others(@monster.id)
        else
            @fight = @monster.fights_defended.build
            @monsters = current_user.monsters
        end
    end

def create
        @monster = Monster.find_by(id: params[:monster_id])
        if my_monster?(@monster) 
            @fight = @monster.fights_challenged.build(fight_params)
            @monsters = Monster.others(@monster.id)
        else
            @fight = @monster.fights_defended.build(fight_params)
            @monsters = current_user.monsters
        end

        if @fight.save
            @fight.attack
            redirect_to monster_path(@monster)
        else
            flash[:alert] = @fight.errors.full_messages
            render :new
        end
    end 
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is for a web app that allows you to create monsters and have them fight each other. When you visited a monster's page the code would determine if it was your monster. If it was you could choose from a drop down and pick a different monster to fight (Meaning it gave you a list of every monster, except the one whose page you were on). If it wasn't your monster you could choose from a drop down of which of YOUR monster's you'd like to send to fight the one you are viewing (So in this case you got a list of every monster that your account was associated with). &lt;/p&gt;

&lt;p&gt;So the code did a couple of things. It determined if you were visiting your monster or not, then it built a list of monsters, and built the appropriate fight object. It's a lot of code, and much of it repeats in both actions. So I needed to create some helper methods so that I only had the same code written once.&lt;/p&gt;

&lt;p&gt;First off I removed the line of code that determined which monster's page you were nested on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; before_action :get_monsters, only: [:new, :create]

    def set_monster
        @monster = Monster.find_by(id: params[:monster_id])
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's one line of code removed. Next was the trickier part. I had to create a helper method out of the large chunk of code that generated the list of monsters and created the appropriate fight objects. The only difference between the two similar chunks of code was that the create action took in parameters. So when I placed the code in a helper method I needed logic to decide if I was on a create action or a new action.&lt;/p&gt;

&lt;p&gt;This is what I came up with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;before_action :get_monsters, only: [:new, :create]

      def get_monsters
        if my_monster?(@monster) 
            @fight = if_challenger
            @monsters = Monster.others(@monster.id)
        else
            @fight = if_defender
            @monsters = current_user.monsters
        end
      end

     def if_challenger
         if params[:action] == "new"
             @monster.fights_challenged.build
         else
             @monster.fights_challenged.build(fight_params)
         end
     end

     def if_defender
         if params[:action] == "new"
             @monster.fights_defended.build
         else
             @monster.fights_defended.build(fight_params)
         end
     end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now, both my original actions (new and create) called get_monsters which in turn decided if they needed to call if_challenger or if_defender. &lt;/p&gt;

&lt;p&gt;Except if_challenger and if_defender looked very similar. Was there a way to make that one method instead of two so I could cut down on even more repeated code? There was, but it involved using the send method. &lt;/p&gt;

&lt;p&gt;The send method takes a number of arguments. The first one it assumes is a method, and the rest are it's parameters. Here is what it would look like if I used a send method to dynamically create a setter method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;self.send("#{method}=", value) #is the same as: self.method= value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, the one part that was different in the two methods had to be supplied to the send method. That means I had a variable that would be either "fights_challenged" or "fights_defended"&lt;/p&gt;

&lt;p&gt;So I replaced is_challenger and is_defender with build_fight that made use of the send method, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def get_monsters
        if my_monster?(@monster) 
            @fight = build_fight("fights_challenged")
            @monsters = Monster.others(@monster.id)
        else
            @fight = build_fight("fights_defended")
            @monsters = current_user.monsters
        end
    end

    def build_fight(arg)
        if params[:action] == "new"
            @monster.send(arg).build
        else
            @monster.send(arg).build(fight_params)
        end
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's talk through this one more time. When get_monsters is called the method determines if it is nested in your monster's page or not. Then it builds the appropriate monsters array. And to prepare a form on the app it calls build_fight(arg). This second method checks the params[:action] to see what action the user is currently on and then uses the arg to build the @fight object dynamically. &lt;/p&gt;

&lt;p&gt;The send method makes your code a bit trickier to read compared to most of ruby's eye friendly language, but it's very powerful in it's ability to work with changing arguments.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Validated by Built in Validations</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Fri, 05 Mar 2021 20:13:31 +0000</pubDate>
      <link>https://forem.com/kevhines/validated-by-built-in-validations-49kg</link>
      <guid>https://forem.com/kevhines/validated-by-built-in-validations-49kg</guid>
      <description>&lt;p&gt;Working on a simple Sinatra MVC app for my Flatiron Project I needed to validate a number of fields. It was so easy thanks to the many built in validation methods inherited from ActiveRecord.&lt;/p&gt;

&lt;p&gt;My project is a webpage that allows a user to create a character, and then enter equipment held by that character and/or notes about the campaign. (Both notes and equipment can be marked as private, otherwise they are all visible to all users)&lt;/p&gt;

&lt;h2&gt;
  
  
  Password Validation
&lt;/h2&gt;

&lt;p&gt;The first validation I needed was to make sure the user entered a password. (for this simple project I don't require any additional rules on the password, so you can finally use your favorite password: 12345).&lt;/p&gt;

&lt;p&gt;This validation is easy because of the bcrypt gem. In my User model I just entered the macro: has_secure_password. This encrypts the password and also requires the user to enter one on sign up. It also helps with authentication later on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:notes&lt;/span&gt;
    &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:goods&lt;/span&gt;
    &lt;span class="n"&gt;has_secure_password&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Picky UserName Validations
&lt;/h2&gt;

&lt;p&gt;But I had other requirements. I didn't want UserNames to have spaces in them or to have special characters. They aren't ever seen and I wanted to keep them simple. &lt;/p&gt;

&lt;p&gt;First I required the presence of username with this macro.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, I could have also written it like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="n"&gt;validates_presence_of&lt;/span&gt; &lt;span class="ss"&gt;:username&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But as I mentioned I wanted to keep spaces and special characters out of my user name. So I used the first version because it took in more attributes for validation. To keep out spaces and special characters I used the format attribute. With a little help from a regular expression it looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;format: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="ss"&gt;with: &lt;/span&gt;&lt;span class="sr"&gt;/\A\w+\z/&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;message: &lt;/span&gt;&lt;span class="s2"&gt;"doesn't allow spaces or special characters"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition I didn't want users to have the same usernames, so I needed to make sure they were unique. Just to be extra clear I didn't want users to have usernames that were identical except for different cases (ex. User1: Texas -- User2: texas). Both of these could be checked with the validation helper which has a case_sensitive attribute.&lt;/p&gt;

&lt;p&gt;So my final validation was:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:notes&lt;/span&gt;
    &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:goods&lt;/span&gt;
    &lt;span class="n"&gt;has_secure_password&lt;/span&gt;
    &lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;format: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="ss"&gt;with: &lt;/span&gt;&lt;span class="sr"&gt;/\A\w+\z/&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;message: &lt;/span&gt;&lt;span class="s2"&gt;"doesn't allow spaces or special characters"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="ss"&gt;uniqueness: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="ss"&gt;case_sensitive: &lt;/span&gt;&lt;span class="kp"&gt;false&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  More Validations
&lt;/h2&gt;

&lt;p&gt;Great. Now let's make sure that when users create notes they don't save blank content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Note&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:user&lt;/span&gt;
    &lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easy. Now let's do the same for my equipment page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Good&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:user&lt;/span&gt;
    &lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;:quantity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Oh wait. I don't want people entering non-numbers for quantity. I don't do any calculations with that value but it just wouldn't make sense. In fact I don't want decimals either. No one carries 1.3 swords. So let's use another built in validation macro.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Good&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:user&lt;/span&gt;
    &lt;span class="n"&gt;validates&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;:quantity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;presence: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;
    &lt;span class="n"&gt;validates_numericality_of&lt;/span&gt; &lt;span class="ss"&gt;:quantity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;only_integer: &lt;/span&gt;&lt;span class="kp"&gt;true&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are so easy. Now my code just has to grab the error messages and send them to the user so they know why their Equipment, Note or Signup didn't save.&lt;/p&gt;

&lt;h2&gt;
  
  
  Further Reading
&lt;/h2&gt;

&lt;p&gt;There are many other validation helpers. You can validate a specific length or length range. You can validate presence on update (allowing large forms to require only truly necessary pieces at first but on later updates require more values to be entered). You can not allow certain text strings (maybe you have an email field and you want to exclude people still using hotmail. You can set that up!). So many easy validations are already defined by these macros!&lt;/p&gt;

&lt;p&gt;Read more about it here: &lt;a href="https://guides.rubyonrails.org/active_record_validations.html#validation-helpers"&gt;https://guides.rubyonrails.org/active_record_validations.html#validation-helpers&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
    </item>
    <item>
      <title>Saved by a Class Variable</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Fri, 05 Feb 2021 17:51:47 +0000</pubDate>
      <link>https://forem.com/kevhines/saved-by-a-class-variable-47ah</link>
      <guid>https://forem.com/kevhines/saved-by-a-class-variable-47ah</guid>
      <description>&lt;p&gt;When working on a ruby application that doesn't connect to a database you'll need to store some critical data in Class Variables. Class Variables are available to the entire Class as well as any Instance of the Class. That's pretty useful. &lt;/p&gt;

&lt;p&gt;Instance Variables are only available to the Instance they were set in.&lt;/p&gt;

&lt;p&gt;And local variables can only be accessed in the local environment where they were created (for example in a method).&lt;/p&gt;

&lt;h2&gt;
  
  
  Don't Overuse Class and Instance Variables
&lt;/h2&gt;

&lt;p&gt;It can be an easy mistake just to make everything an Instance or Class variable. One might think, "I won't need this info outside this method, but what's the harm?"&lt;/p&gt;

&lt;p&gt;Well, a lot. The data you need in one method might get changed by another. So you'll believe a variable is empty but it's gotten a value from somewhere else. You'll need to be extra careful with names of variables. And it just forces some unnecessary storage of information. Once that method is over it's better just to forget that variable. Let your code focus on something else.&lt;/p&gt;

&lt;p&gt;Using a Class Variable when you meant to use an Instance Variable (or worse, a local variable) is exponentially worse. Now every instance is effecting your variable when you only need it in one place to do one job. &lt;/p&gt;

&lt;h2&gt;
  
  
  Good Use of Class Variables
&lt;/h2&gt;

&lt;p&gt;So as I got further along in learning to code in Ruby I got into the habit of only using Class Variables to store all the Instances of an object. You know, like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="vc"&gt;@@all&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;initialize&lt;/span&gt;
  &lt;span class="vc"&gt;@@all&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way later on I can access that list by another object. Even then I have to ask myself, will I ever need that list? In a non-database program the answer is probably.&lt;/p&gt;

&lt;p&gt;Once I have written that little bit of code Class Variables are out of my mind.&lt;/p&gt;

&lt;h2&gt;
  
  
  Houston, We Have a Problem
&lt;/h2&gt;

&lt;p&gt;I was working on a CLI program that interfaced with a free NASA API to give a list of asteroids that would be flying by Earth on a given day. &lt;/p&gt;

&lt;p&gt;You could then choose from that list and find out when that asteroid will return to Earth. Maybe you check what asteroids are flying by on the day your child was born and then you want to see when the biggest asteroid (or the one that came closest to Earth) will return. It's basically a celestial anniversary of a very special day. &lt;/p&gt;

&lt;p&gt;Everything was working pretty well except when a user opted to search the same date twice. My program creates a new object for each asteroid passing Earth (I call that object Asteroid) and then also creates objects for each Pass itself (asteroids are orbiting so they can pass by again and again). When I searched a date twice I'd just create doubles for each Pass and Asteroid.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lrCakBP9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fmptxlf4ul20qz2xhmtw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lrCakBP9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fmptxlf4ul20qz2xhmtw.png" alt="Too Many Asteroids"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Initially I solved this problem pretty elegantly. I just checked my @@all variable for any passes on that day. I assumed that if I stored one pass for the day in question then I had already grabbed all the data for that date from NASA's API. &lt;/p&gt;

&lt;p&gt;That assumption, as they often are, is wrong. You see if a user looked up an asteroid to find it's next visit they will create a single pass on a future date. What if the user decides to see what other asteroids pass by on that same date?&lt;/p&gt;

&lt;p&gt;So for example: I get a list of all the asteroids from the day my fictional friend Zane was born. I see that asteroid 2011 QF3 (that rolls off the tongue) was the biggest one in the sky that day. I check and see that it's coming back on March 29, 2030. Fun! Now let's see what other asteroids are flying by on that day. Well my code pulls that API and finds 6 asteroids coming on that day. I create those 6 Asteroids and their 6 Passes. But one of those Asteroids (2011 QF3) I have already created. And I even created it's Pass for that date. Now my data is getting corrupted with duplicates. &lt;/p&gt;

&lt;p&gt;I tried numerous ways to check my @@all variable for Pass and Asteroid to stop this from happening, but the only solution I could find was after I hit the API checking that data against other instances. That seemed a wasteful hit of the API when it might not be necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Saved by the Bel
&lt;/h2&gt;

&lt;p&gt;I talked to my instructor, Annabel, about this issue and my desire to not have to wait until after I checked the API before I checked for doubles. She looked at my code for a few moments, saw the issue and noted that my class all variable won't work so I needed to create...&lt;/p&gt;

&lt;p&gt;Before she even finished that sentence I realized what I needed to do. Create a second class variable. In my fear of over-using class and instance variables I didn't even consider the solution.&lt;/p&gt;

&lt;p&gt;Talking to Annabel reminded me that this is what class variables are for! I created a new class variables that just kept track of dates I had hit the API for. By checking "@@all_searches" before hitting my API I could determine if I had created all the Passes and Asteroids for that day already. If I had, I could skip the API step and just search for the objects from my class variable "@@all" .&lt;/p&gt;

&lt;p&gt;The same solution solved my creating a second Pass object if I searched for an asteroid's second visit twice. I created "@@next_visitation" so I knew if I had already called NASA's API for an asteroid's next visit. When the user asks for the next time an asteroid visits I don't know the date (yet). I only have the Asteroid Object. I know the next pass is in the future but there might be passes stored in our "@@all" variable that are actually the third, fourth or any number of later visits that this asteroid will next make to Earth so I need to definitively know I have that pass before I can trust the data in my "@@all" class variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="vc"&gt;@@all&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="vc"&gt;@@all_searches&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="vc"&gt;@@next_visitation&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;initialize&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;search_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pass_hash&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="c1"&gt;#code here stores the data for the Pass - not relevant to this post.&lt;/span&gt;
  &lt;span class="vc"&gt;@@all&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;
  &lt;span class="vc"&gt;@@all_searches&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pass_date&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;search_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"date_search"&lt;/span&gt;
  &lt;span class="vc"&gt;@@next_visitation&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;asteroid&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;search_type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"next_visit"&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Know when to use Class Variables and Instance Variables instead of just avoiding them. If you close off an option because of inherent misuse you might be closing yourself off to he solution to your problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KnHa_nhq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/5hvzu54w7ehweox8ytmr.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KnHa_nhq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/5hvzu54w7ehweox8ytmr.jpg" alt="Watch The Skies"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
    </item>
    <item>
      <title>A Return to Software Engineering</title>
      <dc:creator>kevhines</dc:creator>
      <pubDate>Fri, 22 Jan 2021 15:52:52 +0000</pubDate>
      <link>https://forem.com/kevhines/a-return-to-software-engineering-5dim</link>
      <guid>https://forem.com/kevhines/a-return-to-software-engineering-5dim</guid>
      <description>&lt;p&gt;The question for me isn’t why I decided to study Software Engineering, but why I came back, because I’ve been here before. &lt;/p&gt;

&lt;p&gt;In 1997 when I was getting ready to graduate with my Bachelor of Science in Chemical Engineering I knew I wasn’t going to be working in Chemical Engineering. Even before I graduated I found myself more interested in my programming electives. It felt more tactile, more real, more fun. Building a program felt similar to how I’d imagine building a house or car might feel (I might never know since I struggle to even hammer a nail in straight). The code encompassed a series of small programs that when combined could do so much more. When a program that I wrote  ran successfully I truly understood it. When it didn’t run I knew the answer was waiting for me. &lt;/p&gt;

&lt;p&gt;So after graduation I got a series of jobs that involved various levels of programming. Somehow by 2010 I had gradually slipped away from that track and found myself teaching improv and sketch at the UCB Theater in NY and that led me to running their school. This wasn’t something I ever studied or aimed for but I was the best fit for the job at the time and so there I was. I always knew, long term, I couldn’t stay there but one year followed another and the people I worked with were nice so I stayed. I always knew I’d step away and return to programming someday. Covid-19 got me to take that step.&lt;/p&gt;

&lt;p&gt;It didn’t take me long after the pandemic started to decide what I wanted to do to get back to programming. It had been 10 years away and I had never formally studied programming. A few electives in college and then a lot of jobs where I self-taught (or learned under a co-worker) helped me work in PASCAL, ColdFusion, Perl, PHP, SQL, with the necessary HTML and a basic understanding of JavaScript and a dollop of CSS. But 10 years in the programming landscape is an eternity and I knew I needed to get a handle on object orientation, dynamic web pages, and newer languages. I knew I needed to get better at writing code that read clearer, code that was simple and functioned better. So I decided to take the time and learn it right. &lt;/p&gt;

&lt;p&gt;Now I am at Flatiron, I finished all the prep work Flatiron offered before day 1 of my class and now am finishing up the first mile at their full time program. I have already refreshed old skills, learned new skills, and gotten stronger as a programmer. I am excited to continue to grow and learn as I finish the program, and am excited for where this takes me next.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
