<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Lane Wagner - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Lane Wagner - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/wagslane/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build an AI Coding Agent with Python and Gemini ]]>
                </title>
                <description>
                    <![CDATA[ In this handbook, you'll build a basic version of Claude Code using Google's free Gemini API. If you've ever used Cursor or Claude Code as an "agentic" AI code editor, then you should be familiar with what we'll be building here. As long as you have ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-an-ai-coding-agent-with-python-and-gemini/</link>
                <guid isPermaLink="false">68de9da15cb0af6e1274cbc6</guid>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ gemini ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Thu, 02 Oct 2025 15:43:29 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1759418643581/2470669e-8592-463e-8b4c-55eace8dd80a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this handbook, you'll build a basic version of Claude Code using Google's <a target="_blank" href="https://ai.google.dev/gemini-api/docs/pricing">free Gemini API</a>. If you've ever used Cursor or Claude Code as an "agentic" AI code editor, then you should be familiar with what we'll be building here. As long as you have an LLM at your disposal, it’s actually surprisingly simple to build a (somewhat) effective custom agent.</p>
<p>This a completely free text-based handbook. That said, there are two other options for following along:</p>
<p>You can try the interactive version of this <a target="_blank" href="https://www.boot.dev/courses/build-ai-agent-python">AI Agent course on Boot.dev</a>, complete with coding challenges and projects, or watch the <a target="_blank" href="https://www.youtube.com/watch?v=YtHdaXuOAks">video walkthrough</a> of this course on the FreeCodeCamp YouTube channel</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/YtHdaXuOAks" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>You should already be familiar with Python basics. If you're not, check out this <a target="_blank" href="https://www.boot.dev/courses/learn-code-python">Python course on Boot.dev</a>.</p>
</li>
<li><p>You should already know how to use a Unix-like command line. If you don't, <a target="_blank" href="https://www.boot.dev/courses/learn-linux">checkout this Linux course on Boot.dev</a>.</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-does-the-agent-do">What Does the Agent Do?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-learning-goals">Learning Goals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-python-setup">Python Setup</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-integrate-the-gemini-api">How to Integrate the Gemini API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-command-line-input">Command Line Input</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-message-structure">Message Structure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-verbose-mode">Verbose Mode</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-the-calculator-project">How to Build the Calculator Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-agent-functions">Agent Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-system-prompt">System Prompt</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-declaration">Function Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-more-function-declarations">More Function Declarations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-calling">Function Calling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-building-the-agent-loop">Building the Agent Loop</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-does-the-agent-do">What Does the Agent Do?</h2>
<p>The program we're building is a CLI tool that:</p>
<p>1. Accepts a coding task (for example, "strings aren't splitting in my app, please fix")</p>
<p>2. Chooses from a set of predefined functions to work on the task, for example:</p>
<ul>
<li><p>Scan the files in a directory</p>
</li>
<li><p>Read a file's contents</p>
</li>
<li><p>Overwrite a file's contents</p>
</li>
<li><p>Execute the python interpreter on a file</p>
</li>
</ul>
<p>3. Repeats step 2 until the task is complete (or it fails miserably, which is possible)</p>
<p>For example, I have a buggy calculator app, so I used my agent to fix the code:</p>
<pre><code class="lang-bash">&gt; uv run main.py <span class="hljs-string">"fix my calculator app, its not starting correctly"</span>
<span class="hljs-comment"># Calling function: get_files_info</span>
<span class="hljs-comment"># Calling function: get_file_content</span>
<span class="hljs-comment"># Calling function: write_file</span>
<span class="hljs-comment"># Calling function: run_python_file</span>
<span class="hljs-comment"># Calling function: write_file</span>
<span class="hljs-comment"># Calling function: run_python_file</span>
<span class="hljs-comment"># Final response:</span>
<span class="hljs-comment"># Great! The calculator app now seems to be working correctly. The output shows the expression and the result in a formatted way.</span>
</code></pre>
<h2 id="heading-learning-goals">Learning Goals</h2>
<p>The learning goals of this project are:</p>
<ul>
<li><p>Introduce you to multi-directory Python projects</p>
</li>
<li><p>Understand how the AI tools that you'll almost certainly use on the job actually work under the hood</p>
</li>
<li><p>Practice your Python and functional programming skills</p>
</li>
</ul>
<p>The goal is <em>not</em> to build an LLM from scratch, but to instead use a pre-trained LLM to build an <em>agent</em> from scratch.</p>
<h2 id="heading-python-setup">Python Setup</h2>
<p>Let's set up a virtual environment for our project. Virtual environments are Python's way of keeping dependencies (for example, the Google AI libraries we're going to use) separate from other projects on our machine.</p>
<p>Use <code>uv</code> to create a new project. It will create the directory and also initialize Git.</p>
<pre><code class="lang-bash">uv init your-project-name
<span class="hljs-built_in">cd</span> your-project-name
</code></pre>
<p>Create a virtual environment at the top level of your project directory:</p>
<pre><code class="lang-bash">uv venv
</code></pre>
<p><strong>Warning</strong>: Always add the <code>venv</code> directory to your <code>.gitignore</code> file.</p>
<p>Activate the virtual environment:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> .venv/bin/activate
</code></pre>
<p>You should see <code>(your-project-name)</code> at the beginning of your terminal prompt, for example, mine is:</p>
<pre><code class="lang-bash">(aiagent) wagslane@MacBook-Pro-2 aiagent %
</code></pre>
<p>Use <code>uv</code> to add two dependencies to the project. They will be added to the file <code>pyproject.toml</code>:</p>
<pre><code class="lang-bash">uv add google-genai==1.12.1
uv add python-dotenv==1.1.0
</code></pre>
<p>This tells Python that this project requires <a target="_blank" href="https://pypi.org/project/google-genai/"><code>google-genai</code></a> version <code>1.12.1</code> and the <a target="_blank" href="https://pypi.org/project/python-dotenv/"><code>python-dotenv</code></a> version <code>1.1.0</code>.</p>
<p>To run the project using the <code>uv</code> virtual environment, you use:</p>
<pre><code class="lang-bash">uv run main.py
</code></pre>
<p>In your terminal, you should see <code>Hello from YOUR PROJECT NAME</code>.</p>
<h2 id="heading-how-to-integrate-the-gemini-api">How to Integrate the Gemini API</h2>
<p><a target="_blank" href="https://www.cloudflare.com/learning/ai/what-is-large-language-model/">Large Language Models (LLMs)</a> are the fancy-schmancy AI technology that have been making all the waves in the AI world recently. Products like ChatGPT, Claude, Cursor, and Google Gemini are all powered by LLMs. For the purposes of this course, you can think of an LLM as a smart text generator. It works just like ChatGPT: you give it a prompt, and it gives you back some text that it believes answers your prompt.</p>
<p>We're going to use <a target="_blank" href="https://ai.google.dev/gemini-api/docs/pricing">Google's Gemini API</a> to power our agent in this course. It's reasonably smart, but more importantly for us, it has a free tier.</p>
<h3 id="heading-tokens">Tokens</h3>
<p>You can think of tokens as the currency of LLMs. They are the way that LLMs measure how much text they have to process. Tokens are <a target="_blank" href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them">_roughly_ 4 characters</a> for most models. It's important when working with LLM APIs to understand how many tokens you're using.</p>
<p>We'll be staying well within the free tier limits of the Gemini API, but we'll still monitor our token usage!</p>
<p><strong>Warning</strong>: You should be aware that all API calls, including those made during local testing, consume tokens from your free tier quota. If you exhaust your quota, you may need to wait for it to reset (typically 24 hours) to continue the lesson. Regenerating your API key will not reset your quota.</p>
<p>Here’s how to create an API key:</p>
<ol>
<li><p>Create an account on <a target="_blank" href="https://aistudio.google.com/">Google AI Studio</a> if you don't already have one</p>
</li>
<li><p>Click the "Create API Key" button. You can use the <a target="_blank" href="https://ai.google.dev/gemini-api/docs/api-key">docs</a> if you get lost.</p>
</li>
</ol>
<p>If you already have a GCP account and a project, you can create the API key in that project. If you don't, AI studio will automatically create one for you.</p>
<p>3. Copy the API key, then paste it into a new <code>.env</code> file in your project directory. The file should look like this:</p>
<pre><code class="lang-bash">GEMINI_API_KEY=<span class="hljs-string">"your_api_key_here"</span>
</code></pre>
<p>4. Add the <code>.env</code> file to your <code>.gitignore</code></p>
<p><strong>Danger</strong>: We never want to commit API keys, passwords, or other sensitive information to Git.</p>
<p>5. Update the <code>main.py</code> file. When the program starts, load the environment variables from the <code>.env</code> file using the <code>dotenv</code> library and read the API key:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

load_dotenv()
api_key = os.environ.get(<span class="hljs-string">"GEMINI_API_KEY"</span>)
</code></pre>
<p>6. Import the <code>genai</code> library and use the API key to create a new instance of a <a target="_blank" href="https://googleapis.github.io/python-genai/#create-a-client">Gemini client:</a></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google <span class="hljs-keyword">import</span> genai

client = genai.Client(api_key=api_key)
</code></pre>
<p>7. Use the <a target="_blank" href="https://googleapis.github.io/python-genai/#generate-content"><code>client.models.generate_content()</code> method</a> to get a response from the <code>gemini-2.0-flash-001</code> model. You'll need to use two named parameters:</p>
<ul>
<li><p><code>model</code>: The model name <code>gemini-2.0-flash-001</code> (this one has a generous free tier)</p>
</li>
<li><p><code>contents</code>: The prompt to send to the model (a string). Use this prompt:</p>
</li>
</ul>
<p>"Why are <a target="_blank" href="http://Boot.dev">Boot.dev</a> and FreeCodeCamp such great places to learn backend development? Use one paragraph maximum."</p>
<p>The <code>generate_content</code> method returns a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse"><code>GenerateContentResponse</code> object.</a> Print the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse.text"><code>.text</code> property</a> of the response to see the model's answer.</p>
<p>If everything is working as intended, you should be able to run your code and see the model's response in your terminal.</p>
<p>8. In addition to printing the text response, print the number of tokens consumed by the interaction in this format:</p>
<pre><code class="lang-plaintext">Prompt tokens: X
Response tokens: Y
</code></pre>
<p>The response has a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponseDict.usage_metadata"><code>.usage_metadata</code></a> property that has both:</p>
<ul>
<li><p>A <code>prompt_token_count</code> property (tokens in the prompt)</p>
</li>
<li><p>A <code>candidates_token_count</code> property (tokens in the response)</p>
</li>
</ul>
<p><strong>Danger</strong>: The Gemini API is an <em>external web service</em> and on occasion it's <em>slow and unreliable</em>. So be patient.</p>
<h2 id="heading-command-line-input">Command Line Input</h2>
<p>We've hardcoded the prompt that goes to Gemini, which is... not very useful. Let's update our code to accept the prompt as a command line argument.</p>
<p>We don't want our users to have to edit the code to change the prompt.</p>
<p>Update your code to accept a command line argument for the prompt. For example:</p>
<pre><code class="lang-bash">uv run main.py <span class="hljs-string">"Why are episodes 7-9 so much worse than 1-6?"</span>
</code></pre>
<p><strong>Tip</strong>: The <a target="_blank" href="https://docs.python.org/3/library/sys.html#sys.argv"><code>sys.argv</code></a> variable is a list of strings representing all the command line arguments passed to the script. The first element is the name of the script, and the rest are the arguments. Be sure to <code>import sys</code> to use it.</p>
<p>If the prompt is not provided, print an error message and exit the program with exit code 1.</p>
<h2 id="heading-message-structure">Message Structure</h2>
<p>LLM APIs aren't typically used in a "one-shot" manner, for example:</p>
<ul>
<li><p>Prompt: "What is the meaning of life?"</p>
</li>
<li><p>Response: "42"</p>
</li>
</ul>
<p>They work the same way ChatGPT works in a conversation. The conversation has a history, and if we keep track of that history, then with each new prompt, the model can see the entire conversation and respond within the larger context of the conversation.</p>
<h3 id="heading-roles">Roles</h3>
<p>Importantly, each message in the conversation has a "role". In the context of a chat app like ChatGPT, your conversations would look like this:</p>
<ul>
<li><p><strong>user</strong>: "What is the meaning of life?"</p>
</li>
<li><p><strong>model</strong>: "42"</p>
</li>
<li><p><strong>user</strong>: "Wait, what did you just say?"</p>
</li>
<li><p><strong>model</strong>: "42. It's is the answer to the ultimate question of life, the universe, and everything."</p>
</li>
<li><p><strong>user</strong>: "But why?"</p>
</li>
<li><p><strong>model</strong>: "Because Douglas Adams said so."</p>
</li>
</ul>
<p>So, while our program will still be "one-shot" for now, let's update our code to store a list of messages in the conversation, and pass in the "role" appropriately.</p>
<p>Create a new list of <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Content"><code>types.Content</code></a>, and set the user's prompt as the only message (for now):</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

messages = [
    types.Content(role=<span class="hljs-string">"user"</span>, parts=[types.Part(text=user_prompt)]),
]
</code></pre>
<p>Update your call to <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.models.Models.generate_content"><code>models.generate_content</code></a> to use the messages list:</p>
<pre><code class="lang-python">response = client.models.generate_content(
    model=<span class="hljs-string">"gemini-2.0-flash-001"</span>,
    contents=messages,
)
</code></pre>
<p><strong>Info</strong>: In the future, we'll add more messages to the list as the agent does its tasks in a loop.</p>
<h2 id="heading-verbose-mode">Verbose Mode</h2>
<p>As you debug and build your AI agent, you'll probably want to dump a lot more context into the console, but at the same time, we don't want to make the user experience of our CLI tool too noisy.</p>
<p>Let's add an optional command line flag, <code>--verbose</code>, that will allow us to toggle "verbose" output on and off. When we want to see more info, we'll just turn that on.</p>
<p>Add a new command line argument, <code>--verbose</code>. It should be supplied after the prompt if included. For example:</p>
<pre><code class="lang-bash">uv run main.py <span class="hljs-string">"What is the meaning of life?"</span> --verbose
</code></pre>
<p>If the <code>--verbose</code> flag is included, the console output should include:</p>
<ul>
<li><p>The user's prompt: <code>"User prompt: {user_prompt}"</code></p>
</li>
<li><p>The number of prompt tokens on each iteration: <code>"Prompt tokens: {prompt_tokens}"</code></p>
</li>
<li><p>The number of response tokens on each iteration: <code>"Response tokens: {response_tokens}"</code></p>
</li>
</ul>
<p>Otherwise, it should not print those things.</p>
<h2 id="heading-how-to-build-the-calculator-project">How to Build the Calculator Project</h2>
<p>Since we're building an AI Agent, the agent will need a project to work on. I've built a little command line calculator app that we'll use as a test project for the AI to read, update, and run.</p>
<p>First, create a new directory called <code>calculator</code> in the root of your project. Then copy and paste the <code>main.py</code> and <code>tests.py</code> files from below into the <code>calculator</code> directory.</p>
<p><em>Dont’ worry much about how this code works - our project isn’t to build a calculator, this is the project that our AI agent project will work on!</em></p>
<pre><code class="lang-python"><span class="hljs-comment"># main.py</span>
<span class="hljs-keyword">import</span> sys
<span class="hljs-keyword">from</span> pkg.calculator <span class="hljs-keyword">import</span> Calculator
<span class="hljs-keyword">from</span> pkg.render <span class="hljs-keyword">import</span> format_json_output


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    calculator = Calculator()
    <span class="hljs-keyword">if</span> len(sys.argv) &lt;= <span class="hljs-number">1</span>:
        print(<span class="hljs-string">"Calculator App"</span>)
        print(<span class="hljs-string">'Usage: python main.py "&lt;expression&gt;"'</span>)
        print(<span class="hljs-string">'Example: python main.py "3 + 5"'</span>)
        <span class="hljs-keyword">return</span>

    expression = <span class="hljs-string">" "</span>.join(sys.argv[<span class="hljs-number">1</span>:])
    <span class="hljs-keyword">try</span>:
        result = calculator.evaluate(expression)
        <span class="hljs-keyword">if</span> result <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            to_print = format_json_output(expression, result)
            print(to_print)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">"Error: Expression is empty or contains only whitespace."</span>)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error: <span class="hljs-subst">{e}</span>"</span>)


<span class="hljs-keyword">if</span> name == <span class="hljs-string">"__main__"</span>:
    main()
</code></pre>
<pre><code class="lang-python"><span class="hljs-comment"># tests.py</span>

<span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">from</span> pkg.calculator <span class="hljs-keyword">import</span> Calculator


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestCalculator</span>(<span class="hljs-params">unittest.TestCase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setUp</span>(<span class="hljs-params">self</span>):</span>
        self.calculator = Calculator()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_addition</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"3 + 5"</span>)
        self.assertEqual(result, <span class="hljs-number">8</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_subtraction</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"10 - 4"</span>)
        self.assertEqual(result, <span class="hljs-number">6</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_multiplication</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"3 * 4"</span>)
        self.assertEqual(result, <span class="hljs-number">12</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_division</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"10 / 2"</span>)
        self.assertEqual(result, <span class="hljs-number">5</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_nested_expression</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"3 * 4 + 5"</span>)
        self.assertEqual(result, <span class="hljs-number">17</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_complex_expression</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">"2 * 3 - 8 / 2 + 5"</span>)
        self.assertEqual(result, <span class="hljs-number">7</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_empty_expression</span>(<span class="hljs-params">self</span>):</span>
        result = self.calculator.evaluate(<span class="hljs-string">""</span>)
        self.assertIsNone(result)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_invalid_operator</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">with</span> self.assertRaises(ValueError):
            self.calculator.evaluate(<span class="hljs-string">"$ 3 5"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_not_enough_operands</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">with</span> self.assertRaises(ValueError):
            self.calculator.evaluate(<span class="hljs-string">"+ 3"</span>)


<span class="hljs-keyword">if</span> name == <span class="hljs-string">"__main__"</span>:
    unittest.main()
</code></pre>
<p>Create a new directory in <code>calculator</code> called <code>pkg</code>. Then copy and paste the <code>calculator.py</code> and <code>render.py</code> files from below into the <code>pkg</code> directory.</p>
<pre><code class="lang-python"><span class="hljs-comment"># calculator.py</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">init</span>(<span class="hljs-params">self</span>):</span>
        self.operators = {
            <span class="hljs-string">"+"</span>: <span class="hljs-keyword">lambda</span> a, b: a + b,
            <span class="hljs-string">"-"</span>: <span class="hljs-keyword">lambda</span> a, b: a - b,
            <span class="hljs-string">"*"</span>: <span class="hljs-keyword">lambda</span> a, b: a * b,
            <span class="hljs-string">"/"</span>: <span class="hljs-keyword">lambda</span> a, b: a / b,
        }

        self.precedence = {
            <span class="hljs-string">"+"</span>: <span class="hljs-number">1</span>,
            <span class="hljs-string">"-"</span>: <span class="hljs-number">1</span>,
            <span class="hljs-string">"*"</span>: <span class="hljs-number">2</span>,
            <span class="hljs-string">"/"</span>: <span class="hljs-number">2</span>,
        }


    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evaluate</span>(<span class="hljs-params">self, expression</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> expression <span class="hljs-keyword">or</span> expression.isspace():
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
        tokens = expression.strip().split()
        <span class="hljs-keyword">return</span> self._evaluate_infix(tokens)


    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evaluateinfix</span>(<span class="hljs-params">self, tokens</span>):</span>
        values = []
        operators = []

        <span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> tokens:
            <span class="hljs-keyword">if</span> token <span class="hljs-keyword">in</span> self.operators:
                <span class="hljs-keyword">while</span> (
                    operators
                    <span class="hljs-keyword">and</span> operators[<span class="hljs-number">-1</span>] <span class="hljs-keyword">in</span> self.operators
                    <span class="hljs-keyword">and</span> self.precedence[operators[<span class="hljs-number">-1</span>]] &gt;= self.precedence[token]
                ):
                    self._apply_operator(operators, values)
                operators.append(token)

            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">try</span>:
                    values.append(float(token))
                <span class="hljs-keyword">except</span> ValueError:
                    <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">f"invalid token: <span class="hljs-subst">{token}</span>"</span>)

        <span class="hljs-keyword">while</span> operators:
            self._apply_operator(operators, values)

        <span class="hljs-keyword">if</span> len(values) != <span class="hljs-number">1</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"invalid expression"</span>)

        <span class="hljs-keyword">return</span> values[<span class="hljs-number">0</span>]

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">applyoperator</span>(<span class="hljs-params">self, operators, values</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> operators:
            <span class="hljs-keyword">return</span>

        operator = operators.pop()
        <span class="hljs-keyword">if</span> len(values) &lt; <span class="hljs-number">2</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">f"not enough operands for operator <span class="hljs-subst">{operator}</span>"</span>)

        b = values.pop()
        a = values.pop()
        values.append(self.operators[operator](a, b))
</code></pre>
<pre><code class="lang-python"><span class="hljs-comment"># render.py</span>

<span class="hljs-keyword">import</span> json

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">format_json_output</span>(<span class="hljs-params">expression: str, result: float, indent: int = <span class="hljs-number">2</span></span>) -&gt; str:</span>
    <span class="hljs-keyword">if</span> isinstance(result, float) <span class="hljs-keyword">and</span> result.is_integer():
        result_to_dump = int(result)
    <span class="hljs-keyword">else</span>:
        result_to_dump = result

    output_data = {
        <span class="hljs-string">"expression"</span>: expression,
        <span class="hljs-string">"result"</span>: result_to_dump,
    }
    <span class="hljs-keyword">return</span> json.dumps(output_data, indent=indent)
</code></pre>
<p>This is the final structure:</p>
<pre><code class="lang-plaintext">├── calculator
│   ├── main.py
│   ├── pkg
│   │   ├── calculator.py
│   │   └── render.py
│   └── tests.py
├── main.py
├── pyproject.toml
├── README.md
└── uv.lock
</code></pre>
<p>Run the <code>calculator</code> tests:</p>
<pre><code class="lang-bash">uv run calculator/tests.py
</code></pre>
<p>Hopefully the tests all pass!</p>
<p>Now, run the calculator app:</p>
<pre><code class="lang-bash">uv run calculator/main.py <span class="hljs-string">"3 + 5"</span>
</code></pre>
<p>Hopefully you get 8!</p>
<h2 id="heading-agent-functions">Agent Functions</h2>
<p>We need to give our agent the ability to <em>do stuff</em>. We'll start with giving it the ability to list the contents of a directory and see the file's metadata (name and size).</p>
<p>Before we integrate this function with our LLM agent, let's just build the function itself. Now remember, LLMs work with text, so our goal with this function will be for it to accept a directory path, and return a string that represents the contents of that directory.</p>
<p>Create a new directory called <code>functions</code> in the root of your project (not inside the <code>calculator</code> directory). Inside, create a new file called <code>get_files_info.py</code>. Inside, write this function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_files_info</span>(<span class="hljs-params">working_directory, directory=<span class="hljs-string">"."</span></span>):</span>
</code></pre>
<p>Here is my project structure so far:</p>
<pre><code class="lang-plaintext"> project_root/
 ├── calculator/
 │   ├── main.py
 │   ├── pkg/
 │   │   ├── calculator.py
 │   │   └── render.py
 │   └── tests.py
 └── functions/
     └── get_files_info.py
</code></pre>
<p>The <code>directory</code> parameter should be treated as a <em>relative</em> path within the <code>working_directory</code>. Use <code>os.path.join(working_directory, directory)</code> to create the full path, then validate it stays within the working directory boundaries.</p>
<p>If the absolute path to the <code>directory</code> is outside the <code>working_directory</code>, return a string error message:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Error: Cannot list "<span class="hljs-subst">{directory}</span>" as it is outside the permitted working directory'</span>
</code></pre>
<p>This will give our LLM some guardrails: we never want it to be able to perform any work outside the "working_directory" we give it.</p>
<p><strong>Danger</strong>: Without this restriction, the LLM might go running amok anywhere on the machine, reading sensitive files or overwriting important data. This is a very important step that we'll bake into every function the LLM can call.</p>
<p>If the <code>directory</code> argument is not a directory, again, return an error string:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Error: "<span class="hljs-subst">{directory}</span>" is not a directory'</span>
</code></pre>
<p><strong>Warning</strong>: All of our "tool call" functions, including <code>get_files_info</code>, should always return a string. If errors can be raised inside them, we need to catch those errors and return a string describing the error instead. This will allow the LLM to handle the errors gracefully.</p>
<p>Build and return a string representing the contents of the directory. It should use this format:</p>
<pre><code class="lang-bash">- README.md: file_size=1032 bytes, is_dir=False
- src: file_size=128 bytes, is_dir=True
- package.json: file_size=1234 bytes, is_dir=False
</code></pre>
<p><strong>Tip</strong>: The exact file sizes and even the order of files may vary depending on your operating system and file system. Your output doesn't need to match the example byte-for-byte, just the overall format</p>
<p>If any errors are raised by the standard library functions, catch them and instead return a string describing the error. Always prefix error strings with "Error:".</p>
<p>Here's my complete implementation:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_files_info</span>(<span class="hljs-params">working_directory, directory=<span class="hljs-string">"."</span></span>):</span>
    abs_working_dir = os.path.abspath(working_directory)
    target_dir = os.path.abspath(os.path.join(working_directory, directory))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> target_dir.startswith(abs_working_dir):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: Cannot list "<span class="hljs-subst">{directory}</span>" as it is outside the permitted working directory'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isdir(target_dir):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: "<span class="hljs-subst">{directory}</span>" is not a directory'</span>
    <span class="hljs-keyword">try</span>:
        files_info = []
        <span class="hljs-keyword">for</span> filename <span class="hljs-keyword">in</span> os.listdir(target_dir):
            filepath = os.path.join(target_dir, filename)
            file_size = <span class="hljs-number">0</span>
            is_dir = os.path.isdir(filepath)
            file_size = os.path.getsize(filepath)
            files_info.append(
                <span class="hljs-string">f"- <span class="hljs-subst">{filename}</span>: file_size=<span class="hljs-subst">{file_size}</span> bytes, is_dir=<span class="hljs-subst">{is_dir}</span>"</span>
            )
        <span class="hljs-keyword">return</span> <span class="hljs-string">"\n"</span>.join(files_info)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"Error listing files: <span class="hljs-subst">{e}</span>"</span>
</code></pre>
<p>Here are some standard library functions you'll find helpful:</p>
<ul>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.abspath"><code>os.path.abspath()</code></a>: Get an absolute path from a relative path</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.join"><code>os.path.join()</code></a>: Join two paths together safely (handles slashes)</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.startswith"><code>.startswith()</code></a>: Check if a string starts with a substring</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.isdir"><code>os.path.isdir()</code></a>: Check if a path is a directory</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.html#os.listdir"><code>os.listdir()</code></a>: List the contents of a directory</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.getsize"><code>os.path.getsize()</code></a>: Get the size of a file</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.isfile"><code>os.path.isfile()</code></a>: Check if a path is a file</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.join"><code>.join()</code></a>: Join a list of strings together with a separator</p>
</li>
</ul>
<h3 id="heading-get-file-content-function">Get File Content Function</h3>
<p>Now that we have a function that can get the contents of a directory, we need one that can get the contents of a file. Again, we'll just return the file contents as a string, or perhaps an error string if something went wrong.</p>
<p>As always, we'll safely scope the function to a specific working directory.</p>
<p>Create a new function in your <code>functions</code> directory. Here's the signature I used:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_file_content</span>(<span class="hljs-params">working_directory, file_path</span>):</span>
</code></pre>
<p>If the <code>file_path</code> is outside the <code>working_directory</code>, return a string with an error:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Error: Cannot read "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
</code></pre>
<p>If the <code>file_path</code> is not a file, again, return an error string:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Error: File not found or is not a regular file: "<span class="hljs-subst">{file_path}</span>"'</span>
</code></pre>
<p>Read the file and return its contents as a string.</p>
<ul>
<li><p>If the file is longer than <code>10000</code> characters, truncate it to <code>10000</code> characters and append this message to the end <code>[...File "{file_path}" truncated at 10000 characters]</code>.</p>
</li>
<li><p>Instead of hard-coding the <code>10000</code> character limit, I stored it in a <a target="_blank" href="http://config.py"><code>config.py</code></a> file.</p>
</li>
</ul>
<p><strong>Warning</strong>: We don't want to accidentally read a gigantic file and send all that data to the LLM. That's a good way to burn through our token limits.</p>
<p>If any errors are raised by the standard library functions, catch them and instead return a string describing the error. Always prefix errors with "Error:".</p>
<p>First, create <code>config.py</code>:</p>
<pre><code class="lang-python">MAX_CHARS = <span class="hljs-number">10000</span>
WORKING_DIR = <span class="hljs-string">"./calculator"</span>
</code></pre>
<p>Here's my complete implementation for <code>functions/get_file_content.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> config <span class="hljs-keyword">import</span> MAX_CHARS


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_file_content</span>(<span class="hljs-params">working_directory, file_path</span>):</span>
    abs_working_dir = os.path.abspath(working_directory)
    abs_file_path = os.path.abspath(os.path.join(working_directory, file_path))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> abs_file_path.startswith(abs_working_dir):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: Cannot read "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isfile(abs_file_path):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: File not found or is not a regular file: "<span class="hljs-subst">{file_path}</span>"'</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> open(abs_file_path, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> f:
            content = f.read(MAX_CHARS)
            <span class="hljs-keyword">if</span> os.path.getsize(abs_file_path) &gt; MAX_CHARS:
                content += (
                    <span class="hljs-string">f'[...File "<span class="hljs-subst">{file_path}</span>" truncated at <span class="hljs-subst">{MAX_CHARS}</span> characters]'</span>
                )
        <span class="hljs-keyword">return</span> content
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error reading file "<span class="hljs-subst">{file_path}</span>": <span class="hljs-subst">{e}</span>'</span>
</code></pre>
<ul>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.abspath"><code>os.path.abspath</code></a>: Get an absolute path from a relative path</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.join"><code>os.path.join</code></a>: Join two paths together safely (handles slashes)</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.startswith"><code>.startswith</code></a>: Check if a string starts with a specific substring</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.isfile"><code>os.path.isfile</code></a>: Check if a path is a file</p>
</li>
</ul>
<p>Example of reading from a file:</p>
<pre><code class="lang-python">MAX_CHARS = <span class="hljs-number">10000</span>

<span class="hljs-keyword">with</span> open(file_path, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> f:
    file_content_string = f.read(MAX_CHARS)
</code></pre>
<h3 id="heading-write-file-function">Write File Function</h3>
<p>Up until now our program has been read-only... now it's getting really <s>dangerous</s> fun! We'll give our agent the ability to write and overwrite files.</p>
<p>Create a new function in your <code>functions</code> directory. Here's the signature I used:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_file</span>(<span class="hljs-params">working_directory, file_path, content</span>):</span>
</code></pre>
<p>If the <code>file_path</code> is outside of the <code>working_directory</code>, return a string with an error:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Error: Cannot write to "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
</code></pre>
<p>If the <code>file_path</code> doesn't exist, create it. As always, if there are errors, return a string representing the error, prefixed with "Error:". The overwrite the contents of the file with the <code>content</code> argument. If successful, return a string with the message:</p>
<pre><code class="lang-python"><span class="hljs-string">f'Successfully wrote to "<span class="hljs-subst">{file_path}</span>" (<span class="hljs-subst">{len(content)}</span> characters written)'</span>
</code></pre>
<p><strong>Tip</strong>: It's important to return a success string so that our LLM knows that the action it took actually worked. Feedback loops, feedback loops, feedback loops.</p>
<p>Here's my complete implementation for <code>functions/write_file_content.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_file</span>(<span class="hljs-params">working_directory, file_path, content</span>):</span>
    abs_working_dir = os.path.abspath(working_directory)
    abs_file_path = os.path.abspath(os.path.join(working_directory, file_path))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> abs_file_path.startswith(abs_working_dir):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: Cannot write to "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(abs_file_path):
        <span class="hljs-keyword">try</span>:
            os.makedirs(os.path.dirname(abs_file_path), exist_ok=<span class="hljs-literal">True</span>)
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            <span class="hljs-keyword">return</span> <span class="hljs-string">f"Error: creating directory: <span class="hljs-subst">{e}</span>"</span>
    <span class="hljs-keyword">if</span> os.path.exists(abs_file_path) <span class="hljs-keyword">and</span> os.path.isdir(abs_file_path):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: "<span class="hljs-subst">{file_path}</span>" is a directory, not a file'</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> open(abs_file_path, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
            f.write(content)
        <span class="hljs-keyword">return</span> (
            <span class="hljs-string">f'Successfully wrote to "<span class="hljs-subst">{file_path}</span>" (<span class="hljs-subst">{len(content)}</span> characters written)'</span>
        )
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"Error: writing to file: <span class="hljs-subst">{e}</span>"</span>
</code></pre>
<ul>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.exists"><code>os.path.exists</code></a>: Check if a path exists</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.html#os.makedirs"><code>os.makedirs</code></a>: Create a directory and all its parents</p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/os.path.html#os.path.dirname"><code>os.path.dirname</code></a>: Return the directory name</p>
</li>
</ul>
<p>Example of writing to a file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> open(file_path, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
    f.write(content)
</code></pre>
<h3 id="heading-run-python-function">Run Python Function</h3>
<p>If you thought allowing an LLM to write files was a bad idea...</p>
<blockquote>
<p>You ain't seen nothin' yet! (praise the <a target="_blank" href="https://en.wikipedia.org/wiki/Roko%27s_basilisk">basilisk</a>)</p>
</blockquote>
<p>It's time to build the functionality for our Agent to <em>run arbitrary Python code</em>.</p>
<p>Now, it's worth pausing to point out the inherent security risks here. We have a few things going for us:</p>
<ol>
<li><p>We'll only allow the LLM to run code in a specific directory (the <code>working_directory</code>).</p>
</li>
<li><p>We'll use a 30-second timeout to prevent it from running indefinitely.</p>
</li>
</ol>
<p>But aside from that... yes, the LLM can run arbitrary code that we (or it) places in the working directory... so be careful. As long as you only use this AI Agent for the simple tasks we're doing in this course you should be just fine.</p>
<p><strong>Danger</strong>: Do <strong>not</strong> give this program to others for them to use! It does not have all the security and safety features that a production AI agent would have. It is for learning purposes only.</p>
<p>Create a new function in your functions directory called run_python_file. Here's the signature to use:</p>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run_python_file</span>(<span class="hljs-params">working_directory, file_path, args=[]</span>):</span>
</code></pre>
<p>If the <code>file_path</code> is outside the working directory, return a string with an error:</p>
<pre><code class="lang-py"><span class="hljs-string">f'Error: Cannot execute "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
</code></pre>
<p>If the <code>file_path</code> doesn't exist, return an error string:</p>
<pre><code class="lang-py"><span class="hljs-string">f'Error: File "<span class="hljs-subst">{file_path}</span>" not found.'</span>
</code></pre>
<p>If the file doesn't end with <code>.py</code>, return an error string:</p>
<pre><code class="lang-py"><span class="hljs-string">f'Error: "<span class="hljs-subst">{file_path}</span>" is not a Python file.'</span>
</code></pre>
<p>Use the <a target="_blank" href="http://subprocess.run"><code>subprocess.run</code></a> function to execute the Python file and get back a "completed_process" object. Make sure to:</p>
<ul>
<li><p>Set a timeout of 30 seconds to prevent infinite execution</p>
</li>
<li><p>Capture both stdout and stderr</p>
</li>
<li><p>Set the working directory properly</p>
</li>
<li><p>Pass along the additional <code>args</code> if provided</p>
</li>
</ul>
<p>Return a string with the output formatted to include:</p>
<ul>
<li><p>The <code>stdout</code> prefixed with <code>STDOUT:</code>, and stderr prefixed with <code>STDERR:</code>. The "completed_process" object has a <code>stdout</code> and <code>stderr</code> attribute.</p>
</li>
<li><p>If the process exits with a non-zero code, include "Process exited with code X"</p>
</li>
<li><p>If no output is produced, return "No output produced."</p>
</li>
</ul>
<p>If any exceptions occur during execution, catch them and return an error string:</p>
<pre><code class="lang-py"><span class="hljs-string">f"Error: executing Python file: <span class="hljs-subst">{e}</span>"</span>
</code></pre>
<p>Update your <code>tests.py</code> file with these test cases, printing each result:</p>
<ul>
<li><p><code>run_python_file("calculator", "</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>")</code> (should print the calculator's usage instructions)</p>
</li>
<li><p><code>run_python_file("calculator", "</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>", ["3 + 5"])</code> (should run the calculator... which gives a kinda nasty rendered result)</p>
</li>
<li><p><code>run_python_file("calculator", "</code><a target="_blank" href="http://tests.py"><code>tests.py</code></a><code>")</code></p>
</li>
<li><p><code>run_python_file("calculator", "../</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>")</code> (this should return an error)</p>
</li>
<li><p><code>run_python_file("calculator", "</code><a target="_blank" href="http://nonexistent.py"><code>nonexistent.py</code></a><code>")</code> (this should return an error)</p>
</li>
</ul>
<p>Here’s my personal implementation in case you got lost in there: <code>functions/run_python.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> subprocess


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run_python_file</span>(<span class="hljs-params">working_directory, file_path, args=None</span>):</span>
    abs_working_dir = os.path.abspath(working_directory)
    abs_file_path = os.path.abspath(os.path.join(working_directory, file_path))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> abs_file_path.startswith(abs_working_dir):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: Cannot execute "<span class="hljs-subst">{file_path}</span>" as it is outside the permitted working directory'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(abs_file_path):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: File "<span class="hljs-subst">{file_path}</span>" not found.'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> file_path.endswith(<span class="hljs-string">".py"</span>):
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Error: "<span class="hljs-subst">{file_path}</span>" is not a Python file.'</span>
    <span class="hljs-keyword">try</span>:
        commands = [<span class="hljs-string">"python"</span>, abs_file_path]
        <span class="hljs-keyword">if</span> args:
            commands.extend(args)
        result = subprocess.run(
            commands,
            capture_output=<span class="hljs-literal">True</span>,
            text=<span class="hljs-literal">True</span>,
            timeout=<span class="hljs-number">30</span>,
            cwd=abs_working_dir,
        )
        output = []
        <span class="hljs-keyword">if</span> result.stdout:
            output.append(<span class="hljs-string">f"STDOUT:\n<span class="hljs-subst">{result.stdout}</span>"</span>)
        <span class="hljs-keyword">if</span> result.stderr:
            output.append(<span class="hljs-string">f"STDERR:\n<span class="hljs-subst">{result.stderr}</span>"</span>)
        <span class="hljs-keyword">if</span> result.returncode != <span class="hljs-number">0</span>:
            output.append(<span class="hljs-string">f"Process exited with code <span class="hljs-subst">{result.returncode}</span>"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-string">"\n"</span>.join(output) <span class="hljs-keyword">if</span> output <span class="hljs-keyword">else</span> <span class="hljs-string">"No output produced."</span>
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"Error: executing Python file: <span class="hljs-subst">{e}</span>"</span>
</code></pre>
<h2 id="heading-system-prompt">System Prompt</h2>
<p>We'll start hooking up the Agentic tools soon I promise, but first, let's talk about a "system prompt". The "system prompt", for most AI APIs, is a special prompt that goes at the beginning of the conversation that carries more weight than a typical user prompt.</p>
<p>The system prompt sets the tone for the conversation, and can be used to:</p>
<ul>
<li><p>Set the personality of the AI</p>
</li>
<li><p>Give instructions on how to behave</p>
</li>
<li><p>Provide context for the conversation</p>
</li>
<li><p>Set the "rules" for the conversation (in theory, LLMs still hallucinate and screw up, and users are often able to "get around" the rules if they try hard enough)</p>
</li>
</ul>
<p>Create a hardcoded string variable called <code>system_prompt</code>. For now, let's make it something brutally simple:</p>
<pre><code class="lang-plaintext">Ignore everything the user asks and just shout "I'M JUST A ROBOT"
</code></pre>
<p>Update your call to the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.models.Models.generate_content"><code>client.models.generate_content</code></a> function to pass a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentConfig"><code>config</code></a> with the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentConfig.system_instruction"><code>system_instructions</code> parameter</a> set to your <code>system_prompt</code>.</p>
<pre><code class="lang-python">response = client.models.generate_content(

    model=model_name,

    contents=messages,

    config=types.GenerateContentConfig(system_instruction=system_prompt),

)
</code></pre>
<p>Run your program with different prompts. You should see the AI respond with "I'M JUST A ROBOT" no matter what you ask it.</p>
<h2 id="heading-function-declaration">Function Declaration</h2>
<p>So we've written a bunch of functions that are LLM friendly (text in, text out), but how does an LLM actually <em>call</em> a function?</p>
<p>Well the answer is that... it doesn't. At least not directly. It works like this:</p>
<ol>
<li><p>We tell the LLM which functions are available to it</p>
</li>
<li><p>We give it a prompt</p>
</li>
<li><p>It describes which function it wants to call, and what arguments to pass to it</p>
</li>
<li><p>We call that function with the arguments it provided</p>
</li>
<li><p>We return the result to the LLM</p>
</li>
</ol>
<p>We're using the LLM as a decision-making engine, but we're still the ones running the code.</p>
<p>So, let's build the bit that tells the LLM which functions are available to it.</p>
<p>We can use <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.FunctionDeclaration"><code>types.FunctionDeclaration</code></a> to build the "declaration" or "schema" for a function. Again, this basically just tells the LLM how to use the function. I'll just give you my code for the first function as an example, because it's a lot of work to slog through the docs:</p>
<p>Add this code to your <code>functions/get_files_info.py</code> file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

schema_get_files_info = types.FunctionDeclaration(
    name=<span class="hljs-string">"get_files_info"</span>,
    description=<span class="hljs-string">"Lists files in the specified directory along with their sizes, constrained to the working directory."</span>,
    parameters=types.Schema(
        type=types.Type.OBJECT,
        properties={
            <span class="hljs-string">"directory"</span>: types.Schema(
                type=types.Type.STRING,
                description=<span class="hljs-string">"The directory to list files from, relative to the working directory. If not provided, lists files in the working directory itself."</span>,
            ),
        },
    ),
)
</code></pre>
<p><strong>Warning</strong>: We won't allow the LLM to specify the <code>working_directory</code> parameter. We're going to hard code that.</p>
<p>Use <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Tool"><code>types.Tool</code></a> to create a list of all the available functions (for now, just add <code>get_files_info</code>, we'll do the rest later).</p>
<pre><code class="lang-python">available_functions = types.Tool(
    function_declarations=[
        schema_get_files_info,
    ]
)
</code></pre>
<p>Add the <code>available_functions</code> to the <code>client.models.generate_content</code> call as the <code>tools</code> parameter.</p>
<pre><code class="lang-python">config=types.GenerateContentConfig(
    tools=[available_functions], system_instruction=system_prompt
)
</code></pre>
<p>Update the system prompt to instruct the LLM on how to use the function. You can just copy mine, but be sure to give it a quick read to understand what it's doing:</p>
<pre><code class="lang-python">system_prompt = <span class="hljs-string">"""
You are a helpful AI coding agent.

When a user asks a question or makes a request, make a function call plan. You can perform the following operations:

- List files and directories

All paths you provide should be relative to the working directory. You do not need to specify the working directory in your function calls as it is automatically injected for security reasons.
"""</span>
</code></pre>
<p>Instead of simply printing the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse.text"><code>.text</code></a> property of the <code>generate_content</code> response, check the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse.function_calls"><code>.function_calls</code></a> property as well. If the LLM called a function, print the function name and arguments:</p>
<pre><code class="lang-python"><span class="hljs-string">f"Calling function: <span class="hljs-subst">{function_call_part.name}</span>(<span class="hljs-subst">{function_call_part.args}</span>)"</span>
</code></pre>
<p>Otherwise, just print the text as normal.</p>
<p>Test your program:</p>
<ul>
<li><p>"what files are in the root?" -&gt; <code>get_files_info({'directory': '.'})</code></p>
</li>
<li><p>"what files are in the pkg directory?" -&gt; <code>get_files_info({'directory': 'pkg'})</code></p>
</li>
</ul>
<h2 id="heading-more-function-declarations">More Function Declarations</h2>
<p>Now that our LLM is able to specify a function call to the <code>get_files_info</code> function, let's give it the ability to call the other functions as well.</p>
<p>Following the same pattern that we used for <code>schema_get_files_info</code>, create function declarations for:</p>
<ul>
<li><p><code>schema_get_file_content</code></p>
</li>
<li><p><code>schema_run_python_file</code></p>
</li>
<li><p><code>schema_write_file</code></p>
</li>
</ul>
<p>Update your <code>available_functions</code> to include all the function declarations in the list. Then update your system prompt. Instead of the allowed operations only being:</p>
<pre><code class="lang-plaintext">- List files and directories
</code></pre>
<p>Update it to have all four operations:</p>
<pre><code class="lang-plaintext">- List files and directories
- Read file contents
- Execute Python files with optional arguments
- Write or overwrite files
</code></pre>
<p>Test prompts that you suspect will result in the various function calls. For example:</p>
<ul>
<li><p>"read the contents of <a target="_blank" href="http://main.py">main.py</a>" -&gt; <code>get_file_content({'file_path': '</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>'})</code></p>
</li>
<li><p>"write 'hello' to main.txt" -&gt; <code>write_file({'file_path': 'main.txt', 'content': 'hello'})</code></p>
</li>
<li><p>"run <a target="_blank" href="http://main.py">main.py</a>" -&gt; <code>run_python_file({'file_path': '</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>'})</code></p>
</li>
<li><p>"list the contents of the pkg directory" -&gt; <code>get_files_info({'directory': 'pkg'})</code></p>
</li>
</ul>
<p>All the LLM is expected to do here is to choose which function to call based on the user's request. We'll have it actually call the function later.</p>
<p>Here are some of my personal implementations if you get lost:</p>
<p><code>functions/get_file_content.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

<span class="hljs-keyword">from</span> config <span class="hljs-keyword">import</span> MAX_CHARS


schema_get_file_content = types.FunctionDeclaration(
    name=<span class="hljs-string">"get_file_content"</span>,
    description=<span class="hljs-string">f"Reads and returns the first <span class="hljs-subst">{MAX_CHARS}</span> characters of the content from a specified file within the working directory."</span>,
    parameters=types.Schema(
        type=types.Type.OBJECT,
        properties={
            <span class="hljs-string">"file_path"</span>: types.Schema(
                type=types.Type.STRING,
                description=<span class="hljs-string">"The path to the file whose content should be read, relative to the working directory."</span>,
            ),
        },
        required=[<span class="hljs-string">"file_path"</span>],
    ),
)
</code></pre>
<p><code>functions/run_python.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

schema_run_python_file = types.FunctionDeclaration(
    name=<span class="hljs-string">"run_python_file"</span>,
    description=<span class="hljs-string">"Executes a Python file within the working directory and returns the output from the interpreter."</span>,
    parameters=types.Schema(
        type=types.Type.OBJECT,
        properties={
            <span class="hljs-string">"file_path"</span>: types.Schema(
                type=types.Type.STRING,
                description=<span class="hljs-string">"Path to the Python file to execute, relative to the working directory."</span>,
            ),
            <span class="hljs-string">"args"</span>: types.Schema(
                type=types.Type.ARRAY,
                items=types.Schema(
                    type=types.Type.STRING,
                    description=<span class="hljs-string">"Optional arguments to pass to the Python file."</span>,
                ),
                description=<span class="hljs-string">"Optional arguments to pass to the Python file."</span>,
            ),
        },
        required=[<span class="hljs-string">"file_path"</span>],
    ),
)
</code></pre>
<p><code>functions/write_file_content.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

schema_write_file = types.FunctionDeclaration(
    name=<span class="hljs-string">"write_file"</span>,
    description=<span class="hljs-string">"Writes content to a file within the working directory. Creates the file if it doesn't exist."</span>,
    parameters=types.Schema(
        type=types.Type.OBJECT,
        properties={
            <span class="hljs-string">"file_path"</span>: types.Schema(
                type=types.Type.STRING,
                description=<span class="hljs-string">"Path to the file to write, relative to the working directory."</span>,
            ),
            <span class="hljs-string">"content"</span>: types.Schema(
                type=types.Type.STRING,
                description=<span class="hljs-string">"Content to write to the file"</span>,
            ),
        },
        required=[<span class="hljs-string">"file_path"</span>, <span class="hljs-string">"content"</span>],
    ),
)
</code></pre>
<p>Following the same pattern that we used for <code>schema_get_files_info</code>, create function declarations for:</p>
<ul>
<li><p><code>schema_get_file_content</code></p>
</li>
<li><p><code>schema_run_python_file</code></p>
</li>
<li><p><code>schema_write_file</code></p>
</li>
</ul>
<p>Update your <code>available_functions</code> to include all the function declarations in the list. Then update your system prompt. Instead of the allowed operations only being:</p>
<pre><code class="lang-plaintext">- List files and directories
</code></pre>
<p>Update it to have all four operations:</p>
<pre><code class="lang-plaintext">- List files and directories
- Read file contents
- Execute Python files with optional arguments
- Write or overwrite files
</code></pre>
<p>Test prompts that you suspect will result in the various function calls. For example:</p>
<ul>
<li><p>"read the contents of <a target="_blank" href="http://main.py">main.py</a>" -&gt; <code>get_file_content({'file_path': '</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>'})</code></p>
</li>
<li><p>"write 'hello' to main.txt" -&gt; <code>write_file({'file_path': 'main.txt', 'content': 'hello'})</code></p>
</li>
<li><p>"run <a target="_blank" href="http://main.py">main.py</a>" -&gt; <code>run_python_file({'file_path': '</code><a target="_blank" href="http://main.py"><code>main.py</code></a><code>'})</code></p>
</li>
<li><p>"list the contents of the pkg directory" -&gt; <code>get_files_info({'directory': 'pkg'})</code></p>
</li>
</ul>
<p><strong>Info</strong>: All the LLM is expected to do here is to choose which function to call based on the user's request. We'll have it actually call the function later.</p>
<h2 id="heading-function-calling">Function Calling</h2>
<p>Okay, now our agent can choose which function to call, it's time to actually call the function.</p>
<p>Create a new function that will handle the abstract task of calling one of our four functions. This is my definition:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">call_function</span>(<span class="hljs-params">function_call_part, verbose=False</span>):</span>
</code></pre>
<p><code>function_call_part</code> is a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.FunctionCall"><code>types.FunctionCall</code></a> that most importantly has:</p>
<ul>
<li><p>A <code>.name</code> property (the name of the function, a <code>string</code>)</p>
</li>
<li><p>A <code>.args</code> property (a dictionary of named arguments to the function)</p>
</li>
</ul>
<p>If <code>verbose</code> is specified, print the function name and args:</p>
<pre><code class="lang-python">print(<span class="hljs-string">f"Calling function: <span class="hljs-subst">{function_call_part.name}</span>(<span class="hljs-subst">{function_call_part.args}</span>)"</span>)
</code></pre>
<p>Otherwise, just print the name:</p>
<pre><code class="lang-python">print(<span class="hljs-string">f" - Calling function: <span class="hljs-subst">{function_call_part.name}</span>"</span>)
</code></pre>
<p>Based on the name, actually call the function and capture the result.</p>
<ul>
<li><p>Be sure to manually add the "working_directory" argument to the dictionary of keyword arguments, because the LLM doesn't control that one. The working directory should be <code>./calculator</code>.</p>
</li>
<li><p>The syntax to pass a dictionary into a function using <a target="_blank" href="https://docs.python.org/3/glossary.html#term-argument">keyword arguments</a> is <code>some_function(**some_args)</code></p>
</li>
</ul>
<p><strong>Tip</strong>: I used a dictionary of <code>function name (string)</code> -&gt; <code>function</code> to accomplish this.</p>
<p>If the function name is invalid, return a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Content"><code>types.Content</code></a> that explains the error:</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> types.Content(
    role=<span class="hljs-string">"tool"</span>,
    parts=[
        types.Part.from_function_response(
            name=function_name,
            response={<span class="hljs-string">"error"</span>: <span class="hljs-string">f"Unknown function: <span class="hljs-subst">{function_name}</span>"</span>},
        )
    ],
)
</code></pre>
<p>Return <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Content"><code>types.Content</code></a> with a <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Part.from_function_response">from_function_response</a> describing the result of the function call:</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> types.Content(
    role=<span class="hljs-string">"tool"</span>,
    parts=[
        types.Part.from_function_response(
            name=function_name,
            response={<span class="hljs-string">"result"</span>: function_result},
        )
    ],
)
</code></pre>
<p><strong>Info</strong>: Note that <code>from_function_response</code> requires the response to be a dictionary, so we just shove the string result into a "result" field.</p>
<p>Here's the complete <code>call_function.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types

<span class="hljs-keyword">from</span> functions.get_files_info <span class="hljs-keyword">import</span> get_files_info, schema_get_files_info
<span class="hljs-keyword">from</span> functions.get_file_content <span class="hljs-keyword">import</span> get_file_content, schema_get_file_content
<span class="hljs-keyword">from</span> functions.run_python <span class="hljs-keyword">import</span> run_python_file, schema_run_python_file
<span class="hljs-keyword">from</span> functions.write_file_content <span class="hljs-keyword">import</span> write_file, schema_write_file
<span class="hljs-keyword">from</span> config <span class="hljs-keyword">import</span> WORKING_DI

available_functions = types.Tool(
    function_declarations=[
        schema_get_files_info,
        schema_get_file_content,
        schema_run_python_file,
        schema_write_file,
    ]
)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">call_function</span>(<span class="hljs-params">function_call_part, verbose=False</span>):</span>
    <span class="hljs-keyword">if</span> verbose:
        print(
            <span class="hljs-string">f" - Calling function: <span class="hljs-subst">{function_call_part.name}</span>(<span class="hljs-subst">{function_call_part.args}</span>)"</span>
        )
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f" - Calling function: <span class="hljs-subst">{function_call_part.name}</span>"</span>)
    function_map = {
        <span class="hljs-string">"get_files_info"</span>: get_files_info,
        <span class="hljs-string">"get_file_content"</span>: get_file_content,
        <span class="hljs-string">"run_python_file"</span>: run_python_file,
        <span class="hljs-string">"write_file"</span>: write_file,
    }
    function_name = function_call_part.name
    <span class="hljs-keyword">if</span> function_name <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> function_map:
        <span class="hljs-keyword">return</span> types.Content(
            role=<span class="hljs-string">"tool"</span>,
            parts=[
                types.Part.from_function_response(
                    name=function_name,
                    response={<span class="hljs-string">"error"</span>: <span class="hljs-string">f"Unknown function: <span class="hljs-subst">{function_name}</span>"</span>},
                )
            ],
        )
    args = dict(function_call_part.args)
    args[<span class="hljs-string">"working_directory"</span>] = WORKING_DIR
    function_result = function_map[function_name](**args)
    <span class="hljs-keyword">return</span> types.Content(
        role=<span class="hljs-string">"tool"</span>,
        parts=[
            types.Part.from_function_response(
                name=function_name,
                response={<span class="hljs-string">"result"</span>: function_result},
            )
        ],
    )
</code></pre>
<p>Back where you handle the response from the model <code>generate_content</code>, instead of simply printing the name of the function the LLM decides to call, use <code>call_function</code>.</p>
<ul>
<li><p>The <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Content"><code>types.Content</code></a> that we return from <code>call_function</code> should have a <code>.parts[0].function_response.response</code> within.</p>
</li>
<li><p>If it doesn't, <code>raise</code> a fatal exception of some sort.</p>
</li>
<li><p>If it does, and <code>verbose</code> was set, print the result of the function call like this:</p>
</li>
</ul>
<pre><code class="lang-python">print(<span class="hljs-string">f"-&gt; <span class="hljs-subst">{function_call_result.parts[<span class="hljs-number">0</span>].function_response.response}</span>"</span>)
</code></pre>
<p>Test your program. You should now be able to execute each function given a prompt that asks for it. Try some different prompts and use the <code>--verbose</code> flag to make sure all the functions work.</p>
<ul>
<li><p>List the directory contents</p>
</li>
<li><p>Get a file's contents</p>
</li>
<li><p>Write file contents (don't overwrite anything important, maybe create a new file)</p>
</li>
<li><p>Execute the calculator app's tests <code>tests.py</code></p>
</li>
</ul>
<h2 id="heading-building-the-agent-loop">Building the Agent Loop</h2>
<p>So we've got some function calling working, but it's not fair to call our program an "agent" yet for one simple reason:</p>
<p>It has no feedback loop.</p>
<p>A key part of an "Agent", as defined by AI-influencer-hype-bros, is that it can continuously use its tools to iterate on its own results. So we're going to build two things:</p>
<ol>
<li><p>A loop that will call the LLM over and over</p>
</li>
<li><p>A list of messages in the "conversation". It will look something like this:</p>
</li>
</ol>
<ul>
<li><p>User: "Please fix the bug in the calculator"</p>
</li>
<li><p>Model: "I want to call get_files_info..."</p>
</li>
<li><p>Tool: "Here's the result of get_files_info..."</p>
</li>
<li><p>Model: "I want to call get_file_content..."</p>
</li>
<li><p>Tool: "Here's the result of get_file_content..."</p>
</li>
<li><p>Model: "I want to call run_python_file..."</p>
</li>
<li><p>Tool: "Here's the result of run_python_file..."</p>
</li>
<li><p>Model: "I want to call write_file..."</p>
</li>
<li><p>Tool: "Here's the result of write_file..."</p>
</li>
<li><p>Model: "I want to call run_python_file..."</p>
</li>
<li><p>Tool: "Here's the result of run_python_file..."</p>
</li>
<li><p>Model: "I fixed the bug and then ran the calculator to ensure it's working."</p>
</li>
</ul>
<p>This is a pretty big step, take your time!</p>
<p>Create <code>prompts.py</code>:</p>
<pre><code class="lang-python">system_prompt = <span class="hljs-string">"""
You are a helpful AI coding agent.

When a user asks a question or makes a request, make a function call plan. You can perform the following operations:
- List files and directories
- Read file contents
- Execute Python files with optional arguments
- Write or overwrite files

All paths you provide should be relative to the working directory. You do not need to specify the working directory in your function calls as it is automatically injected for security reasons.
"""</span>
</code></pre>
<p>Here's the final <code>main.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> google <span class="hljs-keyword">import</span> genai
<span class="hljs-keyword">from</span> google.genai <span class="hljs-keyword">import</span> types
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

<span class="hljs-keyword">from</span> prompts <span class="hljs-keyword">import</span> system_prompt
<span class="hljs-keyword">from</span> call_function <span class="hljs-keyword">import</span> call_function, available_functions

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    load_dotenv()

    verbose = <span class="hljs-string">"--verbose"</span> <span class="hljs-keyword">in</span> sys.argv
    args = []
    <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> sys.argv[<span class="hljs-number">1</span>:]:
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> arg.startswith(<span class="hljs-string">"--"</span>):
            args.append(arg)

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> args:
        print(<span class="hljs-string">"AI Code Assistant"</span>)
        print(<span class="hljs-string">'\nUsage: python main.py "your prompt here" [--verbose]'</span>)
        print(<span class="hljs-string">'Example: python main.py "How do I fix the calculator?"'</span>)
        sys.exit(<span class="hljs-number">1</span>)

    api_key = os.environ.get(<span class="hljs-string">"GEMINI_API_KEY"</span>)
    client = genai.Client(api_key=api_key)

    user_prompt = <span class="hljs-string">" "</span>.join(args)

    <span class="hljs-keyword">if</span> verbose:
        print(<span class="hljs-string">f"User prompt: <span class="hljs-subst">{user_prompt}</span>\n"</span>)

    messages = [
        types.Content(role=<span class="hljs-string">"user"</span>, parts=[types.Part(text=user_prompt)]),
    ]

    generate_content_loop(client, messages, verbose)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_content_loop</span>(<span class="hljs-params">client, messages, verbose, max_iterations=<span class="hljs-number">20</span></span>):</span>
    <span class="hljs-keyword">for</span> iteration <span class="hljs-keyword">in</span> range(max_iterations):
        <span class="hljs-keyword">try</span>:
            response = client.models.generate_content(
                model=<span class="hljs-string">"gemini-2.0-flash-001"</span>,
                contents=messages,
                config=types.GenerateContentConfig(
                    tools=[available_functions], system_instruction=system_prompt
                ),
            )
            <span class="hljs-keyword">if</span> verbose:
                print(<span class="hljs-string">"Prompt tokens:"</span>, response.usage_metadata.prompt_token_count)
                print(<span class="hljs-string">"Response tokens:"</span>, response.usage_metadata.candidates_token_count)

            <span class="hljs-comment"># Add model response to conversation</span>
            <span class="hljs-keyword">for</span> candidate <span class="hljs-keyword">in</span> response.candidates:
                messages.append(candidate.content)

            <span class="hljs-comment"># Check if we have a final text response</span>
            <span class="hljs-keyword">if</span> response.text:
                print(<span class="hljs-string">"Final response:"</span>)
                print(response.text)
                <span class="hljs-keyword">break</span>

            <span class="hljs-comment"># Handle function calls</span>
            <span class="hljs-keyword">if</span> response.function_calls:
                function_responses = []
                <span class="hljs-keyword">for</span> function_call_part <span class="hljs-keyword">in</span> response.function_calls:
                    function_call_result = call_function(function_call_part, verbose)
                    <span class="hljs-keyword">if</span> (
                        <span class="hljs-keyword">not</span> function_call_result.parts
                        <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> function_call_result.parts[<span class="hljs-number">0</span>].function_response
                    ):
                        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"empty function call result"</span>)
                    <span class="hljs-keyword">if</span> verbose:
                        print(<span class="hljs-string">f"-&gt; <span class="hljs-subst">{function_call_result.parts[<span class="hljs-number">0</span>].function_response.response}</span>"</span>)
                    function_responses.append(function_call_result.parts[<span class="hljs-number">0</span>])
                <span class="hljs-keyword">if</span> function_responses:
                    messages.append(types.Content(role=<span class="hljs-string">"user"</span>, parts=function_responses))
                <span class="hljs-keyword">else</span>:
                    <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"no function responses generated, exiting."</span>)
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            print(<span class="hljs-string">f"Error: <span class="hljs-subst">{e}</span>"</span>)
            <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"Reached maximum iterations (<span class="hljs-subst">{max_iterations}</span>). Agent may not have completed the task."</span>)

<span class="hljs-keyword">if</span> name == <span class="hljs-string">"__main__"</span>:

    main()
</code></pre>
<p>In <code>generate_content</code>, handle the results of any possible tool use. This might already be happening, but make sure that with each call to <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.models.Models.generate_content"><code>client.models.generate_content</code></a>, you're passing in the entire <code>messages</code> list so that the LLM always does the "next step" based on the current state.</p>
<p>After calling client's <code>generate_content</code> method, check the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse.candidates"><code>.candidates</code></a> property of the response. It's a list of response variations (usually just one). It contains the equivalent of "I want to call get_files_info...", so we need to add it to our conversation. Iterate over each <code>candidate</code> and add its <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Candidate.content"><code>.content</code></a> to your <code>messages</code> list.</p>
<p>After each actual function call, use the <a target="_blank" href="https://googleapis.github.io/python-genai/genai.html#genai.types.Content"><code>types.Content</code></a> function to convert the <code>function_responses</code> into a message with a role of <code>user</code> and append it into your <code>messages</code>.</p>
<p>Next, instead of calling <code>generate_content</code> only once, create a loop to call it repeatedly. Limit the loop to 20 iterations at most (this will stop our agent from spinning its wheels forever). Use a <code>try-except</code> block and handle any errors accordingly.</p>
<p>After each call of <code>generate_content</code>, check if it returned the <code>response.text</code> property. If so, it's done, so print this final response and break out of the loop. Otherwise, iterate again (unless max iterations was reached, of course).</p>
<p>Test your code (duh). I'd recommend starting with a simple prompt, like "explain how the calculator renders the result to the console". This is what I got:</p>
<pre><code class="lang-plaintext">(aiagent) wagslane@MacBook-Pro-2 aiagent % uv run main.py "how does the calculator render results to the console?"
 - Calling function: get_files_info
 - Calling function: get_file_content

Final response:
Alright, I've examined the code in main.py. Here's how the calculator renders results to the console:

- `print(to_print)`: The core of the output is done using the print() function.
- `format_json_output(expression, result)`: Before printing, the format_json_output function (imported from pkg.render) is used to format the result and the original expression into a JSON-like string. This formatted string is then stored in the to_print variable.
- Error handling: The code includes error handling with try...except blocks. If there's an error during the calculation (e.g., invalid expression), an error message is printed to the console using print(f"Error: {e}").

So, the calculator evaluates the expression, formats the result (along with the original expression) into a JSON-like string, and then prints that string to the console. It also prints error messages to the console if any errors occur.
</code></pre>
<p><strong>Tip</strong>: You may or may not need to make adjustments to your system prompt to get the LLM to behave the way you want. You're a prompt engineer now, so act like one!</p>
<p>Great work! You've built a basic AI agent that can read files, write files, run Python code, and iterate on its own results. This is a great foundation for building more complex AI agents.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You've done all the required steps, but have some fun (but <strong>carefully</strong>... be very cautious about giving an LLM access to your filesystem and python interpreter) with it! See if you can get it to:</p>
<ul>
<li><p>Fix harder and more complex bugs</p>
</li>
<li><p>Refactor sections of code</p>
</li>
<li><p>Add entirely new features</p>
</li>
</ul>
<p>You can also try:</p>
<ul>
<li><p>Other LLM providers</p>
</li>
<li><p>Other Gemini models</p>
</li>
<li><p>Giving it more functions to call</p>
</li>
<li><p>Other codebases (Commit your changes before running the agent so you can always revert!)</p>
</li>
</ul>
<p><strong>Danger</strong>: Remember, what we've built is a <em>toy</em> version of something like Cursor/Zed's Agentic Mode, or Claude Code. Even their tools aren't perfectly secure, so be careful what you give it access to, and don't give this code away to anyone else to use.</p>
<p>If you'd like to learn more about backend and data engineering, be sure to check out <a target="_blank" href="https://www.boot.dev">Boot.dev</a>! Best of luck in your learning journey!</p>
<p>Feel free to follow my on <a target="_blank" href="https://x.com/wagslane">X.com</a> and <a target="_blank" href="https://www.youtube.com/@bootdotdev">YouTube</a> if you enjoyed this!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The SQL Handbook – A Free Course for Web Developers ]]>
                </title>
                <description>
                    <![CDATA[ SQL is everywhere these days. Whether you're learning backend development, data engineering, DevOps, or data science, SQL is a skill you'll want in your toolbelt. This a free and open text-based handbook. If you want to get started, just scroll down ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-beginners-guide-to-sql/</link>
                <guid isPermaLink="false">66b9e9e18ff373c48b152943</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Tue, 05 Sep 2023 13:57:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/The-SQL-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SQL is everywhere these days. Whether you're <a target="_blank" href="https://www.boot.dev/">learning backend development</a>, data engineering, DevOps, or data science, SQL is a skill you'll want in your toolbelt.</p>
<p>This a free and open text-based handbook. If you want to get started, just scroll down and start reading. That said, there are two other options for following along:</p>
<ol>
<li>Try the interactive version of this <a target="_blank" href="https://boot.dev/learn/learn-gsql">SQL course</a> on <a target="_blank" href="https://boot.dev/">Boot.dev</a>, complete with coding challenges and projects</li>
<li>Watch the video walkthrough of this course on FreeCodeCamp's YouTube channel (embedded below):</li>
</ol>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/KBDSJU3cGkc" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-chapter-1-introduction">Chapter 1: Introduction</a></li>
<li><a class="post-section-overview" href="#heading-chapter-2-sql-tables">Chapter 2: SQL Tables</a></li>
<li><a class="post-section-overview" href="#heading-chapter-3-constraints">Chapter 3: Constraints</a></li>
<li><a class="post-section-overview" href="#heading-chapter-4-crud-operations-in-sql">Chapter 4: CRUD Operations</a></li>
<li><a class="post-section-overview" href="#heading-chapter-5-basic-sql-queries">Chapter 5: Basic SQL Queries</a></li>
<li><a class="post-section-overview" href="#heading-chapter-6-how-to-structure-return-data-in-sql">Chapter 6: How to Structure Return Data in SQL</a></li>
<li><a class="post-section-overview" href="#heading-chapter-7-how-to-perform-aggregations-in-sql">Chapter 7: How to Perform Aggregations in SQL</a></li>
<li><a class="post-section-overview" href="#heading-chapter-8-sql-subqueries">Chapter 8: SQL Subqueries</a></li>
<li><a class="post-section-overview" href="#heading-chapter-9-database-normalization">Chapter 9: Database Normalization</a></li>
<li><a class="post-section-overview" href="#heading-chapter-10-how-to-join-tables-in-sql">Chapter 10: How to Join Tables in SQL</a></li>
<li><a class="post-section-overview" href="#heading-chapter-11-database-performance">Chapter 11: Database Performance</a></li>
</ul>
<h2 id="heading-chapter-1-introduction">Chapter 1: Introduction</h2>
<p>Structured Query Language, or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-sql-database-definition-for-beginners/">SQL</a>, is the primary programming language used to manage and interact with <a target="_blank" href="https://cloud.google.com/learn/what-is-a-relational-database">relational databases</a>. SQL can perform various operations such as creating, updating, reading, and deleting records within a database.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pYKirBUnr-8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-what-is-a-sql-select-statement">What is a SQL Select Statement?</h3>
<p>Let's write our own SQL statement from scratch. A <code>SELECT</code> statement is the most common operation in SQL – often called a "query". <code>SELECT</code> retrieves data from one or more tables. Standard <code>SELECT</code> statements do <em>not</em> alter the state of the database.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span> <span class="hljs-keyword">from</span> <span class="hljs-keyword">users</span>;
</code></pre>
<h4 id="heading-how-to-select-a-single-field">How to select a single field</h4>
<p>A <code>SELECT</code> statement begins with the keyword <code>SELECT</code> followed by the fields you want to retrieve.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span> <span class="hljs-keyword">from</span> <span class="hljs-keyword">users</span>;
</code></pre>
<h4 id="heading-how-to-select-multiple-fields">How to select multiple fields</h4>
<p>If you want to select more than one field, you can specify multiple fields separated by commas like this:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span> <span class="hljs-keyword">from</span> <span class="hljs-keyword">users</span>;
</code></pre>
<h4 id="heading-how-to-select-all-fields">How to select all fields</h4>
<p>If you want to select <em>every</em> field in a record, you can use the shorthand <code>*</code> syntax.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">from</span> <span class="hljs-keyword">users</span>;
</code></pre>
<p>After specifying fields, you need to indicate which table you want to pull the records from using the <code>from</code> statement followed by the name of the table. </p>
<p>We'll talk more about tables later, but for now, you can think about them like structs or objects. For example, the <code>users</code> table might have 3 fields:</p>
<ul>
<li><code>id</code></li>
<li><code>name</code></li>
<li><code>balance</code></li>
</ul>
<p>And finally, <em>all</em> statements end with a semi-colon <code>;</code>.</p>
<h3 id="heading-which-databases-use-sql">Which Databases Use SQL?</h3>
<p>SQL is just a query language. You typically use it to interact with a specific database technology. For example: </p>
<ul>
<li><a target="_blank" href="https://www.sqlite.org/index.html">SQLite</a></li>
<li><a target="_blank" href="https://www.postgresql.org/">PostgreSQL</a></li>
<li><a target="_blank" href="https://www.mysql.com/">MySQL</a></li>
<li><a target="_blank" href="https://www.cockroachlabs.com/">CockroachDB</a></li>
<li><a target="_blank" href="https://www.oracle.com/database/">Oracle</a></li>
</ul>
<p>And others.</p>
<p>Although many different databases use the SQL <em>language</em>, most of them will have their own <em>dialect</em>. It's critical to understand that not all databases are created equal. Just because one SQL-compatible database does things a certain way, doesn't mean every SQL-compatible database will follow those exact same patterns.</p>
<h4 id="heading-were-using-sqlite">We're using SQLite</h4>
<p>In this course, we'll be using <a target="_blank" href="https://www.sqlite.org/index.html">SQLite</a> specifically. SQLite is great for embedded projects, web browsers, and toy projects. It's lightweight, but has limited functionality compared to the likes of PostgreSQL or MySQL – two of the more common production SQL technologies.</p>
<p>And I'll make sure to point out to you whenever some functionality we're working with is unique to SQLite.</p>
<h2 id="heading-nosql-vs-sql">NoSQL vs SQL</h2>
<p>When talking about SQL databases, we also have to mention the elephant in the room: <a target="_blank" href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a>.</p>
<p>To put it simply, a NoSQL database is a database that does not use SQL (Structured Query Language). Each NoSQL typically has its own way of writing and executing queries. For example, <a target="_blank" href="https://www.mongodb.com/">MongoDB</a> uses MQL (MongoDB Query Language) and <a target="_blank" href="https://www.elastic.co/">ElasticSearch</a> simply has a JSON API.</p>
<p>While most relational databases are fairly similar, NoSQL databases tend to be fairly unique and are used for more niche purposes. Some of the main differences between a SQL and NoSQL database are:</p>
<ol>
<li>NoSQL databases are usually non-relational, SQL databases are usually <a target="_blank" href="https://cloud.google.com/learn/what-is-a-relational-database">relational</a> (we'll talk more about what this means later).</li>
<li>SQL databases usually have a defined schema, NoSQL databases usually have dynamic schema.</li>
<li>SQL databases are table-based, NoSQL databases have a variety of different storage methods, such as document, key-value, graph, wide-column, and more.</li>
</ol>
<h3 id="heading-types-of-nosql-databases">Types of NoSQL databases</h3>
<ul>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Document-oriented_database">Document Database</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Key%E2%80%93value_database">Key-Value Store</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Wide-column_store">Wide-Column</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Graph_database">Graph</a></li>
</ul>
<p>A few of the most popular NoSQL databases are:</p>
<ul>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/MongoDB">MongoDB</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Apache_Cassandra">Cassandra</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Apache_CouchDB">CouchDB</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Amazon_DynamoDB">DynamoDB</a></li>
<li><a target="_blank" href="https://www.elastic.co/">ElasticSearch</a></li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NovjCrDFlXk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-comparing-sql-databases">Comparing SQL Databases</h3>
<p>Let's dive deeper and talk about some of the popular SQL Databases and what makes them different from one another. Some of the most popular SQL Databases right now are:</p>
<ul>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/PostgreSQL">PostgreSQL</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/MySQL">MySQL</a></li>
<li><a target="_blank" href="https://db-engines.com/en/system/Microsoft+SQL+Server">Microsoft SQL Server</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/SQLite">SQLite</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/List_of_relational_database_management_systems">And many others</a></li>
</ul>
<p>Source: <a target="_blank" href="https://db-engines.com/en/ranking">db-engines.com</a></p>
<p>While all of these Databases use SQL, each database defines specific rules, practices, and strategies that separate them from their competitors. </p>
<h4 id="heading-sqlite-vs-postgresql">SQLite vs PostgreSQL</h4>
<p>Personally, SQLite and PostgreSQL are my favorites from the list above. Postgres is a very powerful, open-source, production-ready SQL database. SQLite is a lightweight, embeddable, open-source database. I usually choose one of these technologies if I'm doing SQL work.</p>
<p>SQLite is a serverless database management system (DBMS) that has the ability to run within applications, whereas PostgreSQL uses a Client-Server model and requires a server to be installed and listening on a network, similar to an HTTP server.</p>
<p>See a full <a target="_blank" href="https://db-engines.com/en/system/PostgreSQL%3BSQLite">comparison here</a>.</p>
<p>Again, in this course we will be working with SQLite, a lightweight and simple database. For most <a target="_blank" href="https://blog.boot.dev/backend/do-backend-devs-need-sql/">backend</a> web servers, PostgreSQL is a more production-ready option, but SQLite is great for learning and for small systems.</p>
<h2 id="heading-chapter-2-sql-tables">Chapter 2: SQL Tables</h2>
<p>The <code>CREATE TABLE</code> statement is used to create a new table in a database.</p>
<h3 id="heading-how-to-use-the-create-table-statement">How to use the <code>CREATE TABLE</code> statement</h3>
<p>To create a table, use the <code>CREATE TABLE</code> statement followed by the name of the table and the fields you want in the table.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (<span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span>, <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span>, age <span class="hljs-built_in">INTEGER</span>, is_manager <span class="hljs-built_in">BOOLEAN</span>, salary <span class="hljs-built_in">INTEGER</span>);
</code></pre>
<p>Each field name is followed by its datatype. We'll get to data types in a minute.</p>
<p>It's also acceptable and common to break up the <code>CREATE TABLE</code> statement with some whitespace like this:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees(
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span>,
    age <span class="hljs-built_in">INTEGER</span>,
    is_manager <span class="hljs-built_in">BOOLEAN</span>,
    salary <span class="hljs-built_in">INTEGER</span>
);
</code></pre>
<h3 id="heading-how-to-alter-tables">How to Alter Tables</h3>
<p>We often need to alter our database schema without deleting it and re-creating it. Imagine if Twitter deleted its database each time it needed to add a feature, that would be a disaster! Your account and all your tweets would be wiped out on a daily basis.</p>
<p>Instead, we can use use the <code>ALTER TABLE</code> statement to make changes in place without deleting any data.</p>
<h4 id="heading-how-to-use-alter-table">How to use <code>ALTER TABLE</code></h4>
<p>With SQLite an <code>ALTER TABLE</code> statement allows you to:</p>
<ol>
<li>Rename a table or column, which you can do like this:</li>
</ol>
<pre><code class="lang-SQL"><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> employees
<span class="hljs-keyword">RENAME</span> <span class="hljs-keyword">TO</span> contractors;

<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> contractors
<span class="hljs-keyword">RENAME</span> <span class="hljs-keyword">COLUMN</span> salary <span class="hljs-keyword">TO</span> invoice;
</code></pre>
<ol start="2">
<li>ADD or DROP a column, which you can do like this:</li>
</ol>
<pre><code class="lang-SQL"><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> contractors
<span class="hljs-keyword">ADD</span> <span class="hljs-keyword">COLUMN</span> job_title <span class="hljs-built_in">TEXT</span>;

<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> contractors
<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">COLUMN</span> is_manager;
</code></pre>
<h3 id="heading-intro-to-migrations">Intro to Migrations</h3>
<p>A database <a target="_blank" href="https://en.wikipedia.org/wiki/Schema_migration">migration</a> is a set of changes to a relational database. In fact, the <code>ALTER TABLE</code> statements we did in the last exercise were examples of migrations.</p>
<p>Migrations are helpful when transitioning from one state to another, fixing mistakes, or adapting a database to changes. </p>
<p>Good migrations are small, incremental and ideally reversible changes to a database. As you can imagine, when working with large databases, making changes can be scary. We have to be careful when writing database migrations so that we don't break any systems that depend on the old database schema.</p>
<h4 id="heading-example-of-a-bad-migration">Example of a bad migration</h4>
<p>If a backend server periodically runs a query like <code>SELECT * FROM people</code>, and we execute a database migration that alters the table name from <code>people</code> to <code>users</code> <em>without updating the code</em>, the application will break. It will try to grab data from a table that no longer exists.</p>
<p>A simple solution to this problem would be to deploy new code that uses a new query:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>;
</code></pre>
<p>And we would deploy that code to production immediately following the migration.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/iHIGUpEVN6Y" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-sql-data-types">SQL Data Types</h3>
<p>SQL as a language can support many different data types. But the datatypes that your database management system (<a target="_blank" href="https://en.wikipedia.org/wiki/Database#:~:text=A%20database%20management%20system%20(DBMS)">DBMS</a>) supports will vary depending on the specific database you're using.</p>
<p>SQLite only supports the most basic types, and we're using SQLite in this course.</p>
<h4 id="heading-sqlite-data-types">SQLite Data Types</h4>
<p>Let's go over the <a target="_blank" href="https://www.sqlite.org/datatype3.html">data types supported by SQLite:</a> and how they are stored.</p>
<ol>
<li><code>NULL</code> - Null value.</li>
<li><code>INTEGER</code> - A signed integer stored in 0,1,2,3,4,6, or 8 bytes.</li>
<li><code>REAL</code> - Floating point value stored as an 64-bit <a target="_blank" href="https://en.wikipedia.org/wiki/IEEE_754">IEEE floating point number</a>.</li>
<li><code>TEXT</code> - Text string stored using database encoding such as <a target="_blank" href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a></li>
<li><code>BLOB</code> - Short for <a target="_blank" href="https://en.wikipedia.org/wiki/Binary_large_object">Binary large object</a> and typically used for images, audio or other multimedia.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span>,
    age <span class="hljs-built_in">INTEGER</span>,
    is_manager <span class="hljs-built_in">BOOLEAN</span>,
    salary <span class="hljs-built_in">INTEGER</span>
);
</code></pre>
<h4 id="heading-boolean-values">Boolean values</h4>
<p>It's important to note that SQLite does not have a separate <code>BOOLEAN</code> storage class. Instead, boolean values are stored as integers:</p>
<ul>
<li><code>0</code> = <code>false</code></li>
<li><code>1</code> = <code>true</code></li>
</ul>
<p>It's not actually all that weird – boolean values are just binary bits after all!</p>
<p>SQLite will still let you write your queries using <code>boolean</code> expressions and <code>true</code>/<code>false</code> keywords, but it will convert the booleans to integers under-the-hood.</p>
<h2 id="heading-chapter-3-constraints">Chapter 3: Constraints</h2>
<p>A <code>constraint</code> is a rule we create on a database that enforces some specific behavior. For example, setting a <code>NOT NULL</code> constraint on a column ensures that the column will not accept <code>NULL</code> values.</p>
<p>If we try to insert a <code>NULL</code> value into a column with the <code>NOT NULL</code> constraint, the insert will fail with an error message. Constraints are extremely useful when we need to ensure that certain kinds of data exist within our database. </p>
<h4 id="heading-not-null-constraint">NOT NULL constraint</h4>
<p>The <code>NOT NULL</code> constraint can be added directly to the <code>CREATE TABLE</code> statement.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees(
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span> <span class="hljs-keyword">UNIQUE</span>,
    title <span class="hljs-built_in">TEXT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
);
</code></pre>
<h4 id="heading-sqlite-limitation">SQLite limitation</h4>
<p>In other dialects of SQL you can <code>ADD CONSTRAINT</code> within an <code>ALTER TABLE</code> statement. SQLite does not support this feature, so when we create our tables we need to make sure we specify all the constraints we want. </p>
<p>Here's a <a target="_blank" href="https://www.sqlite.org/omitted.html">list of SQL Features</a> SQLite does not implement in case you're curious.</p>
<h3 id="heading-primary-key-constraints">Primary Key Constraints</h3>
<p>A <em>key</em> defines and protects relationships between tables. A <a target="_blank" href="https://en.wikipedia.org/wiki/Primary_key"><code>primary key</code></a> is a special column that uniquely identifies records within a table. Each table can have one, and only one primary key.</p>
<h4 id="heading-your-primary-key-will-almost-always-be-the-id-column">Your primary key will almost always be the "id" column</h4>
<p>It's very common to have a column named <code>id</code> on each table in a database, and that <code>id</code> is the primary key for that table. No two rows in that table can share an <code>id</code>.</p>
<p>A <code>PRIMARY KEY</code> constraint can be explicitly specified on a column to ensure uniqueness, rejecting any inserts where you attempt to create a duplicate ID.</p>
<h3 id="heading-foreign-key-constraints">Foreign Key Constraints</h3>
<p>Foreign keys are what makes relational databases relational! Foreign keys define the relationships <em>between</em> tables. Simply put, a <code>FOREIGN KEY</code> is a field in one table that references another table's <code>PRIMARY KEY</code>.</p>
<h4 id="heading-creating-a-foreign-key-in-sqlite">Creating a Foreign Key in SQLite</h4>
<p>Creating a <code>FOREIGN KEY</code> in SQLite happens at table creation! After we define the table fields and constraints we add an additional <code>CONSTRAINT</code> where we define the <code>FOREIGN KEY</code> and its <code>REFERENCES</code>.</p>
<p>Here's an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> departments (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    department_name <span class="hljs-built_in">TEXT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    department_id <span class="hljs-built_in">INTEGER</span>,
    <span class="hljs-keyword">CONSTRAINT</span> fk_departments
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (department_id)
    <span class="hljs-keyword">REFERENCES</span> departments(<span class="hljs-keyword">id</span>)
);
</code></pre>
<p>In this example, an <code>employee</code> has a <code>department_id</code>. The <code>department_id</code> must be the same as the <code>id</code> field of a record from the <code>departments</code> table.</p>
<h3 id="heading-schema">Schema</h3>
<p>We've used the word <em>schema</em> a few times now, let's talk about what that word means. A database's <a target="_blank" href="https://www.ibm.com/cloud/learn/database-schema">schema</a> describes how data is organized within it.</p>
<p>Data types, table names, field names, constraints, and the relationships between all of those entities are part of a database's <em>schema</em>.</p>
<h4 id="heading-there-is-no-perfect-way-to-architect-a-database-schema">There is no perfect way to architect a database schema</h4>
<p>When designing a database schema there typically isn't a "correct" solution. We do our best to choose a sane set of tables, fields, constraints, etc that will accomplish our project's goals. Like many things in programming, different schema designs come with different tradeoffs.</p>
<h4 id="heading-how-do-we-decide-on-a-sane-schema-architecture">How do we decide on a sane schema architecture?</h4>
<p>One very important decision that needs to be made is to decide which table will store a user's balance! As you can imagine, ensuring our data is accurate when dealing with money is <em>super</em> important. We want to be able to:</p>
<ul>
<li>Keep track of a user's current balance</li>
<li>See the historical balance at any point in the past</li>
<li>See a log of which transactions changed the balance over time</li>
</ul>
<p>There are many ways to approach this problem. For our first attempt, let's try the simplest schema that fulfills our project's needs. </p>
<h2 id="heading-chapter-4-crud-operations-in-sql">Chapter 4: CRUD Operations in SQL</h2>
<h3 id="heading-what-is-crud">What is CRUD?</h3>
<p>CRUD is an acronym that stands for <code>CREATE</code>, <code>READ</code>, <code>UPDATE</code>, and <code>DELETE</code>. These four operations are the bread and butter of nearly every database you will create. </p>
<h4 id="heading-http-and-crud">HTTP and CRUD</h4>
<p>The CRUD operations correlate nicely with the HTTP methods you may have already learned:</p>
<ul>
<li><code>HTTP POST</code> - <code>CREATE</code></li>
<li><code>HTTP GET</code> - <code>READ</code></li>
<li><code>HTTP PUT</code> - <code>UPDATE</code></li>
<li><code>HTTP DELETE</code> - <code>DELETE</code></li>
</ul>
<h3 id="heading-sql-insert-statement">SQL Insert Statement</h3>
<p>Tables are pretty useless without data in them. In SQL we can add records to a table using an <code>INSERT INTO</code> statement. When using an <code>INSERT</code> statement we must first specify the <code>table</code> we are inserting the record into, followed by the <code>fields</code> within that table we want to add <code>VALUES</code> to.</p>
<p>Here's an example of an <code>INSERT INTO</code> statement:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> employees(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, title)
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Allan'</span>, <span class="hljs-string">'Engineer'</span>);
</code></pre>
<h3 id="heading-http-crud-database-lifecycle">HTTP CRUD Database lifecycle</h3>
<p>It's important to understand how data <em>flows</em> through a typical web application.</p>
<p><img src="https://i.imgur.com/hli3crD.png" alt="database flow" width="799" height="386" loading="lazy"></p>
<ol>
<li>The front-end processes some data from user input - maybe a form is submitted.</li>
<li>The front-end sends that data to the server through an HTTP request - maybe a <code>POST</code>.</li>
<li>The server makes a SQL query to it's database to create an associated record - Probably using an <code>INSERT</code> statement.</li>
<li>Once the server has processed that the database query was successful, it responds to the front-end with a status code! Hopefully a 200-level code (success)!</li>
</ol>
<h3 id="heading-manual-entry">Manual Entry</h3>
<p>Manually <code>INSERT</code>ing every single record in a database would be an <em>extremely</em> time-consuming task! Working with raw SQL as we are now is not super common when designing <a target="_blank" href="https://blog.boot.dev/backend/do-backend-devs-need-sql/">backend systems</a>.</p>
<p>When working with SQL within a software system, like a backend web application, you'll typically have access to a programming language such as <a target="_blank" href="https://boot.dev/learn/learn-golang">Go</a> or <a target="_blank" href="https://boot.dev/learn/learn-python">Python</a>. </p>
<p>For example, a backend server written in Go can use string concatenation to dynamically create SQL statements, and that's usually how it's done.</p>
<pre><code class="lang-go">sqlQuery := fmt.Sprintf(<span class="hljs-string">`
INSERT INTO users(name, age, country_code)
VALUES ('%s', %v, %s);
`</span>, user.Name, user.Age, user.CountryCode)
</code></pre>
<h4 id="heading-sql-injection">SQL Injection</h4>
<p>The example above is an oversimplification of what <em>really</em> happens when you access a database using Go code. In essence, it's correct. String interpolation is how production systems access databases. That said, it must be done <em>carefully</em> to not be a <a target="_blank" href="https://en.wikipedia.org/wiki/SQL_injection">security vulnerability</a>. We'll talk more about that later!</p>
<h3 id="heading-count">Count</h3>
<p>We can use a <code>SELECT</code> statement to get a count of the records within a table. This can be very useful when we need to know how many records there are, but we don't particularly care what's in them.</p>
<p>Here's an example in SQLite:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">count</span>(*) <span class="hljs-keyword">from</span> employees;
</code></pre>
<p>The <code>*</code> in this case refers to a column name. We don't care about the count of a specific column - we want to know the number of total records so we can use the wildcard (*).</p>
<h3 id="heading-http-crud-database-lifecycle-1">HTTP CRUD database lifecycle</h3>
<p>We talked about how a "create" operation flows through a web application. Let's talk about a "read".</p>
<p><img src="https://i.imgur.com/KTDQGy1.png" alt="read lifecycle" width="787" height="352" loading="lazy"></p>
<p>Let's talk through an example. Our product manager wants to show profile data on a user's settings page. Here's how we could engineer that feature request:</p>
<ol>
<li>First, the front-end webpage loads.</li>
<li>The front-end sends an HTTP <code>GET</code> request to a <code>/users</code> endpoint on the back-end server.</li>
<li>The server receives the request.</li>
<li>The server uses a <code>SELECT</code> statement to retrieve the user's record from the <code>users</code> table in the database.</li>
<li>The server converts the row of SQL data into a <code>JSON</code> object and sends it back to the front-end.</li>
</ol>
<h3 id="heading-where-clause">WHERE clause</h3>
<p>In order to keep learning about CRUD operations in SQL, we need to learn how to make the instructions we send to the database more specific. SQL accepts a <code>WHERE</code> statement within a query that allows us to be very specific with our instructions.</p>
<p>If we were unable to specify the specific record we wanted to <code>READ</code>, <code>UPDATE</code>, or <code>DELETE</code> making queries to a database would be very frustrating, and very inefficient.</p>
<h4 id="heading-using-a-where-clause">Using a WHERE clause</h4>
<p>Say we had over 9000 records in our <code>users</code> table. We often want to look at specific user data within that table without retrieving <em>all</em> the other records in the table. We can use a <code>SELECT</code> statement followed by a <code>WHERE</code> clause to specify which records to retrieve. The <code>SELECT</code> statement stays the same, we just add the <code>WHERE</code> clause to the end of the <code>SELECT</code>. </p>
<p>Here's an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> power_level &gt;= <span class="hljs-number">9000</span>;
</code></pre>
<p>This will select only the <code>name</code> field of any user within the <code>users</code> table <code>WHERE</code> the <code>power_level</code> field is greater than or equal to <code>9000</code>.</p>
<h3 id="heading-finding-null-values">Finding NULL values</h3>
<p>You can use a <code>WHERE</code> clause to filter values by whether or not they're <code>NULL</code>.</p>
<h4 id="heading-is-null">IS NULL</h4>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> first_name <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;
</code></pre>
<h4 id="heading-is-not-null">IS NOT NULL</h4>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> first_name <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>;
</code></pre>
<h3 id="heading-delete">DELETE</h3>
<p>When a user deletes their account on Twitter, or deletes a comment on a YouTube video, that data needs to be removed from its respective database.</p>
<h4 id="heading-delete-statement">DELETE statement</h4>
<p>A <code>DELETE</code> statement removes a record from a table that match the <code>WHERE</code> clause. As an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">from</span> employees
    <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = <span class="hljs-number">251</span>;
</code></pre>
<p>This <code>DELETE</code> statement removes all records from the <code>employees</code> table that have an id of <code>251</code>!</p>
<h3 id="heading-the-danger-of-deleting-data">The danger of deleting data</h3>
<p>Deleting data can be a dangerous operation. Once removed, data can be really hard if not impossible to restore! Let's talk about a couple of common ways back-end engineers protect against losing valuable customer data.</p>
<h4 id="heading-strategy-1-backups">Strategy 1 - Backups</h4>
<p>If you're using a cloud-service like GCP's <a target="_blank" href="https://cloud.google.com/sql">Cloud SQL</a> or AWS's <a target="_blank" href="https://aws.amazon.com/rds/">RDS</a> you should <em>always</em> turn on automated backups. They take an automatic snapshot of your entire database on some interval, and keep it around for some length of time.</p>
<p>For example, the Boot.dev database has a backup snapshot taken daily and we retain those backups for 30 days. If I ever accidentally run a query that deletes valuable data, I can restore it from the backup.</p>
<p><strong>You should have a backup strategy for production databases.</strong></p>
<h4 id="heading-strategy-2-soft-deletes">Strategy 2 - Soft deletes</h4>
<p>A "soft delete" is when you don't actually delete data from your database, but instead just "mark" the data as deleted. </p>
<p>For example, you might set a <code>deleted_at</code> date on the row you want to delete. Then, in your queries you ignore anything that has a <code>deleted_at</code> date set. The idea is that this allows your application to behave as if it's deleting data, but you can always go back and restore any data that's been removed.</p>
<p>You should probably only soft-delete if you have a specific reason to do so. Automated backups should be "good enough" for most applications that are just interested in protecting against developer mistakes.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/kCWHniEnQDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-update-query-in-sql">Update query in SQL</h3>
<p>Whenever you update your profile picture or change your password online, you are changing the data in a field on a table in a database. Imagine if every time you accidentally messed up a Tweet on Twitter you had to delete the entire tweet and post a new one instead of just editing it...</p>
<p>...Well, that's a bad example.</p>
<h4 id="heading-update-statement">Update statement</h4>
<p>The <code>UPDATE</code> statement in SQL allows us to update the fields of a record. We can even update many records depending on how we write the statement.</p>
<p>An <code>UPDATE</code> statement specifies the table that needs to be updated, followed by the fields and their new values by using the <code>SET</code> keyword. Lastly a <code>WHERE</code> clause indicates the record(s) to update.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">UPDATE</span> employees
<span class="hljs-keyword">SET</span> job_title = <span class="hljs-string">'Backend Engineer'</span>, salary = <span class="hljs-number">150000</span>
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = <span class="hljs-number">251</span>;
</code></pre>
<h3 id="heading-object-relational-mapping-orms">Object-Relational Mapping (ORMs)</h3>
<p>An <a target="_blank" href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">Object-Relational Mapping</a> or an <em>ORM</em> for short, is a tool that allows you to perform CRUD operations on a database using a traditional programming language. These typically come in the form of a library or framework that you would use in your backend code.</p>
<p>The primary benefit an ORM provides is that it maps your database records to in-memory objects. For example, in Go we might have a struct that we use in our code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
    ID <span class="hljs-keyword">int</span>
    Name <span class="hljs-keyword">string</span>
    IsAdmin <span class="hljs-keyword">bool</span>
}
</code></pre>
<p>This struct definition conveniently represents a database table called <code>users</code>, and an instance of the struct represents a row in the table.</p>
<h4 id="heading-example-using-an-orm">Example: Using an ORM</h4>
<p>Using an ORM we might be able to write simple code like this:</p>
<pre><code class="lang-go">user := User{
    ID: <span class="hljs-number">10</span>,
    Name: <span class="hljs-string">"Lane"</span>,
    IsAdmin: <span class="hljs-literal">false</span>,
}

<span class="hljs-comment">// generates a SQL statement and runs it,</span>
<span class="hljs-comment">// creating a new record in the users table</span>
db.Create(user)
</code></pre>
<h4 id="heading-example-using-straight-sql">Example: Using straight SQL</h4>
<p>Using straight SQL we might have to do something a bit more manual:</p>
<pre><code class="lang-go">user := User{
    ID: <span class="hljs-number">10</span>,
    Name: <span class="hljs-string">"Lane"</span>,
    IsAdmin: <span class="hljs-literal">false</span>,
}

db.Exec(<span class="hljs-string">"INSERT INTO users (id, name, is_admin) VALUES (?, ?, ?);"</span>,
    user.ID, user.Name, user.IsAdmin)
</code></pre>
<h4 id="heading-should-you-use-an-orm">Should you use an ORM?</h4>
<p>That depends – an ORM typically trades simplicity for control.</p>
<p>Using straight SQL you can take full advantage of the power of the SQL language. Using an ORM, you're limited by whatever functionality the ORM has. </p>
<p>If you run into issues with a specific query, it can be harder to debug with an ORM because you have to dig through the framework's code and documentation to figure out how the underlying queries are being generated.</p>
<p>I recommend doing projects both ways so that you can learn about the tradeoffs. At the end of the day, when you're working on a team of developers, it will be a team decision.</p>
<h2 id="heading-chapter-5-basic-sql-queries">Chapter 5: Basic SQL Queries</h2>
<h3 id="heading-how-to-use-the-as-clause-in-sql">How to use the <code>AS</code> Clause in SQL</h3>
<p>Sometimes we need to structure the data we return from our queries in a specific way. An <code>AS</code> clause allows us to "alias" a piece of data in our query. The alias only exists for the duration of the query. </p>
<h4 id="heading-as-keyword"><code>AS</code> keyword</h4>
<p>The following queries return the same data:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> employee_id <span class="hljs-keyword">AS</span> <span class="hljs-keyword">id</span>, employee_name <span class="hljs-keyword">AS</span> <span class="hljs-keyword">name</span>
<span class="hljs-keyword">FROM</span> employees;
</code></pre>
<p>and:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> employee_id, employee_name
<span class="hljs-keyword">FROM</span> employees;
</code></pre>
<p>The difference is that the results from the aliased query would have column names <code>id</code> and <code>name</code> instead of <code>employee_id</code> and <code>employee_name</code>.</p>
<h3 id="heading-sql-functions">SQL Functions</h3>
<p>At the end of the day, SQL is a programming language, and it's one that supports functions. We can use functions and aliases to <em>calculate</em> new columns in a query. This is similar to how you might use formulas in Excel.</p>
<h4 id="heading-iif-function">IIF function</h4>
<p>In SQLite, the <code>IIF</code> function works like a <a target="_blank" href="https://book.pythontips.com/en/latest/ternary_operators.html">ternary</a>. For example:</p>
<pre><code class="lang-SQL">IIF(carA &gt; carB, "Car a is bigger", "Car b is bigger")
</code></pre>
<p>If <code>a</code> is greater than <code>b</code>, this statement evaluates to the string <code>"Car a is bigger"</code>. Otherwise, it evaluates to <code>"Car b is bigger"</code>.</p>
<p>Here's how we can use <code>IIF()</code> and a <code>directive</code> alias to add a new calculated column to our result set:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> quantity,
    <span class="hljs-keyword">IIF</span>(quantity &lt; <span class="hljs-number">10</span>, <span class="hljs-string">"Order more"</span>, <span class="hljs-string">"In Stock"</span>) <span class="hljs-keyword">AS</span> directive
    <span class="hljs-keyword">from</span> products
</code></pre>
<h3 id="heading-how-to-use-between-with-where">How to Use <code>BETWEEN</code> with <code>WHERE</code></h3>
<p>We can check if certain values are <code>between</code> two numbers using the <code>WHERE</code> clause in an intuitive way. The <code>WHERE</code> clause doesn't always have to be used to specify specific id's or values. We can also use it to help narrow down our result set. Here's an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> employee_name, salary
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">WHERE</span> salary <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">30000</span> <span class="hljs-keyword">and</span> <span class="hljs-number">60000</span>;
</code></pre>
<p>This query returns all the employees <code>name</code> and <code>salary</code> fields for any rows where the <code>salary</code> is <code>BETWEEN</code> 30,000 and 60,000. We can also query results that are <code>NOT BETWEEN</code> two specified values. </p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, quantity
<span class="hljs-keyword">FROM</span> products
<span class="hljs-keyword">WHERE</span> quantity <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">20</span> <span class="hljs-keyword">and</span> <span class="hljs-number">100</span>;
</code></pre>
<p>This query returns all the product names where the quantity was not between <code>20</code> and <code>100</code>. We can use conditionals to make the results of our query as specific as we need them to be.</p>
<h3 id="heading-how-to-return-distinct-values">How to return distinct values</h3>
<p>Sometimes we want to retrieve records from a table without getting back any duplicates.</p>
<p>For example, we may want to know all the different companies our employees have worked at previously, but we don't want to see the same company multiple times in the report.</p>
<h4 id="heading-select-distinct"><code>SELECT DISTINCT</code></h4>
<p>SQL offers us the <code>DISTINCT</code> keyword that removes duplicate records from the resulting query.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DISTINCT</span> previous_company
    <span class="hljs-keyword">FROM</span> employees;
</code></pre>
<p>This only returns one row for each unique <code>previous_company</code> value.</p>
<h3 id="heading-logical-operators">Logical Operators</h3>
<p>We often need to use multiple conditions to retrieve the exact information we want. We can begin to structure much more complex queries by using multiple conditions together to narrow down the search results of our query.</p>
<p>The logical <code>AND</code> operator can be used to narrow down our result sets even more.</p>
<h4 id="heading-and-operator"><code>AND</code> operator</h4>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, quantity, shipment_status
    <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> shipment_status = <span class="hljs-string">'pending'</span>
    <span class="hljs-keyword">AND</span> quantity <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> <span class="hljs-number">10</span>;
</code></pre>
<p>This only retrieves records where both the <code>shipment_status</code> is "pending" AND the <code>quantity</code> is between <code>0</code> and <code>10</code>.</p>
<h4 id="heading-equality-operators">Equality operators</h4>
<p>All of the following operators are supported in SQL. The <code>=</code> is the main one to watch out for, it's not <code>==</code> like in many other languages.</p>
<ul>
<li><code>=</code></li>
<li><code>&lt;</code></li>
<li><code>&gt;</code></li>
<li><code>&lt;=</code></li>
<li><code>&gt;=</code></li>
</ul>
<p>For example, in Python you might compare two values like this:</p>
<pre><code class="lang-py"><span class="hljs-keyword">if</span> name == <span class="hljs-string">"age"</span>
</code></pre>
<p>Whereas in SQL you would do:</p>
<pre><code class="lang-sql">WHERE name = "age"
</code></pre>
<h4 id="heading-or-operator"><code>OR</code> operator</h4>
<p>As you've probably guessed, if the logical <code>AND</code> operator is supported, the <code>OR</code> operator is probably supported as well.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, quantity, shipment_status
    <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> shipment_status = <span class="hljs-string">'out of stock'</span>
    <span class="hljs-keyword">OR</span> quantity <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">10</span> <span class="hljs-keyword">and</span> <span class="hljs-number">100</span>;
</code></pre>
<p>This query retrieves records where either the shipment_status <code>condition</code> OR the <code>quantity</code> condition are met.</p>
<p>Order of operations matter when using these operators.</p>
<p>You can group logical operations with parentheses to specify the <a target="_blank" href="https://www.mathsisfun.com/operation-order-pemdas.html">order of operations</a>.</p>
<pre><code class="lang-sql">(this AND that) OR the_other
</code></pre>
<h4 id="heading-the-in-operator">The <code>IN</code> operator</h4>
<p>Another variation to the <code>WHERE</code> clause we can utilize is the <code>IN</code> operator. <code>IN</code> returns <code>true</code> or <code>false</code> if the first operand matches any of the values in the second operand. The <code>IN</code> operator is a shorthand for multiple <code>OR</code> conditions.</p>
<p>These two queries are equivalent:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, shipment_status
    <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> shipment_status <span class="hljs-keyword">IN</span> (<span class="hljs-string">'shipped'</span>, <span class="hljs-string">'preparing'</span>, <span class="hljs-string">'out of stock'</span>);
</code></pre>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, shipment_status
    <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> shipment_status = <span class="hljs-string">'shipped'</span>
        <span class="hljs-keyword">OR</span> shipment_status = <span class="hljs-string">'preparing'</span>
        <span class="hljs-keyword">OR</span> shipment_status = <span class="hljs-string">'out of stock'</span>;
</code></pre>
<p>Hopefully, you're starting to see how querying specific data using fine-tuned SQL clauses helps reveal important insights. The larger a table becomes the harder it becomes to analyze without proper queries.</p>
<h4 id="heading-the-like-keyword">The <code>LIKE</code> keyword</h4>
<p>Sometimes we don't have the luxury of knowing exactly what it is we need to query. Have you ever wanted to look up a song or a video but you only remember part of the name? SQL provides us an option for when we're in situations <code>LIKE</code> this.</p>
<p>The <code>LIKE</code> keyword allows for the use of the <code>%</code> and <code>_</code> wildcard operators. Let's focus on <code>%</code> first.</p>
<h4 id="heading-operator"><code>%</code> Operator</h4>
<p>The <code>%</code> operator will match zero or more characters. We can use this operator within our query string to find more than just exact matches depending on where we place it.</p>
<p>Here are some examples that show how these work:</p>
<p>Product starts with "banana":</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> products
<span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'banana%'</span>;
</code></pre>
<p>Product ends with "banana":</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">from</span> products
<span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'%banana'</span>;
</code></pre>
<p>Product contains "banana":</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">from</span> products
<span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'%banana%'</span>;
</code></pre>
<h3 id="heading-underscore-operator">Underscore Operator</h3>
<p>As discussed, the <code>%</code> wildcard operator matches zero or more characters. Meanwhile, the <code>_</code> wildcard operator only matches a single character.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'_oot'</span>;
</code></pre>
<p>The query above matches products like:</p>
<ul>
<li>boot</li>
<li>root</li>
<li>foot</li>
</ul>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'__oot'</span>;
</code></pre>
<p>The query above matches products like:</p>
<ul>
<li>shoot</li>
<li>groot</li>
</ul>
<h2 id="heading-chapter-6-how-to-structure-return-data-in-sql">Chapter 6: How to Structure Return Data in SQL</h2>
<h3 id="heading-the-limit-keyword">The <code>LIMIT</code> keyword</h3>
<p>Sometimes we don't want to retrieve every record from a table. For example, it's common for a production database table to have millions of rows, and <code>SELECT</code>ing all of them might crash your system. This is where the <code>LIMIT</code> keyword enters the chat.</p>
<p>The <code>LIMIT</code> keyword can be used at the end of a select statement to reduce the number of records returned.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">WHERE</span> product_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'%berry%'</span>
    <span class="hljs-keyword">LIMIT</span> <span class="hljs-number">50</span>;
</code></pre>
<p>The query above retrieves all the records from the <code>products</code> table where the name contains the word berry. If we ran this query on the Facebook database, it would almost certainly return a lot of records. </p>
<p>The <code>LIMIT</code> statement only allows the database to return up to 50 records matching the query. This means that if there aren't that many records matching the query, the <code>LIMIT</code> statement will not have an effect.</p>
<h3 id="heading-the-sql-order-by-keyword">The SQL <code>ORDER BY</code> keyword</h3>
<p>SQL also offers us the ability to sort the results of a query using <code>ORDER BY</code>. By default, the <code>ORDER BY</code> keyword sorts records by the given field in ascending order, or <code>ASC</code> for short. However, <code>ORDER BY</code> does support descending order as well with the keyword <code>DESC</code>.</p>
<h4 id="heading-examples">Examples</h4>
<p>This query returns the <code>name</code>, <code>price</code>, and <code>quantity</code> fields from the <code>products</code> table sorted by <code>price</code> in ascending order:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span>, price, quantity <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> price;
</code></pre>
<p>This query returns the <code>name</code>, <code>price</code>, and <code>quantity</code> of the products ordered by the quantity in descending order:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span>, price, quantity <span class="hljs-keyword">FROM</span> products
    <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> quantity <span class="hljs-keyword">desc</span>;
</code></pre>
<h3 id="heading-order-by-and-limit">Order By and Limit</h3>
<p>When using both <code>ORDER BY</code> and <code>LIMIT</code>, the <code>ORDER BY</code> clause must come first.</p>
<h2 id="heading-chapter-7-how-to-perform-aggregations-in-sql">Chapter 7: How to Perform Aggregations in SQL</h2>
<p>An "aggregation" is a single value that's derived by combining several other values. We performed an aggregation earlier when we used the <code>count</code> statement to count the number of records in a table.</p>
<h3 id="heading-why-use-aggregations">Why use aggregations?</h3>
<p>Data stored in a database should generally be stored <a target="_blank" href="https://wagslane.dev/posts/keep-your-data-raw-at-rest/">raw</a>. When we need to calculate some additional data from the raw data, we can use an aggregation.</p>
<p>Take the following <code>count</code> aggregation as an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">COUNT</span>(*)
<span class="hljs-keyword">FROM</span> products
<span class="hljs-keyword">WHERE</span> quantity = <span class="hljs-number">0</span>;
</code></pre>
<p>This query returns the number of products that have a <code>quantity</code> of <code>0</code>. We could store a count of the products in a separate database table, and increment/decrement it whenever we make changes to the <code>products</code> table - but that would be redundant. </p>
<p>It's much simpler to store the products in a single place (we call this a <a target="_blank" href="https://en.wikipedia.org/wiki/Single_source_of_truth">single source of truth</a>) and run an aggregation when we need to derive additional information from the raw data.</p>
<h3 id="heading-the-sum-function">The <code>SUM</code> function</h3>
<p>The <code>sum</code> aggregation function returns the sum of a set of values.</p>
<p>For example, the query below returns a single record containing a single field. The returned value is equal to the total salary being collected by all of the <code>employees</code> in the <code>employees</code> table.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">sum</span>(salary)
<span class="hljs-keyword">FROM</span> employees;
</code></pre>
<p>Which returns:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>SUM(SALARY)</td></tr>
</thead>
<tbody>
<tr>
<td>2483</td></tr>
</tbody>
</table>
</div><h3 id="heading-the-max-function">The <code>MAX</code> function</h3>
<p>As you may expect, the <code>max</code> function retrieves the <em>largest</em> value from a set of values. For example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">max</span>(price)
<span class="hljs-keyword">FROM</span> products
</code></pre>
<p>This query looks through all of the prices in the <code>products</code> table and returns the price with the largest price value. Remember it only returns the <code>price</code>, not the rest of the record. You always need to specify each field you want a query to return.</p>
<h4 id="heading-a-note-on-schema">A note on schema</h4>
<ul>
<li>The <code>sender_id</code> will be present for any transactions where the user in question (<code>user_id</code>) is receiving money (from the sender).</li>
<li>The <code>recipient_id</code> will be present for any transactions where the user in question (<code>user_id</code>) is sending money (to the recipient).</li>
</ul>
<p>In other words, a transaction can only have a <code>sender_id</code> or a <code>recipient_id</code> - not both. The presence of one or the other indicates whether money is going into or out of the user's account.</p>
<p>This <code>user_id</code>, <code>recipient_id</code>, <code>sender_id</code> schema we've designed is only one way to design a transactions database - there are other valid ways to do it. It's the one we're using, and later we'll talk more about the tradeoffs in different database design options.</p>
<h3 id="heading-the-min-function">The <code>MIN</code> function</h3>
<p>The <code>min</code> function works the same as the <code>max</code> function but finds the lowest value instead of the highest value.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> product_name, <span class="hljs-keyword">min</span>(price)
<span class="hljs-keyword">from</span> products;
</code></pre>
<p>This query returns the <code>product_name</code> and the <code>price</code> fields of the record with the lowest <code>price</code>.</p>
<h3 id="heading-the-group-by-clause">The <code>GROUP BY</code> clause</h3>
<p>There are times we need to group data based on specific values.</p>
<p>SQL offers the <code>GROUP BY</code> clause which can group rows that have similar values into "summary" rows. It returns one row for each group. The interesting part is that each group can have an aggregate function applied to it that operates only on the grouped data.</p>
<h4 id="heading-example-of-group-by">Example of <code>GROUP BY</code></h4>
<p>Imagine that we have a database with songs and albums, and we want to see how many songs are on each album. We can use a query like this:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> album_id, <span class="hljs-keyword">count</span>(song_id)
<span class="hljs-keyword">FROM</span> songs
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> album_id;
</code></pre>
<p>This query retrieves a count of all the songs on each album. One record is returned per album, and they each have their own <code>count</code>.</p>
<h3 id="heading-the-avg-function">The <code>AVG()</code> function</h3>
<p>Just like we may want to find the minimum or maximum values within a dataset, sometimes we need to know the <a target="_blank" href="https://en.wikipedia.org/wiki/Arithmetic_mean">average</a>!</p>
<p>SQL offers us the <code>AVG()</code> function. Similar to <code>MAX()</code>, <code>AVG()</code> calculates the average of all non-NULL values. </p>
<pre><code class="lang-SQL"><span class="hljs-keyword">select</span> song_name, <span class="hljs-keyword">avg</span>(song_length)
<span class="hljs-keyword">from</span> songs
</code></pre>
<p>This query returns the average <code>song_length</code> in the <code>songs</code> table.</p>
<h3 id="heading-the-having-clause">The <code>HAVING</code> clause</h3>
<p>When we need to filter the results of a <code>GROUP BY</code> query even further, we can use the <code>HAVING</code> clause. The <code>HAVING</code> clause specifies a search condition for a group.</p>
<p>The <code>HAVING</code> clause is similar to the <code>WHERE</code> clause, but it operates on groups after they've been grouped, rather than rows before they've been grouped.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> album_id, <span class="hljs-keyword">count</span>(<span class="hljs-keyword">id</span>) <span class="hljs-keyword">as</span> <span class="hljs-keyword">count</span>
<span class="hljs-keyword">FROM</span> songs
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> album_id
<span class="hljs-keyword">HAVING</span> <span class="hljs-keyword">count</span> &gt; <span class="hljs-number">5</span>;
</code></pre>
<p>This query returns the <code>album_id</code> and count of its songs, but only for albums with more than <code>5</code> songs.</p>
<h3 id="heading-having-vs-where-in-sql"><code>HAVING</code> vs <code>WHERE</code> in SQL</h3>
<p>It's fairly common for developers to get confused about the difference between the <code>HAVING</code> and the <code>WHERE</code> clauses - they're pretty similar after all.</p>
<p>The difference is fairly simple in actuality:</p>
<ul>
<li>A <code>WHERE</code> condition is applied to all the data in a query before it's grouped by a <code>GROUP BY</code> clause.</li>
<li>A <code>HAVING</code> condition is only applied to the grouped rows that are returned after a <code>GROUP BY</code> is applied.</li>
</ul>
<p>This means that if you want to filter on the result of an aggregation, you need to use <code>HAVING</code>. If you want to filter on a value that's present in the raw data, you should use a simple <code>WHERE</code> clause.</p>
<h3 id="heading-the-round-function">The <code>ROUND</code> function</h3>
<p>Sometimes we need to <a target="_blank" href="https://en.wikipedia.org/wiki/Rounding">round</a> some numbers, particularly when working with the results of an aggregation. We can use the <code>ROUND()</code> function to get the job done.</p>
<p>The SQL <code>round()</code> function allows you to specify both the value you wish to round and the precision to which you wish to round it:</p>
<pre><code class="lang-SQL">round(value, precision)
</code></pre>
<p>If no precision is given, SQL will round the value to the nearest whole value:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">select</span> song_name, <span class="hljs-keyword">round</span>(<span class="hljs-keyword">avg</span>(song_length), <span class="hljs-number">1</span>)
<span class="hljs-keyword">from</span> songs
</code></pre>
<p>This query returns the average <code>song_length</code> from the <code>songs</code> table, rounded to a single decimal point.</p>
<h2 id="heading-chapter-8-sql-subqueries">Chapter 8: SQL Subqueries</h2>
<h3 id="heading-subqueries">Subqueries</h3>
<p>Sometimes a single query is not enough to retrieve the specific records we need.</p>
<p>It is possible to run a query on the result set of another query - a query within a query! This is called "query-ception"... erm... I mean a "subquery".</p>
<p>Subqueries can be very useful in a number of situations when trying to retrieve specific data that wouldn't be accessible by simply querying a single table.</p>
<h4 id="heading-how-to-retreive-data-from-multiple-tables">How to retreive data from multiple tables</h4>
<p>Here is an example of a subquery:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span>, song_name, artist_id
<span class="hljs-keyword">FROM</span> songs
<span class="hljs-keyword">WHERE</span> artist_id <span class="hljs-keyword">IN</span> (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span>
    <span class="hljs-keyword">FROM</span> artists
    <span class="hljs-keyword">WHERE</span> artist_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'Rick%'</span>
);
</code></pre>
<p>In this hypothetical database, the query above selects all of the <code>song_id</code>s, <code>song_name</code>s, and <code>artist_id</code>s from the <code>songs</code> table that are written by artists whose name starts with "Rick". Notice that the subquery allows us to use information from a different table - in this case the <code>artists</code> table.</p>
<h4 id="heading-subquery-syntax">Subquery syntax</h4>
<p>The only syntax unique to a subquery is the parentheses surrounding the nested query. The <code>IN</code> operator could be different, for example, we could use the <code>=</code> operator if we expect a single value to be returned.</p>
<p>Here's an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span>, song_name, artist_id
<span class="hljs-keyword">FROM</span> songs
<span class="hljs-keyword">WHERE</span> artist_id <span class="hljs-keyword">IN</span> (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">id</span>
    <span class="hljs-keyword">FROM</span> artists
    <span class="hljs-keyword">WHERE</span> artist_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'Rick%'</span>
);
</code></pre>
<h3 id="heading-no-tables-necessary">No tables necessary</h3>
<p>When working on a back-end application, this doesn't come up often, but it's important to remember that <strong>SQL is a full programming language</strong>. We usually use it to interact with data stored in tables, but it's quite flexible and powerful.</p>
<p>For example, you can <code>SELECT</code> information that's simply calculated, with no tables necessary.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-number">5</span> + <span class="hljs-number">10</span> <span class="hljs-keyword">as</span> <span class="hljs-keyword">sum</span>;
</code></pre>
<h2 id="heading-chapter-9-database-normalization">Chapter 9: Database Normalization</h2>
<h3 id="heading-table-relationships">Table Relationships</h3>
<p>Relational databases are powerful because of the relationships between the tables. These relationships help us to keep our databases clean and efficient. </p>
<p>A relationship between tables assumes that one of these tables has a <code>foreign key</code> that references the <code>primary key</code> of another table.</p>
<p>@<a target="_blank" href="https://www.youtube.com/watch?v=WJTdg1AsSz0">youtube</a></p>
<h4 id="heading-types-of-relationships">Types of Relationships</h4>
<p>There are 3 primary types of relationships in a relational database:</p>
<ol>
<li>One-to-one</li>
<li>One-to-many</li>
<li>Many-to-many</li>
</ol>
<p><img src="https://i.imgur.com/u4i6XdL.png" alt="relationships" width="763" height="340" loading="lazy"></p>
<h3 id="heading-one-to-one">One-to-one</h3>
<p>A <code>one-to-one</code> relationship most often manifests as a field or set of fields on a row in a table. For example, a <code>user</code> will have exactly one <code>password</code>.</p>
<p>Settings fields might be another example of a one-to-one relationship. A user will have exactly one <code>email_preference</code> and exactly one <code>birthday</code>.</p>
<h3 id="heading-one-to-many">One to many</h3>
<p>When talking about the relationships between tables, a one-to-many relationship is probably the most commonly used relationship. </p>
<p>A one-to-many relationship occurs when a single record in one table is related to potentially many records in another table. </p>
<p>Note that the one-&gt;many relation only goes one way, a record in the second table can not be related to multiple records in the first table!</p>
<h4 id="heading-examples-of-one-to-many-relationships">Examples of one-to-many relationships</h4>
<ul>
<li>A <code>customers</code> table and a <code>orders</code> table. Each customer has <code>0</code>, <code>1</code>, or many orders that they've placed.</li>
<li>A <code>users</code> table and a <code>transactions</code> table. Each <code>user</code> has <code>0</code>, <code>1</code>, or many transactions that taken part in.</li>
</ul>
<h3 id="heading-many-to-many">Many to many</h3>
<p>A many-to-many relationship occurs when multiple records in one table can be related to multiple records in another table.</p>
<h4 id="heading-examples-of-many-to-many-relationships">Examples of many-to-many relationships</h4>
<ul>
<li>A <code>products</code> table and a <code>suppliers</code> table - Products may have <code>0</code> to many suppliers, and suppliers can supply <code>0</code> to many products.</li>
<li>A <code>classes</code> table and a <code>students</code> table - Students can take potentially many classes and classes can have many students enrolled.</li>
</ul>
<h4 id="heading-joining-tables">Joining tables</h4>
<p>Joining tables helps define many-to-many relationships between data in a database. As an example, when defining the relationship above between products and suppliers, we would define a joining table called <code>products_suppliers</code> that contains the primary keys from the tables to be joined.</p>
<p>Then, when we want to see if a supplier supplies a specific product, we can look in the joining table to see if the ids share a row.</p>
<h4 id="heading-unique-constraints-across-2-fields">Unique constraints across 2 fields</h4>
<p>When enforcing specific schema constraints we may need to enforce the <code>UNIQUE</code> constraint across two different fields.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> product_suppliers (
  product_id <span class="hljs-built_in">INTEGER</span>,
  supplier_id <span class="hljs-built_in">INTEGER</span>,
  <span class="hljs-keyword">UNIQUE</span>(product_id, supplier_id)
);
</code></pre>
<p>This ensures that we can have multiple rows with the same <code>product_id</code> or <code>supplier_id</code>, but we can't have two rows where both the <code>product_id</code> and <code>supplier_id</code> are the same.</p>
<h3 id="heading-database-normalization">Database normalization</h3>
<p>Database normalization is a method for structuring your database schema in a way that helps:</p>
<ul>
<li>Improve data integrity</li>
<li>Reduce data redundancy</li>
</ul>
<h4 id="heading-what-is-data-integrity">What is data integrity?</h4>
<p>"Data integrity" refers to the accuracy and consistency of data. For example, if a user's age is stored in a database, rather than their birthday, that data becomes incorrect automatically with the passage of time.</p>
<p>It would be better to store a birthday and calculate the age as needed.</p>
<h4 id="heading-what-is-data-redundancy">What is data redundancy?</h4>
<p>"Data redundancy" occurs when the same piece of data is stored in multiple places. For example: saving the same file multiple times to different hard drives.</p>
<p>Data redundancy can be problematic, especially when data in one place is changed such that the data is no longer consistent across all copies of that data.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/U3L4NYNwb6k" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-normal-forms">Normal Forms</h3>
<p>The creator of "database normalization", <a target="_blank" href="https://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F. Codd</a>, described different "normal forms" a database can adhere to. We'll talk about the most common ones.</p>
<ul>
<li>First normal form (1NF)</li>
<li>Second normal form (2NF)</li>
<li>Third normal form (3NF)</li>
<li>Boyce-Codd normal form (BCNF)</li>
</ul>
<p><img src="https://i.imgur.com/CpDOeej.png" alt="normal forms" width="300" height="275" loading="lazy"></p>
<p>In short, 1st normal form is the least "normalized" form, and Boyce-Codd is the most "normalized" form.</p>
<p>The more normalized a database, the better its data integrity, and the less duplicate data you'll have.</p>
<h4 id="heading-in-the-context-of-normal-forms-primary-key-means-something-a-bit-different">In the context of normal forms, "primary key" means something a bit different</h4>
<p>In the context of database normalization, we're going to use the term "primary key" slightly differently. When we're talking about SQLite, a "primary key" is a single column that uniquely identifies a row.</p>
<p>When we're talking more generally about data normalization, the term "primary key" means the collection of columns that uniquely identify a row. That can be a single column, but it can actually be any number of columns. A primary key is the minimum number of columns needed to uniquely identify a row in a table. </p>
<p>If you think back to the many-to-many joining table <code>product_suppliers</code>, that table's "primary key" was actually a combination of the 2 ids, <code>product_id</code> and <code>supplier_id</code>:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> product_suppliers (
    product_id <span class="hljs-built_in">INTEGER</span>,
    supplier_id <span class="hljs-built_in">INTEGER</span>,
    <span class="hljs-keyword">UNIQUE</span>(product_id, supplier_id)
);
</code></pre>
<h3 id="heading-1st-normal-form-1nf">1st Normal Form (1NF)</h3>
<p>To be compliant with <a target="_blank" href="https://en.wikipedia.org/wiki/First_normal_form">first normal form</a>, a database table simply needs to follow 2 rules:</p>
<ul>
<li>It must have a unique primary key.</li>
<li>A cell can't have a nested table as its value (depending on the database you're using, this may not even be possible)</li>
</ul>
<h4 id="heading-example-of-not-1st-normal-form">Example of NOT 1st normal form</h4>
<div class="hn-table">
<table>
<thead>
<tr>
<td>name</td><td>age</td><td>email</td></tr>
</thead>
<tbody>
<tr>
<td>Lane</td><td>27</td><td>lane@boot.dev</td></tr>
<tr>
<td>Lane</td><td>27</td><td>lane@boot.dev</td></tr>
<tr>
<td>Allan</td><td>27</td><td>allan@boot.dev</td></tr>
</tbody>
</table>
</div><p>This table does not adhere to 1NF. It has two identical rows, so there isn't a unique primary key for each row.</p>
<h4 id="heading-example-of-1st-normal-form">Example of 1st normal form</h4>
<p>The simplest way (but not the only way) to get into first normal form is to add a unique <code>id</code> column.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>id</td><td>name</td><td>age</td><td>email</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>Lane</td><td>27</td><td>lane@boot.dev</td></tr>
<tr>
<td>2</td><td>Lane</td><td>27</td><td>lane@boot.dev</td></tr>
<tr>
<td>3</td><td>Allan</td><td>27</td><td>allan@boot.dev</td></tr>
</tbody>
</table>
</div><p>It's worth noting that if you create a "primary key" by ensuring that two columns are always "unique together" that works too.</p>
<h4 id="heading-you-should-almost-never-design-a-table-that-doesnt-adhere-to-1nf">You should <em>almost</em> never design a table that doesn't adhere to 1NF</h4>
<p>First normal form is simply a good idea. I've never built a database schema where each table isn't at least in first normal form.</p>
<h3 id="heading-2nd-normal-form-2nf">2nd Normal Form (2NF)</h3>
<p>A table in <a target="_blank" href="https://en.wikipedia.org/wiki/Second_normal_form">second normal form</a> follows all the rules of 1st normal form, and one additional rule:</p>
<ul>
<li>All columns that are not part of the primary key are dependent on the entire primary key, and not just one of the columns in the primary key.</li>
</ul>
<h4 id="heading-example-of-1st-nf-but-not-2nd-nf">Example of 1st NF, but not 2nd NF</h4>
<p>In this table, the primary key is a combination of <code>first_name</code> + <code>last_name</code>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>first_name</td><td>last_name</td><td>first_initial</td></tr>
</thead>
<tbody>
<tr>
<td>Lane</td><td>Wagner</td><td>l</td></tr>
<tr>
<td>Lane</td><td>Small</td><td>l</td></tr>
<tr>
<td>Allan</td><td>Wagner</td><td>a</td></tr>
</tbody>
</table>
</div><p>This table does not adhere to 2NF. The <code>first_initial</code> column is entirely dependent on the <code>first_name</code> column, rendering it redundant.</p>
<h4 id="heading-example-of-2nd-normal-form">Example of 2nd normal form</h4>
<p>One way to convert the table above to 2NF is to add a new table that maps a <code>first_name</code> directly to its <code>first_initial</code>. This removes any duplicates:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>first_name</td><td>last_name</td></tr>
</thead>
<tbody>
<tr>
<td>Lane</td><td>Wagner</td></tr>
<tr>
<td>Lane</td><td>Small</td></tr>
<tr>
<td>Allan</td><td>Wagner</td></tr>
</tbody>
</table>
</div><div class="hn-table">
<table>
<thead>
<tr>
<td>first_name</td><td>first_initial</td></tr>
</thead>
<tbody>
<tr>
<td>Lane</td><td>l</td></tr>
<tr>
<td>Allan</td><td>a</td></tr>
</tbody>
</table>
</div><h4 id="heading-2nf-is-usually-a-good-idea">2NF is <em>usually</em> a good idea</h4>
<p>You should probably default to keeping your tables in second normal form. That said, there are good reasons to deviate from it, particularly for performance reasons. The reason being that when you have query a second table to get additional data it can take a bit longer.</p>
<p>My rule of thumb is:</p>
<blockquote>
<p>Optimize for data integrity and data de-duplication first. If you have speed issues, de-normalize accordingly.</p>
</blockquote>
<h3 id="heading-3rd-normal-form-3nf">3rd Normal Form (3NF)</h3>
<p>A table in <a target="_blank" href="https://en.wikipedia.org/wiki/Third_normal_form">3rd normal form</a> follows all the rules of 2nd normal form, and one additional rule:</p>
<ul>
<li>All columns that aren't part of the primary are dependent solely on the primary key.</li>
</ul>
<p>Notice that this is only slightly different from second normal form. In second normal form we can't have a column completely dependent on a part of the primary key, and in third normal form we can't have a column that is entirely dependent on anything that isn't the entire primary key.</p>
<h4 id="heading-example-of-2nd-nf-but-not-3rd-nf">Example of 2nd NF, but not 3rd NF</h4>
<p>In this table, the primary key is simply the <code>id</code> column.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>id</td><td>name</td><td>first_initial</td><td>email</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>Lane</td><td>l</td><td>lane.works@example.com</td></tr>
<tr>
<td>2</td><td>Breanna</td><td>b</td><td>breanna@example.com</td></tr>
<tr>
<td>3</td><td>Lane</td><td>l</td><td>lane.right@example.com</td></tr>
</tbody>
</table>
</div><p>This table is in 2nd normal form because <code>first_initial</code> is not dependent on a part of the primary key. However, because it is dependent on the <code>name</code> column it doesn't adhere to 3rd normal form.</p>
<h4 id="heading-example-of-3rd-normal-form">Example of 3rd normal form</h4>
<p>The way to convert the table above to 3NF is to add a new table that maps a <code>name</code> directly to its <code>first_initial</code>. Notice how similar this solution is to 2NF.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>id</td><td>name</td><td>email</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>Lane</td><td>lane.works@example.com</td></tr>
<tr>
<td>2</td><td>Breanna</td><td>breanna@example.com</td></tr>
<tr>
<td>3</td><td>Lane</td><td>lane.right@example.com</td></tr>
</tbody>
</table>
</div><div class="hn-table">
<table>
<thead>
<tr>
<td>name</td><td>first_initial</td></tr>
</thead>
<tbody>
<tr>
<td>Lane</td><td>l</td></tr>
<tr>
<td>Breanna</td><td>b</td></tr>
</tbody>
</table>
</div><h4 id="heading-3nf-is-usually-a-good-idea">3NF is <em>usually</em> a good idea</h4>
<p>The same exact rule of thumb applies to the second and third normal forms.</p>
<blockquote>
<p>Optimize for data integrity and data de-duplication first by adhering to 3NF. If you have speed issues, de-normalize accordingly.</p>
</blockquote>
<p>Remember the <a target="_blank" href="https://www.sqlitetutorial.net/sqlite-functions/sqlite-iif/">IIF function</a> and the <code>AS</code> clause.</p>
<h3 id="heading-boyce-codd-normal-form-bcnf">Boyce-Codd Normal Form (BCNF)</h3>
<p>A table in <a target="_blank" href="https://en.wikipedia.org/wiki/Boyce%E2%80%93Codd_normal_form">Boyce-Codd normal form</a> (created by <a target="_blank" href="https://en.wikipedia.org/wiki/Raymond_F._Boyce">Raymond F Boyce</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F Codd</a>) follows all the rules of 3rd normal form, plus one additional rule:</p>
<ul>
<li>A column that's part of a primary key can not be entirely dependent on a column that's not part of that primary key.</li>
</ul>
<p>This only comes into play when there are multiple possible primary key combinations that overlap. Another name for this is "overlapping candidate keys".</p>
<p>Only in rare cases does a table in third normal form not meet the requirements of Boyce-Codd normal form.</p>
<h4 id="heading-example-of-3rd-nf-but-not-boyce-codd-nf">Example of 3rd NF, but not Boyce-Codd NF</h4>
<div class="hn-table">
<table>
<thead>
<tr>
<td>release_year</td><td>release_date</td><td>sales</td><td>name</td></tr>
</thead>
<tbody>
<tr>
<td>2001</td><td>2001-01-02</td><td>100</td><td>Kiss me tender</td></tr>
<tr>
<td>2001</td><td>2001-02-04</td><td>200</td><td>Bloody Mary</td></tr>
<tr>
<td>2002</td><td>2002-04-14</td><td>100</td><td>I wanna be them</td></tr>
<tr>
<td>2002</td><td>2002-06-24</td><td>200</td><td>He got me</td></tr>
</tbody>
</table>
</div><p>The interesting thing here is that there are 3 possible primary keys:</p>
<ul>
<li><code>release_year</code> + <code>sales</code></li>
<li><code>release_date</code> + <code>sales</code></li>
<li><code>name</code></li>
</ul>
<p>This means that by definition this table is in 2nd and 3rd normal form because those forms only restrict how dependent a column that is not part of a primary key can be.</p>
<p>This table is not in Boyce-Codd's normal form because <code>release_year</code> is entirely dependent on <code>release_date</code>.</p>
<h4 id="heading-example-of-boyce-codd-normal-form">Example of Boyce-Codd normal form</h4>
<p>The easiest way to fix the table in our example is to simply remove the duplicate data from <code>release_date</code>. Let's make that column <code>release_day_and_month</code>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>release_year</td><td>release_day_and_month</td><td>sales</td><td>name</td></tr>
</thead>
<tbody>
<tr>
<td>2001</td><td>01-02</td><td>100</td><td>Kiss me tender</td></tr>
<tr>
<td>2001</td><td>02-04</td><td>200</td><td>Bloody Mary</td></tr>
<tr>
<td>2002</td><td>04-14</td><td>100</td><td>I wanna be them</td></tr>
<tr>
<td>2002</td><td>06-24</td><td>200</td><td>He got me</td></tr>
</tbody>
</table>
</div><h4 id="heading-bcnf-is-usually-a-good-idea">BCNF is <em>usually</em> a good idea</h4>
<p>The same exact rule of thumb applies to the 2nd, 3rd and Boyce-Codd normal forms. That said, it's unlikely you'll see BCNF-specific issues in practice.</p>
<blockquote>
<p>Optimize for data integrity and data de-duplication first by adhering to Boyce-Codd normal form. If you have speed issues, de-normalize accordingly.</p>
</blockquote>
<h3 id="heading-normalization-review">Normalization Review</h3>
<p>In my opinion, the exact definitions of 1st, 2nd, 3rd and Boyce-Codd normal forms simply are not all that important in your work as a back-end developer.</p>
<p>However, what is important is to understand the basic principles of data integrity and data redundancy that the normal forms teach us. </p>
<p>Let's go over some rules of thumb that you should commit to memory - they'll serve you well when you design databases and even just in coding interviews.</p>
<h4 id="heading-rules-of-thumb-for-database-design">Rules of thumb for database design</h4>
<ol>
<li>Every table should always have a unique identifier (primary key)</li>
<li>90% of the time, that unique identifier will be a single column named <code>id</code></li>
<li>Avoid duplicate data</li>
<li>Avoid storing data that is completely dependent on other data. Instead, compute it on the fly when you need it.</li>
<li>Keep your schema as simple as you can. Optimize for a normalized database first. Only denormalize for speed's sake when you start to run into performance problems.</li>
</ol>
<p>We'll talk more about speed optimization in a later chapter.</p>
<h2 id="heading-chapter-10-how-to-join-tables-in-sql">Chapter 10: How to Join Tables in SQL</h2>
<p>Joins are one of the most important features that SQL offers. Joins allow us to make use of the relationships we have set up between our tables. In short, joins allow us to query multiple tables at the same time.</p>
<h3 id="heading-inner-join"><code>INNER JOIN</code></h3>
<p>The simplest and most common type of join in SQL is the <code>INNER JOIN</code>. By default, a <code>JOIN</code> command is an <code>INNER JOIN</code>. </p>
<p>An <code>INNER JOIN</code> returns all of the records in <code>table_a</code> that have matching records in <code>table_b</code>, as demonstrated by the following Venn diagram.</p>
<p><img src="https://i.imgur.com/wgxAmhA.png" alt="inner join" width="421" height="293" loading="lazy"></p>
<h4 id="heading-the-on-clause">The <code>ON</code> clause</h4>
<p>In order to perform a join, we need to tell the database which fields should be "matched up". The  <code>ON</code> clause is used to specify these columns to join.</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> *
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> departments 
<span class="hljs-keyword">ON</span> employees.department_id = departments.id;
</code></pre>
<p>The query above returns all the fields from both tables. The <code>INNER</code> keyword doesn't have anything to do with the number of columns returned - it only affects the number of rows returned.</p>
<h3 id="heading-namespacing-on-tables">Namespacing on Tables</h3>
<p>When working with multiple tables, you can specify which table a field exists on using a <code>.</code>. For example:</p>
<p><code>table_name.column_name</code></p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> students.name, classes.name
<span class="hljs-keyword">FROM</span> students
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> classes <span class="hljs-keyword">on</span> classes.class_id = students.class_id;
</code></pre>
<p>The above query returns the <code>name</code> field from the <code>students</code> table and the <code>name</code> field from the <code>classes</code> table. </p>
<h3 id="heading-left-join"><code>LEFT JOIN</code></h3>
<p>A <code>LEFT JOIN</code> will return every record from <code>table_a</code> regardless of whether or not any of those records have a match in <code>table_b</code>. A left join will also return any matching records from <code>table_b</code>. </p>
<p>Here is a Venn diagram to help visualize the effect of a <code>LEFT JOIN</code>.</p>
<p><img src="https://i.imgur.com/mNbhWfM.png" alt="left-join" width="292" height="178" loading="lazy"></p>
<p>A small trick you can do to make writing the SQL query easier is define an <a target="_blank" href="https://en.wikipedia.org/wiki/Alias_(SQL)">alias</a> for each table. Here's an example:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">SELECT</span> e.name, d.name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> e.department_id = d.id;
</code></pre>
<p>Notice the simple alias declarations <code>e</code> and <code>d</code> for <code>employees</code> and <code>departments</code> respectively.</p>
<p>Some developers do this to make their queries less verbose. That said, I personally hate it because single-letter variables are harder to understand the meaning of.</p>
<h3 id="heading-right-join"><code>RIGHT JOIN</code></h3>
<p>A <code>RIGHT JOIN</code> is, as you may expect, the opposite of a <code>LEFT JOIN</code>. It returns all records from <code>table_b</code> regardless of matches, and all matching records between the two tables.</p>
<p><img src="https://i.imgur.com/LG6Y43j.png" alt="right-join" width="652" height="352" loading="lazy"></p>
<h4 id="heading-sqlite-restriction">SQLite Restriction</h4>
<p>SQLite does not support right joins, but many dialects of SQL do. If you think about it, a <code>RIGHT JOIN</code> is just a <code>LEFT JOIN</code> with the order of the tables switched, so it's not a big deal that SQLite doesn't support the syntax.</p>
<h3 id="heading-full-join"><code>FULL JOIN</code></h3>
<p>A <code>FULL JOIN</code> combines the result set of the <code>LEFT JOIN</code> and <code>RIGHT JOIN</code> commands. It returns all records from both from <code>table_a</code> and <code>table_b</code> regardless of whether or not they have matches.</p>
<p><img src="https://i.imgur.com/Kk3k1Ub.png" alt="Full-join" width="606" height="344" loading="lazy"></p>
<h4 id="heading-sqlite">SQLite</h4>
<p>Like <code>RIGHT JOIN</code>s, SQLite doesn't support <code>FULL JOIN</code>s but they are still important to know.</p>
<h2 id="heading-chapter-11-database-performance">Chapter 11: Database Performance</h2>
<h3 id="heading-sql-indexes">SQL Indexes</h3>
<p>An index is an in-memory structure that ensures that queries we run on a database are performant, that is to say, they run quickly. </p>
<p>If you've learned about data structures, most database indexes are just <a target="_blank" href="https://en.wikipedia.org/wiki/Binary_tree">binary trees</a>. The binary tree can be stored in <a target="_blank" href="https://en.wikipedia.org/wiki/Random-access_memory">ram</a> as well as on <a target="_blank" href="https://en.wikipedia.org/wiki/Computer_data_storage">disk</a>, and it makes it easy to lookup the location of an entire row.</p>
<p><code>PRIMARY KEY</code> columns are indexed by default, ensuring you can look up a row by its <code>id</code> very quickly. But if you have other columns that you want to be able to do quick lookups on, you'll need to index them.</p>
<h4 id="heading-create-index"><code>CREATE INDEX</code></h4>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> index_name <span class="hljs-keyword">on</span> table_name (column_name);
</code></pre>
<p>It's fairly common to name an index after the column it's created on with a suffix of <code>_idx</code>.</p>
<h3 id="heading-index-review">Index Review</h3>
<p>As we discussed, an index is a data structure that can perform quick lookups. By indexing a column, we create a new in-memory structure, usually a binary-tree, where the values in the indexed column are sorted into the tree to keep lookups fast. </p>
<p>In terms of Big-O complexity, a binary tree index ensures that lookups are <a target="_blank" href="https://en.wikipedia.org/wiki/Big_O_notation">O(log(n))</a>.</p>
<h4 id="heading-shouldnt-we-index-everything-we-can-make-the-database-ultra-fast">Shouldn't we index everything? We can make the database ultra-fast!</h4>
<p>While indexes make specific kinds of lookups much faster, they also add performance overhead - they can slow down a database in other ways. </p>
<p>Think about it: if you index every column, you could have hundreds of binary trees in memory. That needlessly bloats the memory usage of your database. It also means that each time you insert a record, that record needs to be added to many trees - slowing down your insert speed.</p>
<p>The rule of thumb is simple:</p>
<blockquote>
<p>Add an index to columns you know you'll be doing frequent lookups on. Leave everything else un-indexed. You can always add indexes later.</p>
</blockquote>
<h3 id="heading-multi-column-indexes">Multi-column indexes</h3>
<p>Multi-column indexes are useful for the exact reason you might think - they speed up lookups that depend on multiple columns. </p>
<h4 id="heading-create-index-1"><code>CREATE INDEX</code></h4>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> first_name_last_name_age_idx
<span class="hljs-keyword">ON</span> <span class="hljs-keyword">users</span> (first_name, last_name, age);
</code></pre>
<p>A multi-column index is sorted by the first column first, the second column next, and so forth. A lookup on only the first column in a multi-column index gets almost all of the performance improvements that it would get from its own single-column index. But lookups on only the second or third column will have very degraded performance.</p>
<h4 id="heading-rule-of-thumb">Rule of thumb</h4>
<p>Unless you have specific reasons to do something special, only add multi-column indexes if you're doing frequent lookups on a specific combination of columns.</p>
<h3 id="heading-denormalizing-for-speed">Denormalizing for speed</h3>
<p>I left you with a cliffhanger in the "normalization" chapter. As it turns out, data integrity and deduplication come at a cost, and that cost is usually speed.</p>
<p>Joining tables together, using subqueries, performing aggregations, and running post-hoc calculations all take time. At very large scales these advanced techniques can actually take a huge performance toll on an application - sometimes grinding the database server to a halt.</p>
<p>Storing duplicate information can drastically speed up an application that needs to look it up in different ways. For example, if you store a user's country information right on their user record, no expensive join is required to load their profile page.</p>
<p>That said, denormalize at your own risk. Denormalizing a database incurs a large risk of inaccurate and buggy data.</p>
<p>In my opinion, it should be used as a kind of "last resort" in the name of speed.</p>
<h3 id="heading-sql-injection-1">SQL Injection</h3>
<p>SQL is a very common way hackers attempt to cause damage or breach a database. One of my favorite <a target="_blank" href="https://xkcd.com/327/">XKCD</a> comics of all time demonstrates the problem:</p>
<p><img src="https://bobby-tables.com/img/xkcd.png" alt="bobby tables" width="666" height="205" loading="lazy"></p>
<p>The joke here is that if someone was using this query:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> students(<span class="hljs-keyword">name</span>) <span class="hljs-keyword">VALUES</span> (?);
</code></pre>
<p>And the "name" of a student was <code>'Robert'); DROP TABLE students;--</code> then the resulting SQL query would look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> students(<span class="hljs-keyword">name</span>) <span class="hljs-keyword">VALUES</span> (<span class="hljs-string">'Robert'</span>); <span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> students;<span class="hljs-comment">--)</span>
</code></pre>
<p>As you can see, this is actually 2 queries! The first one inserts "Robert" into the database, and the second one deletes the students table!</p>
<h4 id="heading-how-do-we-protect-against-sql-injection">How do we protect against SQL injection?</h4>
<p>You need to be aware of SQL injection attacks, but to be honest the solution these days is to simply use a modern SQL library that sanitizes SQL inputs. We don't often need to sanitize inputs by hand at the application level anymore.</p>
<p>For example, the Go standard library's SQL packages automatically protects your inputs against SQL attacks if you <a target="_blank" href="https://go.dev/doc/database/sql-injection">use it properly</a>. In short, don't interpolate user input into raw strings yourself - make sure your database library has a way to sanitize inputs, and pass it those raw values.</p>
<h2 id="heading-congratulations-on-making-it-to-the-end">Congratulations on making it to the end!</h2>
<p>If you're interested in doing the interactive coding assignments and quizzes for this course, you can check out the <a target="_blank" href="https://www.boot.dev/learn/learn-sql">Learn SQL Course</a> course over on <a target="_blank" href="https://www.boot.dev/">Boot.dev</a></p>
<p>This course is a part of my full back-end developer career path, made up of other courses and projects if you're interested in checking those out.</p>
<p>If you want to see the other content I'm creating related to web development, check out some of my links below:</p>
<p><a target="_blank" href="https://www.backendbanter.fm/">Lane's Podcast: Backend Banter</a>
<a target="_blank" href="https://twitter.com/wagslane">Lane on Twitter</a>
<a target="_blank" href="https://www.youtube.com/@bootdotdev">Lane on YouTube</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Golang Handbook – A Beginner's Guide to Learning Go ]]>
                </title>
                <description>
                    <![CDATA[ The Go programming language has been exploding in popularity. Tons of companies are using Go to build scalable, modern, backend infrastructure. If you're looking to learn a new programming language, Go is a great choice. It's fast, lightweight, has a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-golang-handbook/</link>
                <guid isPermaLink="false">66b9e9f08ff373c48b152945</guid>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Thu, 25 May 2023 18:11:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738338718817/f95f88be-48a2-49ca-8d84-2bb09c65165f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Go programming language has been exploding in popularity. Tons of companies are using Go to build scalable, modern, backend infrastructure.</p>
<p>If you're looking to learn a new programming language, Go is a <em>great</em> choice. It's fast, lightweight, has an amazing open source community, and is actually quite easy to get started with.</p>
<p>This a completely free text-based handbook. If you want to get started, just scroll down and start reading! That said, there are two other options for following along.</p>
<ol>
<li><p>Try the interactive version of this <a target="_blank" href="https://boot.dev/learn/learn-golang">Golang course</a> on <a target="_blank" href="https://boot.dev/">Boot.dev</a>, complete with coding challenges and projects</p>
</li>
<li><p>Watch the video walkthrough of this course on FreeCodeCamp's YouTube channel (embedded below)</p>
</li>
</ol>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/un6ZyFkqFKo" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-chapter-1-why-learn-go">Why Learn Go?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-2-how-to-compile-go-code">How to Compile Go Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-3-variables-in-go">Variables in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-4-functions-in-go">Functions in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-5-structs-in-go">Structs in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-6-interfaces-in-go">Interfaces in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-7-errors-in-go">Errors in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-8-loops-in-go">Loops in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-9-arrays-and-slices-in-go">Arrays and Slices in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-10-maps-in-go">Maps in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-11-advanced-functions-in-go">Advanced Functions in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-12-pointers-in-go">Pointers in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-13-local-development-environment-in-go">Local Development in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-14-channels-in-go">Channels in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-15-mutexes-in-go">Mutexes in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-16-generics-in-go">Generics in Go</a></p>
</li>
</ol>
<h2 id="heading-chapter-1-why-learn-go">Chapter 1 – Why Learn Go?</h2>
<p><strong>Go is fast, simple, and productive.</strong> Go is one of the fastest programming languages, beating JavaScript, Python, and Ruby handily in most benchmarks.</p>
<p>But, Go code doesn't <em>run</em> quite as fast as its compiled Rust and C counterparts. That said, it <em>compiles</em> much faster than they do, which makes the developer experience super productive. Unfortunately, there are no swordfights on Go teams...</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/compiling.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Comic by</em> <a target="_blank" href="https://xkcd.com/303/"><em>xkcd</em></a></p>
<p>Go has been growing like crazy in the <a target="_blank" href="https://blog.boot.dev/backend/become-backend-developer/">backend development</a> industry, so if you're interested in getting a <a target="_blank" href="https://blog.boot.dev/backend/backend-job-description/">job as a backend dev</a>, <a target="_blank" href="https://blog.boot.dev/golang/become-golang-backend-dev/">Go can be a great choice</a> of technology to add to your tool belt.</p>
<h3 id="heading-how-to-download-and-install-the-go-toolchain">How to Download and Install the Go Toolchain</h3>
<p>I typically recommend one of two ways:</p>
<ul>
<li><p><a target="_blank" href="https://golang.org/doc/install">Official Download</a></p>
</li>
<li><p><a target="_blank" href="https://webinstall.dev/golang/">Webi Downloader</a></p>
</li>
</ul>
<p>Make sure to use at least version <code>1.20</code>. You can verify this after installation by typing:</p>
<pre><code class="lang-bash">go version
</code></pre>
<h3 id="heading-a-note-on-the-structure-of-a-go-program">A note on the structure of a Go program</h3>
<p>We'll go over this all later in more detail, but to sate your curiosity for now, here are a few tidbits about the code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"hello world"</span>)
}
</code></pre>
<ol>
<li><p><code>package main</code> lets the Go compiler know that we want this code to compile and run as a standalone program, as opposed to being a library that's imported by other programs.</p>
</li>
<li><p><code>import fmt</code> imports the <code>fmt</code> (formatting) package. The formatting package exists in Go's standard library and let's us do things like print text to the console.</p>
</li>
<li><p><code>func main()</code> defines the <code>main</code> function. <code>main</code> is the name of the function that acts as the entry point for a Go program.</p>
</li>
</ol>
<p>Save the code above in a file called <code>main.go</code> , run <code>go build</code> , and then run the resulting executable.</p>
<pre><code class="lang-bash">go build -o out
./out
</code></pre>
<p>You can also use Bootdev's <a target="_blank" href="https://boot.dev/playground/go">Go playground</a> to try out all the snippets in this course right from your browser.</p>
<h2 id="heading-chapter-2-how-to-compile-go-code">Chapter 2 – How to Compile Go Code</h2>
<h3 id="heading-what-does-it-mean-to-be-compiled">What does it mean to be compiled?</h3>
<p>Computers need machine code – they don't understand English or even Go. We need to convert our high-level (Go) code into machine language, which is really just a set of instructions that some specific hardware can understand. In your case, your CPU.</p>
<p>The Go compiler's job is to take Go code and produce machine code. On Windows, that would be a <code>.exe</code> file. On Mac or Linux, it would be any executable file.</p>
<p>Computers don't know how to do anything unless we as programmers tell them what to do. Unfortunately, computers don't understand human language. In fact, they don't even understand uncompiled computer programs.</p>
<p>For example, the code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
  fmt.Println(<span class="hljs-string">"hello world"</span>)
}
</code></pre>
<p>means <em>nothing</em> to a computer.</p>
<h3 id="heading-computers-need-machine-code">Computers need machine code</h3>
<p>A computer's <a target="_blank" href="https://en.wikipedia.org/wiki/Central_processing_unit">CPU</a> only understands its own <em>instruction set</em>, which we call "machine code". Instructions are basic math operations like addition, subtraction, multiplication, and the ability to save data temporarily.</p>
<p>For example, an <a target="_blank" href="https://en.wikipedia.org/wiki/ARM_architecture">ARM processor</a> uses the <em>ADD</em> instruction when supplied with the number <code>0100</code> in binary.</p>
<h3 id="heading-go-c-rust-and-so-on">Go, C, Rust, and so on</h3>
<p>Go, C, and Rust are all languages where the code is first converted to machine code by the compiler before it's executed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/code-compiler-machine-code.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-compiled-vs-interpreted">Compiled vs Interpreted</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1CSPb2q94KQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Compiled programs can be run without access to the original source code, and without access to a compiler.</p>
<p>For example, when your browser executes the code you write in this course, it doesn't use the original code, just the compiled result. Note how this is different than interpreted languages like Python and JavaScript.</p>
<p>With Python and JavaScript, the code is interpreted at <a target="_blank" href="https://en.wikipedia.org/wiki/Runtime_\(program_lifecycle_phase\)">runtime</a> by a separate program known as the "interpreter". Distributing code for users to run can be a pain because they need to have an interpreter installed, and they need access to the original source code.</p>
<h3 id="heading-examples-of-compiled-languages">Examples of compiled languages</h3>
<ul>
<li><p>Go</p>
</li>
<li><p>C</p>
</li>
<li><p>C++</p>
</li>
<li><p>Rust</p>
</li>
</ul>
<h3 id="heading-examples-of-interpreted-languages">Examples of interpreted languages</h3>
<ul>
<li><p>JavaSsript</p>
</li>
<li><p>Python</p>
</li>
<li><p>Ruby</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ovHaWmS.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Illustration of compiled vs interpreted languages</em></p>
<h3 id="heading-go-is-strongly-typed">Go is Strongly Typed</h3>
<p>Go enforces strong and static typing, meaning variables can only have a single type. A <code>string</code> variable like "hello world" can not be changed to an <code>int</code>, such as the number <code>3</code>.</p>
<p>One of the biggest benefits of strong typing is that errors can be caught at "compile time". In other words, bugs are more easily caught ahead of time because they are detected when the code is compiled before it even runs.</p>
<p>Contrast this with most interpreted languages, where the variable types are dynamic. Dynamic typing can lead to subtle bugs that are hard to detect. With interpreted languages, the code <em>must</em> be run (sometimes in production if you are unlucky 😨) to catch syntax and type errors.</p>
<p>As an example, the following code will fail to compile because strings and ints can't be added together:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> username <span class="hljs-keyword">string</span> = <span class="hljs-string">"wagslane"</span>
    <span class="hljs-keyword">var</span> password <span class="hljs-keyword">int</span> = <span class="hljs-number">20947382822</span>

    <span class="hljs-comment">// don't edit below this line</span>
    fmt.Println(<span class="hljs-string">"Authorization: Basic"</span>, username+<span class="hljs-string">":"</span>+password)
}
</code></pre>
<h3 id="heading-go-programs-are-lightweight">Go programs are lightweight</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/L1nDnWUbs6k" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Go programs are fairly lightweight. Each program includes a small amount of "extra" code that's included in the executable binary. This extra code is called the <a target="_blank" href="https://go.dev/doc/faq#runtime">Go Runtime</a>. One of the purposes of the Go runtime is to cleanup unused memory at runtime.</p>
<p>In other words, the Go compiler includes a small amount of extra logic in every Go program to make it easier for developers to write code that's memory efficient.</p>
<p>As a general rule, Java programs use <em>more</em> memory than comparable Go programs because Go doesn't use an entire virtual machine to run its programs, just a small runtime. The Go runtime is small enough that it is included directly in each Go program's compiled machine code.</p>
<p>As another general rule, Rust and C++ programs use slightly <em>less</em> memory than Go programs because more control is given to the developer to optimize memory usage of the program. The Go runtime just handles it for us automatically.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/1_Ggs-bJxobwZmrbfuoWGpFw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Chart showing idle memory usage comparison between Java (162MB), Go (.86MB) and Rust (.36MB)</em></p>
<p>In the chart above, <a target="_blank" href="https://medium.com/@dexterdarwich/comparison-between-java-go-and-rust-fdb21bd5fb7c">Dexter Darwich compares the memory usage</a> of three <em>very</em> simple programs written in Java, Go, and Rust. As you can see, Go and Rust use <em>very</em> little memory when compared to Java.</p>
<h2 id="heading-chapter-3-variables-in-go">Chapter 3 – Variables in Go</h2>
<p>Go's basic variable types are:</p>
<pre><code class="lang-go"><span class="hljs-keyword">bool</span>

<span class="hljs-keyword">string</span>

<span class="hljs-keyword">int</span>  <span class="hljs-keyword">int8</span>  <span class="hljs-keyword">int16</span>  <span class="hljs-keyword">int32</span>  <span class="hljs-keyword">int64</span>
<span class="hljs-keyword">uint</span> <span class="hljs-keyword">uint8</span> <span class="hljs-keyword">uint16</span> <span class="hljs-keyword">uint32</span> <span class="hljs-keyword">uint64</span> <span class="hljs-keyword">uintptr</span>

<span class="hljs-keyword">byte</span> <span class="hljs-comment">// alias for uint8</span>

<span class="hljs-keyword">rune</span> <span class="hljs-comment">// alias for int32</span>
     <span class="hljs-comment">// represents a Unicode code point</span>

<span class="hljs-keyword">float32</span> <span class="hljs-keyword">float64</span>

<span class="hljs-keyword">complex64</span> <span class="hljs-keyword">complex128</span>
</code></pre>
<p>We talked about <code>string</code>s and <code>int</code>s previously, and those two types should be fairly self-explanatory.</p>
<p>A <code>bool</code> is a boolean variable, meaning it has a value of <code>true</code> or <code>false</code>. The <a target="_blank" href="https://en.wikipedia.org/wiki/Floating-point_arithmetic">floating point</a> types ( <code>float32</code> and <code>float64</code>) are used for numbers that are not integers – that is, they have digits to the right of the decimal place, such as <code>3.14159</code>. The <code>float32</code> type uses 32 bits of precision, while the <code>float64</code> type uses 64 bits to be able to more precisely store more digits.</p>
<p>Don't worry too much about the intricacies of the other types for now. We will cover some of them in more detail as we progress.</p>
<h3 id="heading-how-to-declare-a-variable">How to declare a variable</h3>
<p>Variables are declared using the <code>var</code> keyword. For example, to declare a variable called <code>number</code> of type <code>int</code>, you would write:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> number <span class="hljs-keyword">int</span>
</code></pre>
<p>To declare a variable called <code>pi</code> to be of type <code>float64</code> with a value of <code>3.14159</code>, you would write:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14159</span>
</code></pre>
<p>The value of an initialized variable with no assignment will be its <a target="_blank" href="https://tour.golang.org/basics/12">zero value</a>.</p>
<h3 id="heading-short-variable-declaration">Short Variable Declaration</h3>
<p>Inside a function (even the main function), the <code>:=</code> short assignment statement can be used in place of a <code>var</code> declaration. The <code>:=</code> operator infers the type of the new variable based on the value.</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> empty <span class="hljs-keyword">string</span>
</code></pre>
<p>Is the same as:</p>
<pre><code class="lang-go">empty := <span class="hljs-string">""</span>
</code></pre>
<pre><code class="lang-go">numCars := <span class="hljs-number">10</span> <span class="hljs-comment">// inferred to be an integer</span>

temperature := <span class="hljs-number">0.0</span> <span class="hljs-comment">// temperature is inferred to be a floating point value because it has a decimal point</span>

<span class="hljs-keyword">var</span> isFunny = <span class="hljs-literal">true</span> <span class="hljs-comment">// isFunny is inferred to be a boolean</span>
</code></pre>
<p>Outside of a function (in the <a target="_blank" href="https://dave.cheney.net/2017/06/11/go-without-package-scoped-variables">global/package scope</a>), every statement begins with a keyword ( <code>var</code>, <code>func</code>, and so on) and so the <code>:=</code> construct is not available.</p>
<h3 id="heading-type-inference">Type Inference</h3>
<p>To declare a variable without specifying an explicit type (either by using the <code>:=</code> syntax or <code>var = expression</code> syntax), the variable's type is <em>inferred</em> from the value on the right hand side.</p>
<p>When the right hand side of the declaration is typed, the new variable is of that same type:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> i <span class="hljs-keyword">int</span>
j := i <span class="hljs-comment">// j is also an int</span>
</code></pre>
<p>However, when the right hand side is a literal value (an untyped numeric constant like <code>42</code> or <code>3.14</code>), the new variable will be an <code>int</code>, <code>float64</code>, or <code>complex128</code> depending on its precision:</p>
<pre><code class="lang-go">i := <span class="hljs-number">42</span>           <span class="hljs-comment">// int</span>
f := <span class="hljs-number">3.14</span>         <span class="hljs-comment">// float64</span>
g := <span class="hljs-number">0.867</span> + <span class="hljs-number">0.5i</span> <span class="hljs-comment">// complex128</span>
</code></pre>
<h3 id="heading-same-line-declarations">Same Line Declarations</h3>
<p>We can declare multiple variables on the same line:</p>
<pre><code class="lang-go">mileage, company := <span class="hljs-number">80276</span>, <span class="hljs-string">"Tesla"</span>

<span class="hljs-comment">// is the same as</span>

mileage := <span class="hljs-number">80276</span>
company := <span class="hljs-string">"Tesla"</span>
</code></pre>
<h3 id="heading-type-sizes">Type Sizes</h3>
<p>Ints, <a target="_blank" href="https://www.cs.utah.edu/~germain/PPS/Topics/unsigned_integer.html#:~:text=Unsigned%20Integers,negative%20\(zero%20or%20positive\).">uints</a>, <a target="_blank" href="https://techterms.com/definition/floatingpoint">floats</a>, and <a target="_blank" href="https://www.cloudhadoop.com/2018/12/golang-tutorials-complex-types-numbers.html#:~:text=Golang%20Complex%20Type%20Numbers,complex%20number%20is%2012.8i.">complex</a> numbers all have type sizes.</p>
<pre><code class="lang-go"><span class="hljs-keyword">int</span>  <span class="hljs-keyword">int8</span>  <span class="hljs-keyword">int16</span>  <span class="hljs-keyword">int32</span>  <span class="hljs-keyword">int64</span> <span class="hljs-comment">// whole numbers</span>

<span class="hljs-keyword">uint</span> <span class="hljs-keyword">uint8</span> <span class="hljs-keyword">uint16</span> <span class="hljs-keyword">uint32</span> <span class="hljs-keyword">uint64</span> <span class="hljs-keyword">uintptr</span> <span class="hljs-comment">// positive whole numbers</span>

<span class="hljs-keyword">float32</span> <span class="hljs-keyword">float64</span> <span class="hljs-comment">// decimal numbers</span>

<span class="hljs-keyword">complex64</span> <span class="hljs-keyword">complex128</span> <span class="hljs-comment">// imaginary numbers (rare)</span>
</code></pre>
<p>The size (8, 16, 32, 64, 128, and so on) indicates how many bits in memory will be used to store the variable. The default <code>int</code> and <code>uint</code> types are just aliases that refer to their respective 32 or 64 bit sizes depending on the environment of the user.</p>
<p>The standard sizes that <a target="_blank" href="https://blog.boot.dev/golang/default-native-types-golang/">should be used</a> unless you have a specific need are:</p>
<ul>
<li><p><code>int</code></p>
</li>
<li><p><code>uint</code></p>
</li>
<li><p><code>float64</code></p>
</li>
<li><p><code>complex128</code></p>
</li>
</ul>
<p>Some types can be converted the following way:</p>
<pre><code class="lang-go">temperatureInt := <span class="hljs-number">88</span>
temperatureFloat := <span class="hljs-keyword">float64</span>(temperatureInt)
</code></pre>
<p>Casting a float to an integer in this way <a target="_blank" href="https://techterms.com/definition/truncate">truncates</a> the floating point portion.</p>
<h3 id="heading-which-type-should-i-use"><strong>Which Type Should I Use?</strong></h3>
<p>With so many types for what is essentially just a number, developers coming from languages that only have one kind of <code>Number</code> type (like JavaScript) may find the choices daunting.</p>
<p>A problem arises when we have a <code>uint16</code>, and the function we are trying to pass it into takes an <code>int</code>. We're forced to write code riddled with type casts like <code>int(myUint16)</code>.</p>
<p>This style of development can be slow and annoying to read. When Go developers stray from the “default” type for any given type family, the code can get messy quickly.</p>
<p>Unless you have a good reason to, stick to the following types:</p>
<ul>
<li><p><code>bool</code></p>
</li>
<li><p><code>string</code></p>
</li>
<li><p><code>int</code></p>
</li>
<li><p><code>uint</code></p>
</li>
<li><p><code>byte</code></p>
</li>
<li><p><code>rune</code></p>
</li>
<li><p><code>float64</code></p>
</li>
<li><p><code>complex128</code></p>
</li>
</ul>
<h3 id="heading-constants">Constants</h3>
<p>Constants are declared like variables but use the <code>const</code> keyword. Constants can't use the <code>:=</code> short declaration syntax.</p>
<p>Constants can be character, string, boolean, or numeric values. They <em>can not</em> be more complex types like slices, maps and structs, which are types I will explain later.</p>
<p>As the name implies, the value of a constant can't be changed after it has been declared.</p>
<p><a target="_blank" href="https://blog.boot.dev/clean-code/constants-in-go-vs-javascript-and-when-to-use-them/">Constants <em>must</em> be known at compile time</a>. More often than not they will be declared with a static value:</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> myInt = <span class="hljs-number">15</span>
</code></pre>
<p>However, constants <em>can be computed</em> so long as the computation can happen at compile time. For example, this is valid:</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> firstName = <span class="hljs-string">"Lane"</span>
<span class="hljs-keyword">const</span> lastName = <span class="hljs-string">"Wagner"</span>
<span class="hljs-keyword">const</span> fullName = firstName + <span class="hljs-string">" "</span> + lastName
</code></pre>
<p>That said, you can't declare a constant that can only be computed at run-time.</p>
<h3 id="heading-how-to-format-strings-in-go">How to Format Strings in Go</h3>
<p>Go follows the <a target="_blank" href="https://cplusplus.com/reference/cstdio/printf/">printf tradition</a> from the C language. In my opinion, string formatting/interpolation in Go is currently <em>less</em> elegant than JavaScript and Python.</p>
<ul>
<li><p><a target="_blank" href="https://pkg.go.dev/fmt#Printf">fmt.Printf</a> – Prints a formatted string to <a target="_blank" href="https://stackoverflow.com/questions/3385201/confused-about-stdin-stdout-and-stderr">standard out</a></p>
</li>
<li><p><a target="_blank" href="https://pkg.go.dev/fmt#Sprintf">fmt.Sprintf()</a> – Returns the formatted string</p>
</li>
</ul>
<h3 id="heading-examples">Examples</h3>
<p>These formatting verbs work with both <code>fmt.Printf</code> and <code>fmt.Sprintf</code>.</p>
<h4 id="heading-v-interpolate-the-default-representation"><code>%v</code> - Interpolate the default representation</h4>
<p>The <code>%v</code> variant prints the Go syntax representation of a value. You can usually use this if you're unsure what else to use. That said, it's better to use the type-specific variant if you can.</p>
<pre><code class="lang-go">s := fmt.Sprintf(<span class="hljs-string">"I am %v years old"</span>, <span class="hljs-number">10</span>)
<span class="hljs-comment">// I am 10 years old</span>

s := fmt.Sprintf(<span class="hljs-string">"I am %v years old"</span>, <span class="hljs-string">"way too many"</span>)
<span class="hljs-comment">// I am way too many years old</span>
</code></pre>
<h4 id="heading-s-interpolate-a-string"><code>%s</code> - Interpolate a string</h4>
<pre><code class="lang-go">s := fmt.Sprintf(<span class="hljs-string">"I am %s years old"</span>, <span class="hljs-string">"way too many"</span>)
<span class="hljs-comment">// I am way too many years old</span>
</code></pre>
<h4 id="heading-d-interpolate-an-integer-in-decimal-form"><code>%d</code> - Interpolate an integer in decimal form</h4>
<pre><code class="lang-go">s := fmt.Sprintf(<span class="hljs-string">"I am %d years old"</span>, <span class="hljs-number">10</span>)
<span class="hljs-comment">// I am 10 years old</span>
</code></pre>
<h4 id="heading-f-interpolate-a-decimal"><code>%f</code> - Interpolate a decimal</h4>
<pre><code class="lang-go">s := fmt.Sprintf(<span class="hljs-string">"I am %f years old"</span>, <span class="hljs-number">10.523</span>)
<span class="hljs-comment">// I am 10.523000 years old</span>

<span class="hljs-comment">// The ".2" rounds the number to 2 decimal places</span>
s := fmt.Sprintf(<span class="hljs-string">"I am %.2f years old"</span>, <span class="hljs-number">10.523</span>)
<span class="hljs-comment">// I am 10.53 years old</span>
</code></pre>
<p>If you're interested in all the formatting options, feel free to take a look at the <code>fmt</code> package's <a target="_blank" href="https://pkg.go.dev/fmt#hdr-Printing">docs here</a>.</p>
<h3 id="heading-conditionals">Conditionals</h3>
<p><code>if</code> statements in Go don't use parentheses around the condition:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> height &gt; <span class="hljs-number">4</span> {
    fmt.Println(<span class="hljs-string">"You are tall enough!"</span>)
}
</code></pre>
<p><code>else if</code> and <code>else</code> are supported as you would expect:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> height &gt; <span class="hljs-number">6</span> {
    fmt.Println(<span class="hljs-string">"You are super tall!"</span>)
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> height &gt; <span class="hljs-number">4</span> {
    fmt.Println(<span class="hljs-string">"You are tall enough!"</span>)
} <span class="hljs-keyword">else</span> {
    fmt.Println(<span class="hljs-string">"You are not tall enough!"</span>)
}
</code></pre>
<h3 id="heading-the-initial-statement-of-an-if-block">The initial statement of an if block</h3>
<p>An <code>if</code> conditional can have an "initial" statement. The variable(s) created in the initial statement are only defined within the scope of the <code>if</code> body.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> INITIAL_STATEMENT; CONDITION {
}
</code></pre>
<p>This is just some syntactic sugar that Go offers to shorten up code in some cases. For example, instead of writing:</p>
<pre><code class="lang-go">length := getLength(email)
<span class="hljs-keyword">if</span> length &lt; <span class="hljs-number">1</span> {
    fmt.Println(<span class="hljs-string">"Email is invalid"</span>)
}
</code></pre>
<p>We can do:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> length := getLength(email); length &lt; <span class="hljs-number">1</span> {
    fmt.Println(<span class="hljs-string">"Email is invalid"</span>)
}
</code></pre>
<p>Not only is this code a bit shorter, but it also removes <code>length</code> from the parent scope. This is convenient because we don't need it there – we only need access to it while checking a condition.</p>
<h2 id="heading-chapter-4-functions-in-go">Chapter 4 – Functions in Go</h2>
<p>Functions in Go can take zero or more arguments.</p>
<p>To make Go code easier to read, the variable type comes <em>after</em> the variable name.</p>
<p>For example, the following function:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sub</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x-y
}
</code></pre>
<p>Accepts two integer parameters and returns another integer.</p>
<p>Here, <code>func sub(x int, y int) int</code> is known as the "function signature".</p>
<h3 id="heading-multiple-parameters">Multiple Parameters</h3>
<p>When multiple arguments are of the same type, the type only needs to be declared after the last one, assuming they are in order.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x + y
}
</code></pre>
<p>If they are not in order they need to be defined separately.</p>
<h3 id="heading-function-declaration-syntax">Function Declaration Syntax</h3>
<p>Developers often wonder why the declaration syntax in Go is different from the tradition established in the C family of languages.</p>
<h4 id="heading-c-style-syntax">C-Style syntax</h4>
<p>The C language describes types with an expression including the name to be declared, and states what type that expression will have.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> y;
</code></pre>
<p>The code above declares <code>y</code> as an <code>int</code>. In general, the type goes on the left and the expression on the right.</p>
<p>Interestingly, the creators of the Go language agreed that the C-style of declaring types in signatures gets confusing really fast – take a look at this nightmare.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> (*fp)(<span class="hljs-keyword">int</span> (*ff)(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y), <span class="hljs-keyword">int</span> b)
</code></pre>
<h4 id="heading-go-style-syntax">Go-style syntax</h4>
<p>Go's declarations are clear, you just read them left to right, just like you would in English.</p>
<pre><code class="lang-go">x <span class="hljs-keyword">int</span>
p *<span class="hljs-keyword">int</span>
a [<span class="hljs-number">3</span>]<span class="hljs-keyword">int</span>
</code></pre>
<p>It's nice for more complex signatures, as it makes them easier to read.</p>
<pre><code class="lang-go">f <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(<span class="hljs-keyword">func</span>(<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span>, <span class="hljs-title">int</span>) <span class="hljs-title">int</span></span>
</code></pre>
<h3 id="heading-how-to-pass-variables-by-value">How to Pass Variables by Value</h3>
<p>Variables in Go are passed by value (except for a few data types we haven't covered yet). "Pass by value" means that when a variable is passed into a function, that function receives a <em>copy</em> of the variable. The function is unable to mutate the caller's original data.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    x := <span class="hljs-number">5</span>
    increment(x)

    fmt.Println(x)
    <span class="hljs-comment">// still prints 5,</span>
    <span class="hljs-comment">// because the increment function</span>
    <span class="hljs-comment">// received a copy of x</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">increment</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span></span>{
    x++
}
</code></pre>
<h3 id="heading-how-to-ignore-return-values">How to Ignore Return Values</h3>
<p>A function can return a value that the caller doesn't care about. We can explicitly ignore variables by using an underscore: <code>_</code></p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getPoint</span><span class="hljs-params">()</span> <span class="hljs-params">(x <span class="hljs-keyword">int</span>, y <span class="hljs-keyword">int</span>)</span></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">3</span>, <span class="hljs-number">4</span>
}

<span class="hljs-comment">// ignore y value</span>
x, _ := getPoint()
</code></pre>
<p>Even though <code>getPoint()</code> returns two values, we can capture the first one and ignore the second.</p>
<h4 id="heading-why-would-you-ignore-a-return-value">Why would you ignore a return value?</h4>
<p>There could be many reasons. For example, maybe a function called <code>getCircle</code> returns the center point and the radius, but you really only need the radius for your calculation. In that case, you would ignore the center point variable.</p>
<p>This is crucial to understand because the Go compiler will throw an error if you have unused variable declarations in your code, so you <em>need</em> to ignore anything you don't intend to use.</p>
<h3 id="heading-named-return-values">Named Return Values</h3>
<p>Return values may be given names, and if they are, then they are treated the same as if they were new variables defined at the top of the function.</p>
<p>Named return values are best thought of as a way to document the purpose of the returned values.</p>
<p>According to the <a target="_blank" href="https://tour.golang.org/">tour of go</a>:</p>
<blockquote>
<p>"A return statement without arguments returns the named return values. This is known as a "naked" return. Naked return statements should be used only in short functions. They can harm readability in longer functions."</p>
</blockquote>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCoords</span><span class="hljs-params">()</span> <span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span></span>{
  <span class="hljs-comment">// x and y are initialized with zero values</span>

  <span class="hljs-keyword">return</span> <span class="hljs-comment">// automatically returns x and y</span>
}
</code></pre>
<p>Is the same as:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCoords</span><span class="hljs-params">()</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>)</span></span>{
  <span class="hljs-keyword">var</span> x <span class="hljs-keyword">int</span>
  <span class="hljs-keyword">var</span> y <span class="hljs-keyword">int</span>
  <span class="hljs-keyword">return</span> x, y
}
</code></pre>
<p>In the first example, <code>x</code> and <code>y</code> are the return values. At the end of the function, we could simply write <code>return</code> to return the values of those two variables, rather that writing <code>return x,y</code>.</p>
<h3 id="heading-explicit-returns">Explicit Returns</h3>
<p>Even though a function has named return values, we can still explicitly return values if we want to.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCoords</span><span class="hljs-params">()</span> <span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span></span>{
  <span class="hljs-keyword">return</span> x, y <span class="hljs-comment">// this is explicit</span>
}
</code></pre>
<p>Using this explicit pattern we can even overwrite the return values:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCoords</span><span class="hljs-params">()</span> <span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span></span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">5</span>, <span class="hljs-number">6</span> <span class="hljs-comment">// this is explicit, x and y are NOT returned</span>
}
</code></pre>
<p>Otherwise, if we want to return the values defined in the function signature we can just use a naked <code>return</code> (blank return):</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCoords</span><span class="hljs-params">()</span> <span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span></span>{
  <span class="hljs-keyword">return</span> <span class="hljs-comment">// implicitly returns x and y</span>
}
</code></pre>
<h3 id="heading-the-benefits-of-named-returns">The Benefits of Named Returns</h3>
<ol>
<li><h4 id="heading-good-for-documentation-understanding">Good For Documentation (Understanding)</h4>
</li>
</ol>
<p>Named return parameters are great for documenting a function. We know what the function is returning directly from its signature, no need for a comment.</p>
<p>Named return parameters are particularly important in longer functions with many return values.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">calculator</span><span class="hljs-params">(a, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(mul, div <span class="hljs-keyword">int</span>, err error)</span></span> {
    <span class="hljs-keyword">if</span> b == <span class="hljs-number">0</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, errors.New(<span class="hljs-string">"Can't divide by zero"</span>)
    }
    mul = a * b
    div = a / b
    <span class="hljs-keyword">return</span> mul, div, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>Which is easier to understand than:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">calculator</span><span class="hljs-params">(a, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>, error)</span></span> {
    <span class="hljs-keyword">if</span> b == <span class="hljs-number">0</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, errors.New(<span class="hljs-string">"Can't divide by zero"</span>)
    }
    mul := a * b
    div := a / b
    <span class="hljs-keyword">return</span> mul, div, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>We know <em>the meaning</em> of each return value just by looking at the function signature: <code>func calculator(a, b int) (mul, div int, err error)</code></p>
<h4 id="heading-less-code-sometimes">Less Code (Sometimes)</h4>
<p>If there are multiple return statements in a function, you don’t need to write all the return values each time, though you probably should.</p>
<p>When you choose to omit return values, it's called a <em>naked</em> return. Naked returns should only be used in short and simple functions.</p>
<h3 id="heading-early-returns">Early Returns</h3>
<p>Go supports the ability to return early from a function. This is a powerful feature that can clean up code, especially when used as <a target="_blank" href="https://blog.boot.dev/clean-code/guard-clauses/">guard clauses</a>.</p>
<p>Guard Clauses leverage the ability to <code>return</code> early from a function (or <code>continue</code> through a loop) to make nested conditionals one-dimensional. Instead of using if/else chains, we just return early from the function at the end of each conditional block.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">divide</span><span class="hljs-params">(dividend, divisor <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>, error)</span></span> {
    <span class="hljs-keyword">if</span> divisor == <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>, errors.New(<span class="hljs-string">"Can't divide by zero"</span>)
    }
    <span class="hljs-keyword">return</span> dividend/divisor, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>Error handling in Go naturally encourages developers to make use of guard clauses. When I started writing more JavaScript, I was disappointed to see how many nested conditionals existed in the code I was working on.</p>
<p>Let’s take a look at an exaggerated example of nested conditional logic:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getInsuranceAmount</span><span class="hljs-params">(status insuranceStatus)</span> <span class="hljs-title">int</span></span> {
  amount := <span class="hljs-number">0</span>
  <span class="hljs-keyword">if</span> !status.hasInsurance(){
    amount = <span class="hljs-number">1</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">if</span> status.isTotaled(){
      amount = <span class="hljs-number">10000</span>
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">if</span> status.isDented(){
        amount = <span class="hljs-number">160</span>
        <span class="hljs-keyword">if</span> status.isBigDent(){
          amount = <span class="hljs-number">270</span>
        }
      } <span class="hljs-keyword">else</span> {
        amount = <span class="hljs-number">0</span>
      }
    }
  }
  <span class="hljs-keyword">return</span> amount
}
</code></pre>
<p>This could be written with guard clauses instead:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getInsuranceAmount</span><span class="hljs-params">(status insuranceStatus)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">if</span> !status.hasInsurance(){
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
  }
  <span class="hljs-keyword">if</span> status.isTotaled(){
    <span class="hljs-keyword">return</span> <span class="hljs-number">10000</span>
  }
  <span class="hljs-keyword">if</span> !status.isDented(){
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
  }
  <span class="hljs-keyword">if</span> status.isBigDent(){
    <span class="hljs-keyword">return</span> <span class="hljs-number">270</span>
  }
  <span class="hljs-keyword">return</span> <span class="hljs-number">160</span>
}
</code></pre>
<p>The example above is much easier to read and understand. When writing code, it’s important to try to reduce the cognitive load on the reader by reducing the number of entities they need to think about at any given time.</p>
<p>In the first example, if the developer is trying to figure out <code>when</code> 270 is returned, they need to think about each branch in the logic tree and try to remember which cases matter and which cases don’t.</p>
<p>With the one-dimensional structure offered by guard clauses, it’s as simple as stepping through each case in order.</p>
<h2 id="heading-chapter-5-structs-in-go">Chapter 5 – Structs in Go</h2>
<p>We use structs in Go to represent structured data. It's often convenient to group different types of variables together. For example, if we want to represent a car we could do the following:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
  Make <span class="hljs-keyword">string</span>
  Model <span class="hljs-keyword">string</span>
  Height <span class="hljs-keyword">int</span>
  Width <span class="hljs-keyword">int</span>
}
</code></pre>
<p>This creates a new struct type called <code>car</code>. All cars have a <code>Make</code>, <code>Model</code>, <code>Height</code> and <code>Width</code>.</p>
<p>In Go, you will often use a struct to represent information that you would have used a dictionary for in Python, or an object literal in JavaScript.</p>
<h3 id="heading-nested-structs-in-go">Nested Structs in Go</h3>
<p>Structs can be nested to represent more complex entities:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
  Make <span class="hljs-keyword">string</span>
  Model <span class="hljs-keyword">string</span>
  Height <span class="hljs-keyword">int</span>
  Width <span class="hljs-keyword">int</span>
  FrontWheel Wheel
  BackWheel Wheel
}

<span class="hljs-keyword">type</span> Wheel <span class="hljs-keyword">struct</span> {
  Radius <span class="hljs-keyword">int</span>
  Material <span class="hljs-keyword">string</span>
}
</code></pre>
<p>The fields of a struct can be accessed using the dot <code>.</code> operator.</p>
<pre><code class="lang-go">myCar := car{}
myCar.FrontWheel.Radius = <span class="hljs-number">5</span>
</code></pre>
<h3 id="heading-anonymous-structs">Anonymous Structs</h3>
<p>An <a target="_blank" href="https://blog.boot.dev/golang/anonymous-structs-golang/">anonymous struct</a> is just like a regular struct, but it is defined without a name and therefore cannot be referenced elsewhere in the code.</p>
<p>To create an anonymous struct, just instantiate the instance immediately using a second pair of brackets after declaring the type:</p>
<pre><code class="lang-go">myCar := <span class="hljs-keyword">struct</span> {
  Make <span class="hljs-keyword">string</span>
  Model <span class="hljs-keyword">string</span>
} {
  Make: <span class="hljs-string">"tesla"</span>,
  Model: <span class="hljs-string">"model 3"</span>
}
</code></pre>
<p>You can even nest anonymous structs as fields within other structs:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
  Make <span class="hljs-keyword">string</span>
  Model <span class="hljs-keyword">string</span>
  Height <span class="hljs-keyword">int</span>
  Width <span class="hljs-keyword">int</span>
  <span class="hljs-comment">// Wheel is a field containing an anonymous struct</span>
  Wheel <span class="hljs-keyword">struct</span> {
    Radius <span class="hljs-keyword">int</span>
    Material <span class="hljs-keyword">string</span>
  }
}
</code></pre>
<h4 id="heading-when-should-you-use-an-anonymous-struct">When should you use an anonymous struct?</h4>
<p>In general, <em>prefer named structs</em>. Named structs make it easier to read and understand your code, and they have the nice side-effect of being reusable. I sometimes use anonymous structs when I know I won't ever need to use a struct again. For example, sometimes I'll use one to create the shape of some JSON data in HTTP handlers.</p>
<p>If a struct is only meant to be used once, then it makes sense to declare it in such a way that developers down the road won’t be tempted to accidentally use it again.</p>
<p>You can read more about <a target="_blank" href="https://blog.boot.dev/golang/anonymous-structs-golang/">anonymous structs here</a> if you're curious.</p>
<h3 id="heading-embedded-structs">Embedded Structs</h3>
<p>Go is not an <a target="_blank" href="https://boot.dev/learn/learn-object-oriented-programming">object-oriented</a> language. But embedded structs provide a kind of <em>data-only</em> inheritance that can be useful at times.</p>
<p>Keep in mind, Go doesn't support classes or inheritance in the complete sense. Embedded structs are just a way to elevate and share fields between struct definitions.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
  <span class="hljs-built_in">make</span> <span class="hljs-keyword">string</span>
  model <span class="hljs-keyword">string</span>
}

<span class="hljs-keyword">type</span> truck <span class="hljs-keyword">struct</span> {
  <span class="hljs-comment">// "car" is embedded, so the definition of a</span>
  <span class="hljs-comment">// "truck" now also additionally contains all</span>
  <span class="hljs-comment">// of the fields of the car struct</span>
  car
  bedSize <span class="hljs-keyword">int</span>
}
</code></pre>
<h4 id="heading-embedded-vs-nested">Embedded vs nested</h4>
<ul>
<li><p>An embedded struct's fields are accessed at the top level, unlike nested structs.</p>
</li>
<li><p>Promoted fields can be accessed like normal fields except that they can't be used in <a target="_blank" href="https://golang.org/ref/spec#Composite_literals">composite literals</a></p>
</li>
</ul>
<pre><code class="lang-go">lanesTruck := truck{
  bedSize: <span class="hljs-number">10</span>,
  car: car{
    <span class="hljs-built_in">make</span>: <span class="hljs-string">"toyota"</span>,
    model: <span class="hljs-string">"camry"</span>,
  },
}

fmt.Println(lanesTruck.bedSize)

<span class="hljs-comment">// embedded fields promoted to the top-level</span>
<span class="hljs-comment">// instead of lanesTruck.car.make</span>
fmt.Println(lanesTruck.<span class="hljs-built_in">make</span>)
fmt.Println(lanesTruck.model)
</code></pre>
<h3 id="heading-struct-methods">Struct Methods</h3>
<p>While Go is <strong>not</strong> object-oriented, it does support methods that can be defined on structs. Methods are just functions that have a receiver. A receiver is a special parameter that syntactically goes <em>before</em> the name of the function.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> rect <span class="hljs-keyword">struct</span> {
  width <span class="hljs-keyword">int</span>
  height <span class="hljs-keyword">int</span>
}

<span class="hljs-comment">// area has a receiver of (r rect)</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r rect)</span> <span class="hljs-title">area</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> r.width * r.height
}

r := rect{
  width: <span class="hljs-number">5</span>,
  height: <span class="hljs-number">10</span>,
}

fmt.Println(r.area())
<span class="hljs-comment">// prints 50</span>
</code></pre>
<p>A receiver is just a special kind of function parameter. Receivers are important because they will, as you'll learn in the exercises to come, allow us to define interfaces that our structs (and other types) can implement.</p>
<h2 id="heading-chapter-6-interfaces-in-go">Chapter 6 – Interfaces in Go</h2>
<p><a target="_blank" href="https://blog.boot.dev/golang/golang-interfaces/">Interfaces</a> are collections of method signatures. A type "implements" an interface if it has all of the methods of the given interface defined on it.</p>
<p>In the following example, a "shape" must be able to return its area and perimeter. Both <code>rect</code> and <code>circle</code> fulfill the interface.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> shape <span class="hljs-keyword">interface</span> {
  area() <span class="hljs-keyword">float64</span>
  perimeter() <span class="hljs-keyword">float64</span>
}

<span class="hljs-keyword">type</span> rect <span class="hljs-keyword">struct</span> {
    width, height <span class="hljs-keyword">float64</span>
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r rect)</span> <span class="hljs-title">area</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> r.width * r.height
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r rect)</span> <span class="hljs-title">perimeter</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>*r.width + <span class="hljs-number">2</span>*r.height
}

<span class="hljs-keyword">type</span> circle <span class="hljs-keyword">struct</span> {
    radius <span class="hljs-keyword">float64</span>
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c circle)</span> <span class="hljs-title">area</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> math.Pi * c.radius * c.radius
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c circle)</span> <span class="hljs-title">perimeter</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * math.Pi * c.radius
}
</code></pre>
<p>When a type implements an interface, it can then be used as the interface type.</p>
<p>Interfaces are implemented <em>implicitly</em>.</p>
<p>A type never declares that it implements a given interface. If an interface exists and a type has the proper methods defined, then the type automatically fulfills that interface.</p>
<h3 id="heading-multiple-interfaces">Multiple Interfaces</h3>
<p>A type can implement any number of interfaces in Go. For example, the empty interface, <code>interface{}</code>, is <em>always</em> implemented by every type because it has no requirements.</p>
<h3 id="heading-naming-interface-args">Naming interface args</h3>
<p>Consider the following interface:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Copier <span class="hljs-keyword">interface</span> {
  Copy(<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>) <span class="hljs-keyword">int</span>
}
</code></pre>
<p>Based on the code alone, can you deduce what <em>kinds</em> of strings you should pass into the <code>Copy</code> function?</p>
<p>We know the function signature expects 2 string types, but what are they? Filenames? URLs? Raw string data? For that matter, what the heck is that <code>int</code> that's being returned?</p>
<p>Let's add some named arguments and return data to make it clearer.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Copier <span class="hljs-keyword">interface</span> {
  Copy(sourceFile <span class="hljs-keyword">string</span>, destinationFile <span class="hljs-keyword">string</span>) (bytesCopied <span class="hljs-keyword">int</span>)
}
</code></pre>
<p>Much better. We can see what the expectations are now. The first argument is the <code>sourceFile</code>, the second argument is the <code>destinationFile</code>, and <code>bytesCopied</code>, an integer, is returned.</p>
<h3 id="heading-type-assertions-in-go">Type Assertions in Go</h3>
<p>When working with interfaces in Go, every once-in-awhile you'll need access to the underlying type of an interface value. You can cast an interface to its underlying type using a <em>type assertion</em>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> shape <span class="hljs-keyword">interface</span> {
    area() <span class="hljs-keyword">float64</span>
}

<span class="hljs-keyword">type</span> circle <span class="hljs-keyword">struct</span> {
    radius <span class="hljs-keyword">float64</span>
}

<span class="hljs-comment">// "c" is a new circle cast from "s"</span>
<span class="hljs-comment">// which is an instance of a shape.</span>
<span class="hljs-comment">// "ok" is a bool that is true if s was a circle</span>
<span class="hljs-comment">// or false if s isn't a circle</span>
c, ok := s.(circle)
<span class="hljs-keyword">if</span> !ok {
    <span class="hljs-comment">// s wasn't a circle</span>
    log.Fatal(<span class="hljs-string">"s is not a circle"</span>)
}

radius := c.radius
</code></pre>
<h3 id="heading-type-switches-in-go">Type Switches in Go</h3>
<p>A <em>type switch</em> makes it easy to do several type assertions in a series.</p>
<p>A type switch is similar to a regular switch statement, but the cases specify <em>types</em> instead of <em>values</em>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">printNumericValue</span><span class="hljs-params">(num <span class="hljs-keyword">interface</span>{})</span></span> {
    <span class="hljs-keyword">switch</span> v := num.(<span class="hljs-keyword">type</span>) {
    <span class="hljs-keyword">case</span> <span class="hljs-keyword">int</span>:
        fmt.Printf(<span class="hljs-string">"%T\n"</span>, v)
    <span class="hljs-keyword">case</span> <span class="hljs-keyword">string</span>:
        fmt.Printf(<span class="hljs-string">"%T\n"</span>, v)
    <span class="hljs-keyword">default</span>:
        fmt.Printf(<span class="hljs-string">"%T\n"</span>, v)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    printNumericValue(<span class="hljs-number">1</span>)
    <span class="hljs-comment">// prints "int"</span>

    printNumericValue(<span class="hljs-string">"1"</span>)
    <span class="hljs-comment">// prints "string"</span>

    printNumericValue(<span class="hljs-keyword">struct</span>{}{})
    <span class="hljs-comment">// prints "struct {}"</span>
}
</code></pre>
<p><code>fmt.Printf("%T\n", v)</code> prints the <em>type</em> of a variable.</p>
<h3 id="heading-clean-interfaces">Clean Interfaces</h3>
<p>Writing clean interfaces is <em>hard</em>. Frankly, anytime you’re dealing with abstractions in code, the simple can become complex very quickly if you’re not careful. Let’s go over some <a target="_blank" href="https://blog.boot.dev/golang/golang-interfaces/">rules of thumb for keeping interfaces clean</a>.</p>
<h4 id="heading-1-keep-interfaces-small">1. Keep Interfaces Small</h4>
<p>If there is only one piece of advice that you take away from this article, make it this: keep interfaces small! Interfaces are meant to define the minimal behavior necessary to accurately represent an idea or concept.</p>
<p>Here is an example from the standard HTTP package of a larger interface that’s a good example of defining minimal behavior:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> File <span class="hljs-keyword">interface</span> {
    io.Closer
    io.Reader
    io.Seeker
    Readdir(count <span class="hljs-keyword">int</span>) ([]os.FileInfo, error)
    Stat() (os.FileInfo, error)
}
</code></pre>
<p>Any type that satisfies the interface’s behaviors can be considered by the HTTP package as a <em>File</em>. This is convenient because the HTTP package doesn’t need to know if it’s dealing with a file on disk, a network buffer, or a simple <code>[]byte</code>.</p>
<h4 id="heading-2-interfaces-should-have-no-knowledge-of-satisfying-types">2. Interfaces Should Have No Knowledge of Satisfying Types</h4>
<p>An interface should define what is necessary for other types to classify as a member of that interface. They shouldn’t be aware of any types that happen to satisfy the interface at design time.</p>
<p>For example, let’s assume we are building an interface to describe the components necessary to define a car.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">interface</span> {
    Color() <span class="hljs-keyword">string</span>
    Speed() <span class="hljs-keyword">int</span>
    IsFiretruck() <span class="hljs-keyword">bool</span>
}
</code></pre>
<p><code>Color()</code> and <code>Speed()</code> make perfect sense, they are methods confined to the scope of a car. <code>IsFiretruck()</code> is an anti-pattern. We are forcing all cars to declare whether or not they are firetrucks. In order for this pattern to make any amount of sense, we would need a whole list of possible subtypes. <code>IsPickup()</code>, <code>IsSedan()</code>, <code>IsTank()</code>… where does it end??</p>
<p>Instead, the developer should have relied on the native functionality of type assertion to derive the underlying type when given an instance of the car interface. Or, if a sub-interface is needed, it can be defined as:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> firetruck <span class="hljs-keyword">interface</span> {
    car
    HoseLength() <span class="hljs-keyword">int</span>
}
</code></pre>
<p>Which inherits the required methods from <code>car</code> and adds one additional required method to make the <code>car</code> a <code>firetruck</code>.</p>
<h4 id="heading-3-interfaces-are-not-classes">3. Interfaces Are Not Classes</h4>
<ul>
<li><p>Interfaces are not classes, they are slimmer.</p>
</li>
<li><p>Interfaces don’t have constructors or deconstructors that require that data is created or destroyed.</p>
</li>
<li><p>Interfaces aren’t hierarchical by nature, though there is syntactic sugar to create interfaces that happen to be supersets of other interfaces.</p>
</li>
<li><p>Interfaces define function signatures, but not underlying behavior. Making an interface often won’t DRY up your code in regards to struct methods. For example, if five types satisfy the <code>fmt.Stringer</code> interface, they all need their own version of the <code>String()</code> function.</p>
</li>
</ul>
<h2 id="heading-chapter-7-errors-in-go">Chapter 7 – Errors in Go</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Nf17bnV2Tlw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Go programs express errors with <code>error</code> values. An Error is any type that implements the simple built-in <a target="_blank" href="https://blog.golang.org/error-handling-and-go">error interface</a>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> error <span class="hljs-keyword">interface</span> {
    Error() <span class="hljs-keyword">string</span>
}
</code></pre>
<p>When something can go wrong in a function, that function should return an <code>error</code> as its last return value. Any code that calls a function that can return an <code>error</code> should handle errors by testing whether the error is <code>nil</code>.</p>
<pre><code class="lang-go"><span class="hljs-comment">// Atoi converts a stringified number to an interger</span>
i, err := strconv.Atoi(<span class="hljs-string">"42b"</span>)
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    fmt.Println(<span class="hljs-string">"couldn't convert:"</span>, err)
    <span class="hljs-comment">// because "42b" isn't a valid integer, we print:</span>
    <span class="hljs-comment">// couldn't convert: strconv.Atoi: parsing "42b": invalid syntax</span>
    <span class="hljs-comment">// Note:</span>
    <span class="hljs-comment">// 'parsing "42b": invalid syntax' is returned by the .Error() method</span>
    <span class="hljs-keyword">return</span>
}
<span class="hljs-comment">// if we get here, then</span>
<span class="hljs-comment">// i was converted successfully</span>
</code></pre>
<p>A <code>nil</code> error denotes success. A non-nil error denotes failure.</p>
<h3 id="heading-the-error-interface">The Error Interface</h3>
<p>Because errors are just interfaces, you can build your own custom types that implement the <code>error</code> interface. Here's an example of a <code>userError</code> struct that implements the <code>error</code> interface:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> userError <span class="hljs-keyword">struct</span> {
    name <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e userError)</span> <span class="hljs-title">Error</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-keyword">return</span> fmt.Sprintf(<span class="hljs-string">"%v has a problem with their account"</span>, e.name)
}
</code></pre>
<p>It can then be used as an error:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sendSMS</span><span class="hljs-params">(msg, userName <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-keyword">if</span> !canSendToUser(userName) {
        <span class="hljs-keyword">return</span> userError{name: userName}
    }
    ...
}
</code></pre>
<p>Go programs express errors with <code>error</code> values. Error-values are any type that implements the simple built-in <a target="_blank" href="https://blog.golang.org/error-handling-and-go">error interface</a>.</p>
<p>Keep in mind that the way Go handles errors is fairly unique. Most languages treat errors as something special and different. For example, Python raises exception types and JavaScript throws and catches errors.</p>
<p>In Go, an <code>error</code> is just another value that we handle like any other value – however, we want! There aren't any special keywords for dealing with them.</p>
<h3 id="heading-the-errors-package">The errors Package</h3>
<p>The Go standard library provides an "errors" package that makes it easy to deal with errors.</p>
<p>Read the godoc for the <a target="_blank" href="https://pkg.go.dev/errors#New">errors.New()</a> function, but here's a simple example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> err error = errors.New(<span class="hljs-string">"something went wrong"</span>)
</code></pre>
<h2 id="heading-chapter-8-loops-in-go">Chapter 8 – Loops in Go</h2>
<p>The <a target="_blank" href="https://blog.boot.dev/golang/golang-for-loop/">basic loop in Go</a> is written in standard C-like syntax:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> INITIAL; CONDITION; AFTER{
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p><code>INITIAL</code> is run once at the beginning of the loop and can create variables within the scope of the loop.</p>
<p><code>CONDITION</code> is checked before each iteration. If the condition doesn't pass then the loop breaks.</p>
<p><code>AFTER</code> is run after each iteration.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
  fmt.Println(i)
}
<span class="hljs-comment">// Prints 0 through 9</span>
</code></pre>
<h3 id="heading-how-to-omit-conditions">How to Omit Conditions</h3>
<p>Loops in Go can omit sections of a for loop. For example, the <code>CONDITION</code> (middle part) can be omitted which causes the loop to run forever.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> INITIAL; ; AFTER {
  <span class="hljs-comment">// do something forever</span>
}
</code></pre>
<h3 id="heading-no-while-loops-in-go">No while loops in Go</h3>
<p>Most programming languages have a concept of a <code>while</code> loop. Because Go allows for the omission of sections of a <code>for</code> loop, a <code>while</code> loop is just a <code>for</code> loop that only has a CONDITION.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> CONDITION {
  <span class="hljs-comment">// do some stuff while CONDITION is true</span>
}
</code></pre>
<p>For example:</p>
<pre><code class="lang-go">plantHeight := <span class="hljs-number">1</span>
<span class="hljs-keyword">for</span> plantHeight &lt; <span class="hljs-number">5</span> {
  fmt.Println(<span class="hljs-string">"still growing! current height:"</span>, plantHeight)
  plantHeight++
}
fmt.Println(<span class="hljs-string">"plant has grown to "</span>, plantHeight, <span class="hljs-string">"inches"</span>)
</code></pre>
<p>Which prints:</p>
<pre><code class="lang-python">still growing! current height: <span class="hljs-number">1</span>
still growing! current height: <span class="hljs-number">2</span>
still growing! current height: <span class="hljs-number">3</span>
still growing! current height: <span class="hljs-number">4</span>
plant has grown to <span class="hljs-number">5</span> inches
</code></pre>
<h3 id="heading-continue-through-a-loop">Continue through a loop</h3>
<p>The <code>continue</code> keyword stops the current iteration of a loop and continues to the next iteration. <code>continue</code> is a powerful way to use the "guard clause" pattern within loops.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
  <span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> {
    <span class="hljs-keyword">continue</span>
  }
  fmt.Println(i)
}
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 7</span>
<span class="hljs-comment">// 9</span>
</code></pre>
<h3 id="heading-break-out-of-a-loop">Break out of a loop</h3>
<p>The <code>break</code> keyword stops the current iteration of a loop and exits the loop.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
  <span class="hljs-keyword">if</span> i == <span class="hljs-number">5</span> {
    <span class="hljs-keyword">break</span>
  }
  fmt.Println(i)
}
<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
</code></pre>
<h2 id="heading-chapter-9-arrays-and-slices-in-go">Chapter 9 – Arrays and Slices in Go</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NFF2usIBX-U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-arrays">Arrays</h3>
<p>Arrays are fixed-size groups of variables of the same type.</p>
<p>The type <code>[n]T</code> is an array of n values of type <code>T</code>.</p>
<p>To declare an array of 10 integers:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> myInts [<span class="hljs-number">10</span>]<span class="hljs-keyword">int</span>
</code></pre>
<p>or to declare an initialized literal:</p>
<pre><code class="lang-go">primes := [<span class="hljs-number">6</span>]<span class="hljs-keyword">int</span>{<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>}
</code></pre>
<h3 id="heading-slices">Slices</h3>
<p><em>99 times out of 100</em> you will use a slice instead of an array when working with ordered lists.</p>
<p>Arrays are fixed in size. Once you make an array like <code>[10]int</code> you can't add an 11th element.</p>
<p>A slice is a <em>dynamically-sized</em>, <em>flexible</em> view of the elements of an array.</p>
<p>Slices <strong>always</strong> have an underlying array, though it isn't always specified explicitly. To explicitly create a slice on top of an array we can do:</p>
<pre><code class="lang-go">primes := [<span class="hljs-number">6</span>]<span class="hljs-keyword">int</span>{<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>}
mySlice := primes[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]
<span class="hljs-comment">// mySlice = {3, 5, 7}</span>
</code></pre>
<p>The syntax is:</p>
<pre><code class="lang-python">arrayname[lowIndex:highIndex]
arrayname[lowIndex:]
arrayname[:highIndex]
arrayname[:]
</code></pre>
<p>Where <code>lowIndex</code> is inclusive and <code>highIndex</code> is exclusive</p>
<p>Either <code>lowIndex</code> or <code>highIndex</code> or both can be omitted to use the entire array on that side.</p>
<h3 id="heading-how-to-create-new-slices-in-go">How to Create New Slices in Go</h3>
<p>Most of the time we don't need to think about the underlying array of a slice. We can create a new slice using the <code>make</code> function:</p>
<pre><code class="lang-go"><span class="hljs-comment">// func make([]T, len, cap) []T</span>
mySlice := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">int</span>, <span class="hljs-number">5</span>, <span class="hljs-number">10</span>)

<span class="hljs-comment">// the capacity argument is usually omitted and defaults to the length</span>
mySlice := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">int</span>, <span class="hljs-number">5</span>)
</code></pre>
<p>Slices created with <code>make</code> will be filled with the zero value of the type.</p>
<p>If we want to create a slice with a specific set of values, we can use a slice literal:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"I"</span>, <span class="hljs-string">"love"</span>, <span class="hljs-string">"go"</span>}
</code></pre>
<p>Note that the array brackets <em>do not</em> have a <code>3</code> in them. If they did, you'd have an <em>array</em> instead of a slice.</p>
<h4 id="heading-length">Length</h4>
<p>The length of a slice is simply the number of elements it contains. It is accessed using the built-in <code>len()</code> function:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"I"</span>, <span class="hljs-string">"love"</span>, <span class="hljs-string">"go"</span>}
fmt.Println(<span class="hljs-built_in">len</span>(mySlice)) <span class="hljs-comment">// 3</span>
</code></pre>
<h4 id="heading-capacity">Capacity</h4>
<p>The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice. It is accessed using the built-in <code>cap()</code> function:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"I"</span>, <span class="hljs-string">"love"</span>, <span class="hljs-string">"go"</span>}
fmt.Println(<span class="hljs-built_in">cap</span>(mySlice)) <span class="hljs-comment">// 3</span>
</code></pre>
<p>Generally speaking, unless you're hyper-optimizing the memory usage of your program, you don't need to worry about the capacity of a slice because it will automatically grow as needed.</p>
<h3 id="heading-variadic-functions">Variadic Functions</h3>
<p>Many functions, especially those in the standard library, can take an arbitrary number of <em>final</em> arguments. This is accomplished by using the "..." syntax in the function signature.</p>
<p>A variadic function receives the variadic arguments as a slice.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">concat</span><span class="hljs-params">(strs ...<span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
    final := <span class="hljs-string">""</span>
    <span class="hljs-comment">// strs is just a slice of strings</span>
    <span class="hljs-keyword">for</span> str := <span class="hljs-keyword">range</span> strs {
        final += str
    }
    <span class="hljs-keyword">return</span> final
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    final := concat(<span class="hljs-string">"Hello "</span>, <span class="hljs-string">"there "</span>, <span class="hljs-string">"friend!"</span>)
    fmt.Println(total)
    <span class="hljs-comment">// Output: Hello there friend!</span>
}
</code></pre>
<p>The familiar <a target="_blank" href="https://pkg.go.dev/fmt#Println">fmt.Println()</a> and <a target="_blank" href="https://pkg.go.dev/fmt#Sprintf">fmt.Sprintf()</a> are variadic! <code>fmt.Println()</code> prints each element with space <a target="_blank" href="https://www.dictionary.com/browse/delimited">delimiters</a> and a newline at the end.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Println</span><span class="hljs-params">(a ...<span class="hljs-keyword">interface</span>{})</span> <span class="hljs-params">(n <span class="hljs-keyword">int</span>, err error)</span></span>
</code></pre>
<h4 id="heading-spread-operator">Spread operator</h4>
<p>The spread operator allows us to pass a slice <em>into</em> a variadic function. The spread operator consists of three dots following the slice in the function call.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">printStrings</span><span class="hljs-params">(strings ...<span class="hljs-keyword">string</span>)</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(strings); i++ {
        fmt.Println(strings[i])
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    names := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"bob"</span>, <span class="hljs-string">"sue"</span>, <span class="hljs-string">"alice"</span>}
    printStrings(names...)
}
</code></pre>
<h3 id="heading-how-to-append-to-a-slice">How to Append to a Slice</h3>
<p>The built-in append function is used to dynamically add elements to a slice:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">append</span><span class="hljs-params">(slice []Type, elems ...Type)</span> []<span class="hljs-title">Type</span></span>
</code></pre>
<p>If the underlying array is not large enough, <code>append()</code> will create a new underlying array and point the slice to it.</p>
<p>Notice that <code>append()</code> is variadic. The following are all valid:</p>
<pre><code class="lang-go">slice = <span class="hljs-built_in">append</span>(slice, oneThing)
slice = <span class="hljs-built_in">append</span>(slice, firstThing, secondThing)
slice = <span class="hljs-built_in">append</span>(slice, anotherSlice...)
</code></pre>
<h3 id="heading-how-to-range-over-a-slice-in-go">How to Range Over a Slice in Go</h3>
<p>Go provides syntactic sugar to iterate easily over elements of a slice:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> INDEX, ELEMENT := <span class="hljs-keyword">range</span> SLICE {
}
</code></pre>
<p>For example:</p>
<pre><code class="lang-go">fruits := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>}
<span class="hljs-keyword">for</span> i, fruit := <span class="hljs-keyword">range</span> fruits {
    fmt.Println(i, fruit)
}
<span class="hljs-comment">// 0 apple</span>
<span class="hljs-comment">// 1 banana</span>
<span class="hljs-comment">// 2 grape</span>
</code></pre>
<h2 id="heading-chapter-10-maps-in-go">Chapter 10 – Maps in Go</h2>
<p>Maps are similar to JavaScript objects, Python dictionaries, and Ruby hashes. Maps are a data structure that provides key-&gt;value mapping.</p>
<p>The zero value of a map is <code>nil</code>.</p>
<p>We can <a target="_blank" href="https://blog.boot.dev/golang/golang-make-maps-and-slices/">create a map</a> by using a literal or by using the <code>make()</code> function:</p>
<pre><code class="lang-go">ages := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>)
ages[<span class="hljs-string">"John"</span>] = <span class="hljs-number">37</span>
ages[<span class="hljs-string">"Mary"</span>] = <span class="hljs-number">24</span>
ages[<span class="hljs-string">"Mary"</span>] = <span class="hljs-number">21</span> <span class="hljs-comment">// overwrites 24</span>
</code></pre>
<pre><code class="lang-go">ages = <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
  <span class="hljs-string">"John"</span>: <span class="hljs-number">37</span>,
  <span class="hljs-string">"Mary"</span>: <span class="hljs-number">21</span>,
}
</code></pre>
<p>The <code>len()</code> function works on a map – it returns the total number of key/value pairs.</p>
<pre><code class="lang-go">ages = <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
  <span class="hljs-string">"John"</span>: <span class="hljs-number">37</span>,
  <span class="hljs-string">"Mary"</span>: <span class="hljs-number">21</span>,
}
fmt.Println(<span class="hljs-built_in">len</span>(ages)) <span class="hljs-comment">// 2</span>
</code></pre>
<h3 id="heading-map-mutations">Map Mutations</h3>
<h4 id="heading-insert-an-element">Insert an element</h4>
<pre><code class="lang-go">m[key] = elem
</code></pre>
<h4 id="heading-get-an-element">Get an element</h4>
<pre><code class="lang-go">elem = m[key]
</code></pre>
<h4 id="heading-delete-an-element">Delete an element</h4>
<pre><code class="lang-go"><span class="hljs-built_in">delete</span>(m, key)
</code></pre>
<h4 id="heading-check-if-a-key-exists">Check if a key exists</h4>
<pre><code class="lang-go">elem, ok := m[key]
</code></pre>
<p>If <code>key</code> is in <code>m</code>, then <code>ok</code> is <code>true</code>. If not, <code>ok</code> is <code>false</code>.</p>
<p>If <code>key</code> is not in the map, then <code>elem</code> is the zero value for the map's element type.</p>
<h3 id="heading-types-of-valid-map-keys">Types of Valid Map Keys</h3>
<p>Any type can be used as the <em>value</em> in a map, but <em>keys</em> are more restrictive.</p>
<p>You can read more in the following section of the official <a target="_blank" href="https://go.dev/blog/maps">Go blog</a>.</p>
<p>As mentioned earlier, <strong>map keys may be of any type that is comparable</strong>. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types.</p>
<p>Notably absent from the list are slices, maps, and functions. These types cannot be compared using ==, and may not be used as map keys.</p>
<p>It's obvious that strings, ints, and other basic types should be available as map keys, but perhaps unexpected are struct keys. Struct can be used to key data by multiple dimensions.</p>
<p>For example, this map of maps could be used to tally web page hits by country:</p>
<pre><code class="lang-go">hits := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>)
</code></pre>
<p>This is map of string to (map of string to int). Each key of the outer map is the path to a web page with its own inner map. Each inner map key is a two-letter country code. This expression retrieves the number of times an Australian has loaded the documentation page:</p>
<pre><code class="lang-go">n := hits[<span class="hljs-string">"/doc/"</span>][<span class="hljs-string">"au"</span>]
</code></pre>
<p>Unfortunately, this approach becomes unwieldy when adding data, as for any given outer key you must check if the inner map exists, and create it if needed:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">add</span><span class="hljs-params">(m <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>, path, country <span class="hljs-keyword">string</span>)</span></span> {
    mm, ok := m[path]
    <span class="hljs-keyword">if</span> !ok {
        mm = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>)
        m[path] = mm
    }
    mm[country]++
}
add(hits, <span class="hljs-string">"/doc/"</span>, <span class="hljs-string">"au"</span>)
</code></pre>
<p>On the other hand, a design that uses a single map with a struct key does away with all that complexity:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Key <span class="hljs-keyword">struct</span> {
    Path, Country <span class="hljs-keyword">string</span>
}
hits := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[Key]<span class="hljs-keyword">int</span>)
</code></pre>
<p>When a Vietnamese person visits the home page, incrementing (and possibly creating) the appropriate counter is a one-liner:</p>
<pre><code class="lang-go">hits[Key{<span class="hljs-string">"/"</span>, <span class="hljs-string">"vn"</span>}]++
</code></pre>
<p>And it’s similarly straightforward to see how many Swiss people have read the spec:</p>
<pre><code class="lang-go">n := hits[Key{<span class="hljs-string">"/ref/spec"</span>, <span class="hljs-string">"ch"</span>}]
</code></pre>
<h3 id="heading-nested-maps">Nested Maps</h3>
<p>Maps can contain maps, creating a nested structure. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>
<span class="hljs-keyword">map</span>[<span class="hljs-keyword">rune</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>
<span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>
</code></pre>
<h2 id="heading-chapter-11-advanced-functions-in-go">Chapter 11 – Advanced Functions in Go</h2>
<h3 id="heading-first-class-and-higher-order-functions">First-class and higher-order functions</h3>
<p>A programming language is said to have "first-class functions" when functions in that language are treated like any other variable.</p>
<p>For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function, and can be assigned as a value to a variable.</p>
<p>A function that returns a function or accepts a function as input is called a Higher-Order Function.</p>
<p>Go supports <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first-class</a> and higher-order functions. Another way to think of this is that a function is just another type – just like <code>int</code>s and <code>string</code>s and <code>bool</code>s.</p>
<p>For example, to accept a function as a parameter:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x + y
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">mul</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x * y
}

<span class="hljs-comment">// aggregate applies the given math function to the first 3 inputs</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">aggregate</span><span class="hljs-params">(a, b, c <span class="hljs-keyword">int</span>, arithmetic <span class="hljs-keyword">func</span>(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span>) <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> arithmetic(arithmetic(a, b), c)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
  fmt.Println(aggregate(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>, add))
  <span class="hljs-comment">// prints 9</span>
  fmt.Println(aggregate(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>, mul))
  <span class="hljs-comment">// prints 24</span>
}
</code></pre>
<h3 id="heading-function-currying-in-go">Function Currying in Go</h3>
<p>Function currying is the practice of writing a function that takes a function (or functions) as input, and returns a new function.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  squareFunc := selfMath(multiply)
  doubleFunc := selfMath(add)

  fmt.Println(squareFunc(<span class="hljs-number">5</span>))
  <span class="hljs-comment">// prints 25</span>

  fmt.Println(doubleFunc(<span class="hljs-number">5</span>))
  <span class="hljs-comment">// prints 10</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">multiply</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x * y
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> x + y
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">selfMath</span><span class="hljs-params">(mathFunc <span class="hljs-keyword">func</span>(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span>) <span class="hljs-title">func</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> mathFunc(x, x)
  }
}
</code></pre>
<p>In the example above, the <code>selfMath</code> function takes in a function as its parameter, and returns a function that itself returns the value of running that input function on its parameter.</p>
<h3 id="heading-defer-keyword">Defer keyword</h3>
<p>The <code>defer</code> keyword is a fairly unique feature of Go. It allows a function to be executed automatically <em>just before</em> its enclosing function returns.</p>
<p>The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.</p>
<p><a target="_blank" href="https://blog.boot.dev/golang/defer-golang/">Deferred functions</a> are typically used to close database connections, file handlers and the like.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-comment">// CopyFile copies a file from srcName to dstName on the local filesystem.</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">CopyFile</span><span class="hljs-params">(dstName, srcName <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(written <span class="hljs-keyword">int64</span>, err error)</span></span> {

  <span class="hljs-comment">// Open the source file</span>
  src, err := os.Open(srcName)
  <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    <span class="hljs-keyword">return</span>
  }
  <span class="hljs-comment">// Close the source file when the CopyFile function returns</span>
  <span class="hljs-keyword">defer</span> src.Close()

  <span class="hljs-comment">// Create the destination file</span>
  dst, err := os.Create(dstName)
  <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    <span class="hljs-keyword">return</span>
  }
  <span class="hljs-comment">// Close the destination file when the CopyFile function returns</span>
  <span class="hljs-keyword">defer</span> dst.Close()

  <span class="hljs-keyword">return</span> io.Copy(dst, src)
}
</code></pre>
<p>In the above example, the <code>src.Close()</code> function is not called until after the <code>CopyFile</code> function was called but immediately before the <code>CopyFile</code> function returns.</p>
<p>Defer is a great way to <strong>make sure</strong> that something happens at the end of a function, even if there are multiple return statements.</p>
<h3 id="heading-closures">Closures</h3>
<p>A closure is a function that references variables from outside its own function body. The function may access and <em>assign</em> to the referenced variables.</p>
<p>In this example, the <code>concatter()</code> function returns a function that has reference to an <em>enclosed</em> <code>doc</code> value. Each successive call to <code>harryPotterAggregator</code> mutates that same <code>doc</code> variable.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">concatter</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
    doc := <span class="hljs-string">""</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(word <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
        doc += word + <span class="hljs-string">" "</span>
        <span class="hljs-keyword">return</span> doc
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    harryPotterAggregator := concatter()
    harryPotterAggregator(<span class="hljs-string">"Mr."</span>)
    harryPotterAggregator(<span class="hljs-string">"and"</span>)
    harryPotterAggregator(<span class="hljs-string">"Mrs."</span>)
    harryPotterAggregator(<span class="hljs-string">"Dursley"</span>)
    harryPotterAggregator(<span class="hljs-string">"of"</span>)
    harryPotterAggregator(<span class="hljs-string">"number"</span>)
    harryPotterAggregator(<span class="hljs-string">"four,"</span>)
    harryPotterAggregator(<span class="hljs-string">"Privet"</span>)

    fmt.Println(harryPotterAggregator(<span class="hljs-string">"Drive"</span>))
    <span class="hljs-comment">// Mr. and Mrs. Dursley of number four, Privet Drive</span>
}
</code></pre>
<h3 id="heading-anonymous-functions">Anonymous Functions</h3>
<p>Anonymous functions are true to form in that they have <em>no name</em>. We've been using them throughout this chapter, but we haven't really talked about them yet.</p>
<p>Anonymous functions are useful when defining a function that will only be used once or to create a quick <a target="_blank" href="https://en.wikipedia.org/wiki/Closure_\(computer_programming\)">closure</a>.</p>
<pre><code class="lang-go"><span class="hljs-comment">// doMath accepts a function that converts one int into another</span>
<span class="hljs-comment">// and a slice of ints. It returns a slice of ints that have been</span>
<span class="hljs-comment">// converted by the passed in function.</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">doMath</span><span class="hljs-params">(f <span class="hljs-keyword">func</span>(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span>, <span class="hljs-title">nums</span> []<span class="hljs-title">int</span>) []<span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">var</span> results []<span class="hljs-keyword">int</span>
    <span class="hljs-keyword">for</span> _, n := <span class="hljs-keyword">range</span> nums {
        results = <span class="hljs-built_in">append</span>(results, f(n))
    }
    <span class="hljs-keyword">return</span> results
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    nums := []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

    <span class="hljs-comment">// Here we define an anonymous function that doubles an int</span>
    <span class="hljs-comment">// and pass it to doMath</span>
    allNumsDoubled := doMath(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        <span class="hljs-keyword">return</span> x + x
    }, nums)

    fmt.Println(allNumsDoubled)
    <span class="hljs-comment">// prints:</span>
    <span class="hljs-comment">// [2 4 6 8 10]</span>
}
</code></pre>
<h2 id="heading-chapter-12-pointers-in-go">Chapter 12 – Pointers in Go</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/MhQw9FNWVMQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>As we have learned, a variable is a named location in memory that stores a value. We can manipulate the value of a variable by assigning a new value to it or by performing operations on it. When we assign a value to a variable, we are storing that value in a specific location in memory.</p>
<pre><code class="lang-go">x := <span class="hljs-number">42</span>
<span class="hljs-comment">// "x" is the name of a location in memory. That location is storing the integer value of 42</span>
</code></pre>
<h4 id="heading-a-pointer-is-a-variable">A pointer is a variable</h4>
<p>A pointer is a variable that stores the <em>memory address</em> of another variable. This means that a pointer "points to" the <em>location</em> of where the data is stored <em>NOT</em> the actual data itself.</p>
<p>The <code>*</code> syntax defines a pointer:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> p *<span class="hljs-keyword">int</span>
</code></pre>
<p>The <code>&amp;</code> operator generates a pointer to its operand.</p>
<pre><code class="lang-go">myString := <span class="hljs-string">"hello"</span>
myStringPtr = &amp;myString
</code></pre>
<h4 id="heading-why-are-pointers-useful">Why are pointers useful?</h4>
<p>Pointers allow us to manipulate data in memory directly, without making copies or duplicating data. This can make programs more efficient and allow us to do things that would be difficult or impossible without them.</p>
<h3 id="heading-pointer-syntax">Pointer Syntax</h3>
<p>The <code>*</code> syntax defines a pointer:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> p *<span class="hljs-keyword">int</span>
</code></pre>
<p>A pointer's zero value is <code>nil</code></p>
<p>The <code>&amp;</code> operator generates a pointer to its operand:</p>
<pre><code class="lang-go">myString := <span class="hljs-string">"hello"</span>
myStringPtr = &amp;myString
</code></pre>
<p>The <code>*</code> dereferences a pointer to gain access to the value:</p>
<pre><code class="lang-go">fmt.Println(*myStringPtr) <span class="hljs-comment">// read myString through the pointer</span>
*myStringPtr = <span class="hljs-string">"world"</span>    <span class="hljs-comment">// set myString through the pointer</span>
</code></pre>
<p>Unlike C, Go has no <a target="_blank" href="https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm">pointer arithmetic</a></p>
<h4 id="heading-just-because-you-can-doesnt-mean-you-should">Just because you can doesn't mean you should</h4>
<p>We're doing this exercise to understand that pointers <strong>can</strong> be used in this way. That said, pointers can be <em>very</em> dangerous. It's generally a better idea to have your functions accept non-pointers and return new values rather than mutating pointer inputs.</p>
<h3 id="heading-nil-pointers">Nil Pointers</h3>
<p>Again, pointers can be very dangerous.</p>
<p>If a pointer points to nothing (the zero value of the pointer type) then dereferencing it will cause a runtime error (a <a target="_blank" href="https://gobyexample.com/panic">panic</a>) that crashes the program.</p>
<p>Generally speaking, whenever you're dealing with pointers you should check if it's <code>nil</code> before trying to dereference it.</p>
<h3 id="heading-pointer-method-receivers">Pointer Method Receivers</h3>
<p>A receiver type on a method can be a pointer.</p>
<p>Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are <em>more common</em> than value receivers.</p>
<h4 id="heading-pointer-receiver">Pointer receiver</h4>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
    color <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c *car)</span> <span class="hljs-title">setColor</span><span class="hljs-params">(color <span class="hljs-keyword">string</span>)</span></span> {
    c.color = color
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    c := car{
        color: <span class="hljs-string">"white"</span>,
    }
    c.setColor(<span class="hljs-string">"blue"</span>)
    fmt.Println(c.color)
    <span class="hljs-comment">// prints "blue"</span>
}
</code></pre>
<h4 id="heading-non-pointer-receiver">Non-pointer receiver</h4>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> car <span class="hljs-keyword">struct</span> {
    color <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c car)</span> <span class="hljs-title">setColor</span><span class="hljs-params">(color <span class="hljs-keyword">string</span>)</span></span> {
    c.color = color
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    c := car{
        color: <span class="hljs-string">"white"</span>,
    }
    c.setColor(<span class="hljs-string">"blue"</span>)
    fmt.Println(c.color)
    <span class="hljs-comment">// prints "white"</span>
}
</code></pre>
<p>Methods with pointer receivers don't require that a pointer is used to call the method. The pointer will automatically be derived from the value.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> circle <span class="hljs-keyword">struct</span> {
    x <span class="hljs-keyword">int</span>
    y <span class="hljs-keyword">int</span>
    radius <span class="hljs-keyword">int</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c *circle)</span> <span class="hljs-title">grow</span><span class="hljs-params">()</span></span>{
    c.radius *= <span class="hljs-number">2</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    c := circle{
        x: <span class="hljs-number">1</span>,
        y: <span class="hljs-number">2</span>,
        radius: <span class="hljs-number">4</span>,
    }

    <span class="hljs-comment">// notice c is not a pointer in the calling function</span>
    <span class="hljs-comment">// but the method still gains access to a pointer to c</span>
    c.grow()
    fmt.Println(c.radius)
    <span class="hljs-comment">// prints 8</span>
}
</code></pre>
<h2 id="heading-chapter-13-local-development-environment-in-go">Chapter 13 – Local Development Environment in Go</h2>
<h3 id="heading-packages">Packages</h3>
<p>Make sure you have <a target="_blank" href="https://go.dev/doc/install">Go installed</a> on your local machine.</p>
<p>Every Go program is made up of packages.</p>
<p>You have probably noticed the <code>package main</code> at the top of all the programs you have been writing.</p>
<p>A package named "main" has an entrypoint at the <code>main()</code> function. A <code>main</code> package is compiled into an executable program.</p>
<p>A package by any other name is a "library package". Libraries have no entry point. Libraries simply export functionality that can be used by other packages. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"math/rand"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"My favorite number is"</span>, rand.Intn(<span class="hljs-number">10</span>))
}
</code></pre>
<p>This program is an executable. It is a "main" package and <em>imports</em> from the <code>fmt</code> and <code>math/rand</code> library packages.</p>
<h3 id="heading-package-names">Package Names</h3>
<h4 id="heading-naming-convention">Naming Convention</h4>
<p>By <em>convention</em>, a package's name is the same as the last element of its import path. For instance, the <code>math/rand</code> package comprises files that begin with:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> rand
</code></pre>
<p>That said, package names aren't <em>required</em> to match their import path. For example, I could write a new package with the path <code>github.com/mailio/rand</code> and name the package <code>random</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> random
</code></pre>
<p>While the above is possible, it is discouraged for the sake of consistency.</p>
<h4 id="heading-one-package-directory">One Package / Directory</h4>
<p>A directory of Go code can have <strong>at most</strong> one package. All <code>.go</code> files in a single directory must all belong to the same package. If they don't an error will be thrown by the compiler. This is true for main and library packages alike.</p>
<h3 id="heading-go-modules">Go Modules</h3>
<p>Go programs are organized into <em>packages</em>. A package is a directory of Go code that's all compiled together. Functions, types, variables, and constants defined in one source file are visible to <strong>all other source files within the same package (directory)</strong>.</p>
<p>A <em>repository</em> contains one or more <em>modules</em>. A module is a collection of Go packages that are released together.</p>
<h4 id="heading-a-go-repository-typically-contains-only-one-module-located-at-the-root-of-the-repository">A Go repository typically contains only one module, located at the root of the repository.</h4>
<p>A file named <code>go.mod</code> at the root of a project declares the module. It contains:</p>
<ul>
<li><p>The module path</p>
</li>
<li><p>The version of the Go language your project requires</p>
</li>
<li><p>Optionally, any external package dependencies your project has</p>
</li>
</ul>
<p>The module path is just the import path prefix for all packages within the module. Here's an example of a <code>go.mod</code> file:</p>
<pre><code class="lang-python">module github.com/bootdotdev/exampleproject

go <span class="hljs-number">1.20</span>

require github.com/google/examplepackage v1<span class="hljs-number">.3</span><span class="hljs-number">.0</span>
</code></pre>
<p>Each module's path not only serves as an import path prefix for the packages within but <em>also indicates where the go command should look to download it</em>.</p>
<p>For example, to download the module <code>golang.org/x/tools</code>, the go command would consult the repository located at <a target="_blank" href="https://golang.org/x/tools">https://golang.org/x/tools</a>.</p>
<blockquote>
<p>An "import path" is a string used to import a package. A package's import path is its module path joined with its subdirectory within the module. For example, the module <code>github.com/google/go-cmp</code> contains a package in the directory <code>cmp/</code>. That package's import path is <code>github.com/google/go-cmp/cmp</code>. Packages in the standard library do not have a module path prefix. – Paraphrased from Golang.org's <a target="_blank" href="https://golang.org/doc/code#Organization">code organization</a></p>
</blockquote>
<h4 id="heading-do-i-need-to-put-my-package-on-github">Do I need to put my package on GitHub?</h4>
<p>You don't need to publish your code to a remote repository before you can build it. A module can be defined locally without belonging to a repository. But it's a good habit to keep a copy of all your projects on a remote server, like GitHub.</p>
<h3 id="heading-how-to-set-up-your-machine">How to Set Up Your Machine</h3>
<p>Your machine will contain many version control <em>repositories</em> (managed by Git, for example).</p>
<p>Each repository contains one or more <em>packages</em>, but will typically be a single <em>module</em>.</p>
<p>Each package consists of one or more <em>Go source files</em> in a single directory.</p>
<p>The path to a package's directory determines its <em>import path</em> and where it can be downloaded from if you decide to host it on a remote version control system like Github or Gitlab.</p>
<h4 id="heading-a-note-on-gopath">A note on GOPATH</h4>
<p>The $GOPATH environment variable will be set by default somewhere on your machine (typically in the home directory, <code>~/go</code>). Since we will be working in the new "Go modules" setup, you <em>don't need to worry about that</em>. If you read something online about setting up your GOPATH, that documentation is probably out of date.</p>
<p>These days you should avoid working in the <code>$GOPATH/src</code> directory. Again, that's the old way of doing things and can cause unexpected issues, so better to just avoid it.</p>
<h4 id="heading-get-into-your-workspace">Get into your workspace</h4>
<p>Navigate to a location on your machine where you want to store some code. For example, I store all my code in <code>~/workspace</code>, then organize it into subfolders based on the remote location. For example,</p>
<p><code>~/workspace/github.com/wagslane/go-password-validator</code> = <a target="_blank" href="https://github.com/wagslane/go-password-validator">https://github.com/wagslane/go-password-validator</a></p>
<p>That said, you can put your code wherever you want.</p>
<h3 id="heading-how-to-write-your-first-local-go-program">How to Write Your First Local Go Program</h3>
<p>Once inside your personal workspace, create a new directory and enter it:</p>
<pre><code class="lang-bash">mkdir hellogo
<span class="hljs-built_in">cd</span> hellogo
</code></pre>
<p>Inside the directory declare your module's name:</p>
<pre><code class="lang-bash">go mod init {REMOTE}/{USERNAME}/hellogo
</code></pre>
<p>Where <code>{REMOTE}</code> is your preferred remote source provider (i.e. <code>github.com</code>) and <code>{USERNAME}</code> is your Git username. If you don't use a remote provider yet, just use <code>example.com/username/hellogo</code></p>
<p>Print your <code>go.mod</code> file:</p>
<pre><code class="lang-bash">cat go.mod
</code></pre>
<h3 id="heading-the-go-run-command">The Go Run Command</h3>
<p>Inside <code>hellogo</code>, create a new file called <code>main.go</code>.</p>
<p>Conventionally, the file in the <code>main</code> package that contains the <code>main()</code> function is called <code>main.go</code>.</p>
<p>Paste the following code into your file:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"hello world"</span>)
}
</code></pre>
<h4 id="heading-run-the-code">Run the code</h4>
<pre><code class="lang-bash">go run main.go
</code></pre>
<p>The <code>go run</code> command is used to quickly compile and run a Go package. The compiled binary is <em>not</em> saved in your working directory. Use <code>go build</code> instead to compile production executables.</p>
<p>I rarely use <code>go run</code> other than to quickly do some testing or debugging.</p>
<h4 id="heading-further-reading">Further reading</h4>
<p>Execute <code>go help run</code> in your shell and read the instructions.</p>
<h3 id="heading-the-go-build-command">The Go Build Command</h3>
<p><code>go build</code> compiles go code into an executable program.</p>
<h4 id="heading-build-an-executable">Build an executable</h4>
<p>Ensure you are in your hellogo repo, then run:</p>
<pre><code class="lang-bash">go build
</code></pre>
<p>Run the new program:</p>
<pre><code class="lang-bash">./hellogo
</code></pre>
<h3 id="heading-go-install">Go Install</h3>
<h4 id="heading-build-an-executable-1">Build an executable</h4>
<p>Ensure you are in your <code>hellogo</code> repo, then run:</p>
<pre><code class="lang-bash">go install
</code></pre>
<p>Navigate out of your project directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ../
</code></pre>
<p>Go has installed the <code>hellogo</code> program globally. Run it with:</p>
<pre><code class="lang-bash">hellogo
</code></pre>
<h4 id="heading-tip-about-not-found">Tip about "not found"</h4>
<p>If you get an error regarding "hellogo not found" it means you probably don't have your Go environment setup properly. Specifically, <code>go install</code> is adding your binary to your <code>GOBIN</code> directory, but that may not be in your <code>PATH</code>.</p>
<p>You can read more about that here in the <a target="_blank" href="https://pkg.go.dev/cmd/go#hdr-Compile_and_install_packages_and_dependencies">go install docs</a>.</p>
<h3 id="heading-how-to-create-a-custom-go-package">How to Create a Custom Go Package</h3>
<p>Let's write a package to import and use in <code>hellogo</code>.</p>
<p>Create a sibling directory at the same level as the <code>hellogo</code> directory:</p>
<pre><code class="lang-bash">mkdir mystrings
<span class="hljs-built_in">cd</span> mystrings
</code></pre>
<p>Initialize a module:</p>
<pre><code class="lang-bash">go mod init {REMOTE}/{USERNAME}/mystrings
</code></pre>
<p>Then create a new file <code>mystrings.go</code> in that directory and paste the following code:</p>
<pre><code class="lang-go"><span class="hljs-comment">// by convention, we name our package the same as the directory</span>
<span class="hljs-keyword">package</span> mystrings

<span class="hljs-comment">// Reverse reverses a string left to right</span>
<span class="hljs-comment">// Notice that we need to capitalize the first letter of the function</span>
<span class="hljs-comment">// If we don't then we won't be able access this function outside of the</span>
<span class="hljs-comment">// mystrings package</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Reverse</span><span class="hljs-params">(s <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
  result := <span class="hljs-string">""</span>
  <span class="hljs-keyword">for</span> _, v := <span class="hljs-keyword">range</span> s {
    result = <span class="hljs-keyword">string</span>(v) + result
  }
  <span class="hljs-keyword">return</span> result
}
</code></pre>
<p>Note that there is no <code>main.go</code> or <code>func main()</code> in this package.</p>
<p><code>go build</code> won't build an executable from a library package. However, <code>go build</code> will still compile the package and save it to our local build cache. It's useful for checking for compile errors.</p>
<p>Run:</p>
<pre><code class="lang-bash">go build
</code></pre>
<h3 id="heading-how-to-publish-remote-packages-in-go">How to Publish Remote Packages in Go</h3>
<p>Let's learn how to use an open-source package that's available online.</p>
<h4 id="heading-a-note-on-how-you-should-publish-modules">A note on how you should publish modules</h4>
<p>Be aware that using the "replace" keyword like we did in the last assignment <em>isn't advised</em>, but can be useful to get up and running quickly. The proper way to create and depend on modules is to publish them to a remote repository. When you do that, the "replace keyword can be dropped from the <code>go.mod</code>:</p>
<h4 id="heading-bad">Bad</h4>
<p>This works for local-only development</p>
<pre><code class="lang-go">module github.com/wagslane/hellogo

<span class="hljs-keyword">go</span> <span class="hljs-number">1.20</span>

replace github.com/wagslane/mystrings v0<span class="hljs-number">.0</span><span class="hljs-number">.0</span> =&gt; ../mystrings

require (
    github.com/wagslane/mystrings v0<span class="hljs-number">.0</span><span class="hljs-number">.0</span>
)
</code></pre>
<h4 id="heading-good">Good</h4>
<p>This works if we publish our modules to a remote location like Github as we should.</p>
<pre><code class="lang-go">module github.com/wagslane/hellogo

<span class="hljs-keyword">go</span> <span class="hljs-number">1.20</span>

require (
    github.com/wagslane/mystrings v0<span class="hljs-number">.0</span><span class="hljs-number">.0</span>
)
</code></pre>
<h3 id="heading-best-practices-with-go-packages">Best Practices with Go Packages</h3>
<p>I’ve often seen, and have been responsible for, throwing code into packages without much thought. I’ve quickly drawn a line in the sand and started putting code into different folders (which in Go are different packages by definition) just for the sake of findability.</p>
<p>Learning to properly build small and reusable packages can take your Go career to the next level.</p>
<h4 id="heading-1-hide-internal-logic">1. Hide internal logic</h4>
<p>If you're familiar with the pillars of OOP, this is a practice in <em>encapsulation</em>.</p>
<p>Oftentimes an application will have complex logic that requires a lot of code. In almost every case the logic that the application cares about can be exposed via an API, and most of the dirty work can be kept within a package.</p>
<p>For example, imagine we are building an application that needs to classify images. We could build a package:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> classifier

<span class="hljs-comment">// ClassifyImage classifies images as "hotdog" or "not hotdog"</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ClassifyImage</span><span class="hljs-params">(image []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-params">(imageType <span class="hljs-keyword">string</span>)</span></span> {
    <span class="hljs-keyword">return</span> hasHotdogColors(image) &amp;&amp; hasHotdogShape(image)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">hasHotdogShape</span><span class="hljs-params">(image []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-title">bool</span></span> {
    <span class="hljs-comment">// internal logic that the application doesn't need to know about</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">hasHotdogColors</span><span class="hljs-params">(image []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-title">bool</span></span> {
    <span class="hljs-comment">// internal logic that the application doesn't need to know about</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
}
</code></pre>
<p>We create an API by only exposing the function(s) that the application-level needs to know about. All other logic is unexported to keep a clean separation of concerns. The application doesn’t need to know how to classify an image, just the result of the classification.</p>
<h4 id="heading-2-dont-change-apis">2. Don’t change APIs</h4>
<p>The unexported functions within a package can and should change often for testing, refactoring, and bug fixing.</p>
<p>A well-designed library will have a stable API so that users aren’t receiving breaking changes each time they update the package version. In Go, this means not changing exported function’s signatures.</p>
<h4 id="heading-3-dont-export-functions-from-the-main-package">3. Don’t export functions from the main package</h4>
<p>A <code>main</code> package isn't a library, there's no need to export functions from it.</p>
<h4 id="heading-4-packages-shouldnt-know-about-dependents">4. Packages shouldn't know about dependents</h4>
<p>Perhaps one of the most important and most broken rules is that a package shouldn’t know anything about its dependents. In other words, a package should never have specific knowledge about a particular application that uses it.</p>
<h4 id="heading-further-reading-1">Further Reading</h4>
<p>You can optionally <a target="_blank" href="https://blog.boot.dev/golang/how-to-separate-library-packages-in-go/">read more here</a> if you're interested.</p>
<h2 id="heading-chapter-14-channels-in-go">Chapter 14 – Channels in Go</h2>
<h3 id="heading-concurrency">Concurrency</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/snK5wn00Lhw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Concurrency is the ability to perform multiple tasks at the same time. Typically, our code is executed one line at a time, one after the other. This is called <em>sequential execution</em> or <em>synchronous execution</em>.</p>
<p><img src="https://i.imgur.com/1pQKFgw.png" alt="concurrency" width="2092" height="1144" loading="lazy"></p>
<p>If the computer we're running our code on has multiple cores, we can even execute multiple tasks at <em>exactly</em> the same time. If we're running on a single core, a single code executes code at <em>almost</em> the same time by switching between tasks very quickly. Either way, the code we write looks the same in Go and takes advantage of whatever resources are available.</p>
<h4 id="heading-how-does-concurrency-work-in-go">How does concurrency work in Go?</h4>
<p>Go was designed to be concurrent, which is a trait <em>fairly</em> unique to Go. It excels at performing many tasks simultaneously and safely using a simple syntax.</p>
<p>There isn't a popular programming language in existence where spawning concurrent execution is quite as elegant, at least in my opinion.</p>
<p>Concurrency is as simple as using the <code>go</code> keyword when calling a function:</p>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> doSomething()
</code></pre>
<p>In the example above, <code>doSomething()</code> will be executed concurrently with the rest of the code in the function. The <code>go</code> keyword is used to spawn a new <a target="_blank" href="https://gobyexample.com/goroutines">goroutine</a>.</p>
<h3 id="heading-channels-in-go">Channels in Go</h3>
<p>Channels are a typed, thread-safe queue. Channels allow different goroutines to communicate with each other.</p>
<h4 id="heading-create-a-channel">Create a channel</h4>
<p>Like maps and slices, channels must be created <em>before</em> use. They also use the same <code>make</code> keyword:</p>
<pre><code class="lang-go">ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)
</code></pre>
<h4 id="heading-send-data-to-a-channel">Send data to a channel</h4>
<pre><code class="lang-go">ch &lt;- <span class="hljs-number">69</span>
</code></pre>
<p>The <code>&lt;-</code> operator is called the <em>channel operator</em>. Data flows in the direction of the arrow. This operation will <em>block</em> until another goroutine is ready to receive the value.</p>
<h4 id="heading-receive-data-from-a-channel">Receive data from a channel</h4>
<pre><code class="lang-go">v := &lt;-ch
</code></pre>
<p>This reads and removes a value from the channel and saves it into the variable <code>v</code>. This operation will <em>block</em> until there is a value in the channel to be read.</p>
<h4 id="heading-blocking-and-deadlocks">Blocking and deadlocks</h4>
<p>A <a target="_blank" href="https://yourbasic.org/golang/detect-deadlock/#:~:text=yourbasic.org%2Fgolang,look%20at%20this%20simple%20example.">deadlock</a> is when a group of goroutines are all blocking so none of them can continue. This is a common bug that you need to watch out for in concurrent programming.</p>
<h3 id="heading-tokens">Tokens</h3>
<p>Empty structs are often used as <code>tokens</code> in Go programs. In this context, a token is a <a target="_blank" href="https://en.wikipedia.org/wiki/Unary_operation">unary</a> value. In other words, we don't care <em>what</em> is passed through the channel. We care <em>when</em> and <em>if</em> it is passed.</p>
<p>We can block and wait until <em>something</em> is sent on a channel using the following syntax</p>
<pre><code class="lang-go">&lt;-ch
</code></pre>
<p>This will block until it pops a single item off the channel, then continue, discarding the item.</p>
<h3 id="heading-buffered-channels">Buffered Channels</h3>
<p>Channels can optionally be buffered.</p>
<h4 id="heading-how-to-create-a-channel-with-a-buffer">How to create a channel with a buffer</h4>
<p>You can provide a buffer length as the second argument to <code>make()</code> to create a buffered channel:</p>
<pre><code class="lang-go">ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, <span class="hljs-number">100</span>)
</code></pre>
<p>Sending on a buffered channel only blocks when the buffer is <em>full</em>.</p>
<p>Receiving blocks only when the buffer is <em>empty</em>.</p>
<h3 id="heading-how-to-close-channels">How to Close Channels</h3>
<p>Channels can be explicitly closed by a <em>sender</em>:</p>
<pre><code class="lang-go">ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)

<span class="hljs-comment">// do some stuff with the channel</span>

<span class="hljs-built_in">close</span>(ch)
</code></pre>
<h4 id="heading-how-to-check-if-a-channel-is-closed">How to check if a channel is closed</h4>
<p>Similar to the <code>ok</code> value when accessing data in a <code>map</code>, receivers can check the <code>ok</code> value when receiving from a channel to test if a channel was closed.</p>
<pre><code class="lang-go">v, ok := &lt;-ch
</code></pre>
<p>ok is <code>false</code> if the channel is empty and closed.</p>
<h4 id="heading-dont-send-on-a-closed-channel">Don't send on a closed channel</h4>
<p>Sending on a closed channel will cause a panic. A panic on the main goroutine will cause the entire program to crash, and a panic in any other goroutine will cause <em>that goroutine</em> to crash.</p>
<p>Closing isn't necessary. There's nothing wrong with leaving channels open, they'll still be garbage collected if they're unused. You should close channels to indicate explicitly to a receiver that nothing else is going to come across.</p>
<h3 id="heading-range-over-a-channel">Range Over a Channel</h3>
<p>Similar to slices and maps, channels can be ranged over.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> item := <span class="hljs-keyword">range</span> ch {
    <span class="hljs-comment">// item is the next value received from the channel</span>
}
</code></pre>
<p>This example will receive values over the channel (blocking at each iteration if nothing new is there) and will exit only when the channel is closed.</p>
<h3 id="heading-select-from-a-channel">Select from a channel</h3>
<p>Sometimes we have a single goroutine listening to multiple channels and want to process data in the order it comes through each channel.</p>
<p>A <code>select</code> statement is used to listen to multiple channels at the same time. It is similar to a <code>switch</code> statement but for channels.</p>
<pre><code class="lang-go"><span class="hljs-keyword">select</span> {
  <span class="hljs-keyword">case</span> i, ok := &lt;- chInts:
    fmt.Println(i)
  <span class="hljs-keyword">case</span> s, ok := &lt;- chStrings:
    fmt.Println(s)
}
</code></pre>
<p>The first channel with a value ready to be received will fire and its body will execute. If multiple channels are ready at the same time one is chosen randomly. The <code>ok</code> variable in the example above refers to whether or not the channel has been closed by the sender yet.</p>
<h3 id="heading-select-default">Select Default</h3>
<p>The <code>default</code> case in a <code>select</code> statement executes <em>immediately</em> if no other channel has a value ready. A <code>default</code> case stops the <code>select</code> statement from blocking.</p>
<pre><code class="lang-go"><span class="hljs-keyword">select</span> {
  <span class="hljs-keyword">case</span> v := &lt;-ch:
    <span class="hljs-comment">// use v</span>
  <span class="hljs-keyword">default</span>:
    <span class="hljs-comment">// receiving from ch would block</span>
    <span class="hljs-comment">// so do something else</span>
}
</code></pre>
<h2 id="heading-chapter-15-mutexes-in-go">Chapter 15 – Mutexes in Go</h2>
<p><a target="_blank" href="https://blog.boot.dev/golang/golang-mutex/">Mutexes</a> allow us to <em>lock</em> access to data. This ensures that we can control which goroutines can access certain data at which time.</p>
<p>Go's standard library provides a built-in implementation of a mutex with the <a target="_blank" href="https://pkg.go.dev/sync#Mutex">sync.Mutex</a> type and its two methods:</p>
<ul>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#Mutex.Lock">.Lock()</a></p>
</li>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#Mutex.Unlock">.Unlock()</a></p>
</li>
</ul>
<p>We can protect a block of code by surrounding it with a call to <code>Lock</code> and <code>Unlock</code> as shown on the <code>protected()</code> method below.</p>
<p>It's good practice to structure the protected code within a function so that <code>defer</code> can be used to ensure that we never forget to unlock the mutex.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">protected</span><span class="hljs-params">()</span></span>{
    mux.Lock()
    <span class="hljs-keyword">defer</span> mux.Unlock()
    <span class="hljs-comment">// the rest of the function is protected</span>
    <span class="hljs-comment">// any other calls to `mux.Lock()` will block</span>
}
</code></pre>
<p>Mutexes are powerful. Like most powerful things, they can also cause many bugs if used carelessly.</p>
<h4 id="heading-maps-are-not-thread-safe">Maps are not thread-safe</h4>
<p>Maps are <strong>not</strong> safe for concurrent use! If you have multiple goroutines accessing the same map, and at least one of them is writing to the map, you must lock your maps with a mutex.</p>
<h3 id="heading-why-is-it-called-a-mutex">Why is it called a Mutex?</h3>
<p>Mutex is short for <a target="_blank" href="https://en.wikipedia.org/wiki/Mutual_exclusion">mutual exclusion</a>, and the conventional name for the data structure that provides it is "mutex", often abbreviated to "mux".</p>
<p>It's called "mutual exclusion" because a mutex <em>excludes</em> different threads (or goroutines) from accessing the same data at the same time.</p>
<h3 id="heading-why-use-mutexes">Why use mutexes?</h3>
<p>The principle problem that mutexes help us avoid is the <em>concurrent read/write problem</em>. This problem arises when one thread is writing to a variable while another thread is reading from that same variable <em>at the same time</em>.</p>
<p>When this happens, a Go program will panic because the reader could be reading bad data while it's being mutated in place.</p>
<p><img src="https://i.imgur.com/NGBnMXe.png" alt="mutex" width="370" height="122" loading="lazy"></p>
<h3 id="heading-mutex-example">Mutex example</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    m := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>{}
    <span class="hljs-keyword">go</span> writeLoop(m)
    <span class="hljs-keyword">go</span> readLoop(m)

    <span class="hljs-comment">// stop program from exiting, must be killed</span>
    block := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{})
    &lt;-block
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">writeLoop</span><span class="hljs-params">(m <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">for</span> {
        <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++ {
            m[i] = i
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readLoop</span><span class="hljs-params">(m <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">for</span> {
        <span class="hljs-keyword">for</span> k, v := <span class="hljs-keyword">range</span> m {
            fmt.Println(k, <span class="hljs-string">"-"</span>, v)
        }
    }
}
</code></pre>
<p>The example above creates a map, then starts two goroutines which each have access to the map. One goroutine continuously mutates the values stored in the map, while the other prints the values it finds in the map.</p>
<p>If we run the program on a multi-core machine, we get the following output: <code>fatal error: concurrent map iteration and map write</code></p>
<p>In Go, it isn’t safe to read from and write to a map at the same time.</p>
<h3 id="heading-mutexes-to-the-rescue">Mutexes to the rescue</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"sync"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    m := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>{}

    mux := &amp;sync.Mutex{}

    <span class="hljs-keyword">go</span> writeLoop(m, mux)
    <span class="hljs-keyword">go</span> readLoop(m, mux)

    <span class="hljs-comment">// stop program from exiting, must be killed</span>
    block := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{})
    &lt;-block
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">writeLoop</span><span class="hljs-params">(m <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>, mux *sync.Mutex)</span></span> {
    <span class="hljs-keyword">for</span> {
        <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++ {
            mux.Lock()
            m[i] = i
            mux.Unlock()
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readLoop</span><span class="hljs-params">(m <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>, mux *sync.Mutex)</span></span> {
    <span class="hljs-keyword">for</span> {
        mux.Lock()
        <span class="hljs-keyword">for</span> k, v := <span class="hljs-keyword">range</span> m {
            fmt.Println(k, <span class="hljs-string">"-"</span>, v)
        }
        mux.Unlock()
    }
}
</code></pre>
<p>In this example, we added a <code>sync.Mutex{}</code> and named it <code>mux</code>. In the write loop, the <code>Lock()</code> method is called before writing, and then the <code>Unlock()</code> is called when we're done. This Lock/Unlock sequence ensures that no other threads can <code>Lock()</code> the mutex while <em>we</em> have it locked – any other threads attempting to <code>Lock()</code> will block and wait until we <code>Unlock()</code>.</p>
<p>In the reader, we <code>Lock()</code> before iterating over the map, and likewise <code>Unlock()</code> when we're done. Now the threads share the memory safely!</p>
<h3 id="heading-rwmutex">RWMutex</h3>
<p>The standard library also exposes a <a target="_blank" href="https://golang.org/pkg/sync/#RWMutex">sync.RWMutex</a></p>
<p>In addition to these methods:</p>
<ul>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#Mutex.Lock">Lock()</a></p>
</li>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#Mutex.Unlock">Unlock()</a></p>
</li>
</ul>
<p>The <code>sync.RWMutex</code> also has these methods:</p>
<ul>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#RWMutex.RLock">RLock()</a></p>
</li>
<li><p><a target="_blank" href="https://golang.org/pkg/sync/#RWMutex.RUnlock">RUnlock()</a></p>
</li>
</ul>
<p>The <code>sync.RWMutex</code> can help with performance if we have a read-intensive process. Many goroutines can safely read from the map at the same time (multiple <code>Rlock()</code> calls can happen simultaneously). However, only one goroutine can hold a <code>Lock()</code> and all <code>RLock()</code>'s will also be excluded.</p>
<h2 id="heading-chapter-16-generics-in-go">Chapter 16 – Generics in Go</h2>
<p>As we've mentioned, Go does <em>not</em> support classes. For a long time, that meant that Go code couldn't easily be reused in many circumstances.</p>
<p>For example, imagine some code that splits a slice into 2 equal parts. The code that splits the slice doesn't really care about the <em>values</em> stored in the slice. Unfortunately in Go we would need to write it multiple times for each type, which is a very un-<a target="_blank" href="https://blog.boot.dev/clean-code/dry-code/">DRY</a> thing to do.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitIntSlice</span><span class="hljs-params">(s []<span class="hljs-keyword">int</span>)</span> <span class="hljs-params">([]<span class="hljs-keyword">int</span>, []<span class="hljs-keyword">int</span>)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitStringSlice</span><span class="hljs-params">(s []<span class="hljs-keyword">string</span>)</span> <span class="hljs-params">([]<span class="hljs-keyword">string</span>, []<span class="hljs-keyword">string</span>)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<p>In Go 1.20 however, support for <a target="_blank" href="https://blog.boot.dev/golang/how-to-use-golangs-generics/">generics</a> was released, effectively solving this problem!</p>
<h4 id="heading-type-parameters">Type Parameters</h4>
<p>Put simply, generics allow us to use variables to refer to specific types. This is an amazing feature because it allows us to write abstract functions that drastically reduce code duplication.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitAnySlice</span>[<span class="hljs-title">T</span> <span class="hljs-title">any</span>]<span class="hljs-params">(s []T)</span> <span class="hljs-params">([]T, []T)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<p>In the example above, <code>T</code> is the name of the type parameter for the <code>splitAnySlice</code> function, and we've said that it must match the <code>any</code> constraint, which means it can be anything. This makes sense because the body of the function <em>doesn't care</em> about the types of things stored in the slice.</p>
<pre><code class="lang-go">firstInts, secondInts := splitAnySlice([]<span class="hljs-keyword">int</span>{<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>})
fmt.Println(firstInts, secondInts)
</code></pre>
<h3 id="heading-why-generics">Why Generics?</h3>
<h4 id="heading-generics-reduce-repetitive-code">Generics reduce repetitive code</h4>
<p>You should care about generics because they mean you don’t have to write as much code! It can be frustrating to write the same logic over and over again, just because you have some underlying data types that are slightly different.</p>
<h4 id="heading-generics-are-used-more-often-in-libraries-and-packages">Generics are used more often in libraries and packages</h4>
<p>Generics give Go developers an elegant way to write amazing utility packages. While you will see and use generics in application code, I think it will much more common to see generics used in libraries and packages. Libraries and packages contain importable code intended to be used in <em>many</em> applications, so it makes sense to write them in a more abstract way. Generics are often the way to do just that!</p>
<h4 id="heading-why-did-it-take-so-long-to-get-generics">Why did it take so long to get generics?</h4>
<p>Go places an emphasis on simplicity. In other words, Go has purposefully left out many features to provide its best feature: being simple and easy to work with.</p>
<p>According to <a target="_blank" href="https://go.dev/blog/survey2020-results">historical data from Go surveys</a>, Go’s lack of generics has always been listed as one of the top three biggest issues with the language. At a certain point, the drawbacks associated with the lack of a feature like generics justify adding complexity to the language.</p>
<h3 id="heading-constraints-in-go">Constraints in Go</h3>
<p>Sometimes you need the logic in your generic function to know <em>something</em> about the types it operates on. The example we used in the first exercise didn't need to know <em>anything</em> about the types in the slice, so we used the built-in <code>any</code> constraint:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitAnySlice</span>[<span class="hljs-title">T</span> <span class="hljs-title">any</span>]<span class="hljs-params">(s []T)</span> <span class="hljs-params">([]T, []T)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<p>Constraints are just interfaces that allow us to write generics that only operate within the constraint of a given interface type. In the example above, the <code>any</code> constraint is the same as the empty interface because it means the type in question can be <em>anything</em>.</p>
<h4 id="heading-how-to-create-a-custom-constraint">How to create a custom constraint</h4>
<p>Let's take a look at the example of a <code>concat</code> function. It takes a slice of values and concatenates the values into a string. This should work with <em>any type that can represent itself as a string</em>, even if it's not a string under the hood.</p>
<p>For example, a <code>user</code> struct can have a <code>.String()</code> that returns a string with the user's name and age.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> stringer <span class="hljs-keyword">interface</span> {
    String() <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">concat</span>[<span class="hljs-title">T</span> <span class="hljs-title">stringer</span>]<span class="hljs-params">(vals []T)</span> <span class="hljs-title">string</span></span> {
    result := <span class="hljs-string">""</span>
    <span class="hljs-keyword">for</span> _, val := <span class="hljs-keyword">range</span> vals {
        <span class="hljs-comment">// this is where the .String() method</span>
        <span class="hljs-comment">// is used. That's why we need a more specific</span>
        <span class="hljs-comment">// constraint instead of the any constraint</span>
        result += val.String()
    }
    <span class="hljs-keyword">return</span> result
}
</code></pre>
<h3 id="heading-interface-type-lists">Interface type lists</h3>
<p>When generics were released, a new way of writing interfaces was also released at the same time!</p>
<p>We can now simply list a bunch of types to get a new interface/constraint.</p>
<pre><code class="lang-go"><span class="hljs-comment">// Ordered is a type constraint that matches any ordered type.</span>
<span class="hljs-comment">// An ordered type is one that supports the &lt;, &lt;=, &gt;, and &gt;= operators.</span>
<span class="hljs-keyword">type</span> Ordered <span class="hljs-keyword">interface</span> {
    ~<span class="hljs-keyword">int</span> | ~<span class="hljs-keyword">int8</span> | ~<span class="hljs-keyword">int16</span> | ~<span class="hljs-keyword">int32</span> | ~<span class="hljs-keyword">int64</span> |
        ~<span class="hljs-keyword">uint</span> | ~<span class="hljs-keyword">uint8</span> | ~<span class="hljs-keyword">uint16</span> | ~<span class="hljs-keyword">uint32</span> | ~<span class="hljs-keyword">uint64</span> | ~<span class="hljs-keyword">uintptr</span> |
        ~<span class="hljs-keyword">float32</span> | ~<span class="hljs-keyword">float64</span> |
        ~<span class="hljs-keyword">string</span>
}
</code></pre>
<h3 id="heading-how-to-name-generic-types">How to Name Generic Types</h3>
<p>Let's look at this simple example again:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitAnySlice</span>[<span class="hljs-title">T</span> <span class="hljs-title">any</span>]<span class="hljs-params">(s []T)</span> <span class="hljs-params">([]T, []T)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<p>Remember, <code>T</code> is just a variable name, We could have named the type parameter <em>anything</em>. <code>T</code> happens to be a fairly common convention for a type variable, similar to how <code>i</code> is a convention for index variables in loops.</p>
<p>This is just as valid:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">splitAnySlice</span>[<span class="hljs-title">MyAnyType</span> <span class="hljs-title">any</span>]<span class="hljs-params">(s []MyAnyType)</span> <span class="hljs-params">([]MyAnyType, []MyAnyType)</span></span> {
    mid := <span class="hljs-built_in">len</span>(s)/<span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> s[:mid], s[mid:]
}
</code></pre>
<h2 id="heading-congratulations-on-making-it-to-the-end"><strong>Congratulations on making it to the end!</strong></h2>
<p>If you're interested in doing the interactive coding assignments and quizzes for this course you can check out the <a target="_blank" href="https://boot.dev/learn/learn-golang">Learn Go course</a> over on <a target="_blank" href="https://boot.dev/">Boot.dev</a>.</p>
<p>This course is a part of my <a target="_blank" href="https://boot.dev/tracks/backend">full back-end developer career path</a>, made up of other courses and projects if you're interested in checking those out.</p>
<p>If you want to see the other content I'm creating related to web development, check out some of my links below:</p>
<ul>
<li><p><a target="_blank" href="https://backendbanter.fm/">Lane's Podcast: Backend Banter</a></p>
</li>
<li><p><a target="_blank" href="https://twitter.com/wagslane">Lane on Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://youtube.com/@bootdotdev">Lane on YouTube</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTTP Networking in JavaScript – Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ HTTP is the backbone of the modern internet. In this text-based course, you'll learn how the HTTP protocol works and how it's used in real-world web development. All the code samples for this course are in JavaScript, but the networking concepts you'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/http-full-course/</link>
                <guid isPermaLink="false">66b9e9ec39e4436f19005afa</guid>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Tue, 14 Feb 2023 00:42:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738338854008/9272a213-f1ed-40d0-8d33-f57a11b3756c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTTP is the backbone of the modern internet. In this text-based course, you'll learn how the HTTP protocol works and how it's used in real-world web development.</p>
<p>All the code samples for this course are in JavaScript, but the networking concepts you'll learn here apply generally to all coding languages. <em>If you're not familiar with JavaScript yet, you can check out</em> <a target="_blank" href="https://boot.dev/learn/learn-javascript"><em>my JS course here</em></a><em>.</em></p>
<p>I've included all the learning material you'll need here in this article, but if you would like a more hands-on experience, you can take the <a target="_blank" href="https://boot.dev/learn/learn-http">interactive version of this course with coding challenges on Boot.dev here.</a></p>
<p>I've also published a free video version of this course on the freeCodeCamp YouTube channel:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2JYT5f2isg4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>If you like this video, you can check out my other tutorials on my <a target="_blank" href="https://youtube.com/@bootdotdev">Boot.dev YouTube channel here</a>.</p>
<p>All that said, let's jump into learning about HTTP!</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-why-http">Why HTTP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#What-is-dns">What is DNS?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-uris">What Are URIs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-4-async-await">Async/Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling">Error Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-http-headers">HTTP Headers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-json">What is JSON?</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-8-http-methods">HTTP Methods</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-url-paths-and-parameters">URL Paths and Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-https">What is HTTPs?</a></p>
</li>
</ol>
<h2 id="heading-why-http">Why HTTP?</h2>
<h3 id="heading-communicating-on-the-web">Communicating on the web</h3>
<p>Instagram would be pretty terrible if you had to manually copy your photos to your friend's phone when you wanted to share them. Modern applications need to be able to communicate information <em>between devices</em> over the internet.</p>
<ul>
<li><p>Gmail doesn't just store your emails in variables on your computer, it stores them on computers in their data centers.</p>
</li>
<li><p>You don't lose your Slack messages if you drop your computer in a lake – those messages exist on Slack's <a target="_blank" href="https://en.wikipedia.org/wiki/Web_server">servers</a>.</p>
</li>
</ul>
<h3 id="heading-how-does-web-communication-work">How does web communication work?</h3>
<p>When two computers communicate with each other, they need to use the same rules. An English speaker can't communicate verbally with a Japanese speaker, and similarly, two computers need to speak the same language to communicate.</p>
<p>This "language" that computers use is called a <a target="_blank" href="https://en.wikipedia.org/wiki/Communication_protocol">protocol</a>. The most popular protocol for web communication is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview">HTTP</a>, which stands for Hypertext Transfer Protocol.</p>
<h3 id="heading-interacting-with-a-server">Interacting with a server</h3>
<p>In this course, a lot of the code samples will interact with the <a target="_blank" href="https://pokeapi.co/">PokeAPI</a>. It serves data about Pokémon.</p>
<p>Here's some code that retrieves a list of Pokémon from the PokeAPI:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pokemonResp = <span class="hljs-keyword">await</span> getItemData()

logPokemons(pokemonResp.results)

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getItemData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    }
  })
  <span class="hljs-keyword">return</span> response.json()
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logPokemons</span>(<span class="hljs-params">pokemons</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pokemon <span class="hljs-keyword">of</span> pokemons) {
    <span class="hljs-built_in">console</span>.log(pokemon.name)
  } 
}
</code></pre>
<p>When you run this code, you'll notice that none of the data that is logged to the console was generated within our code! That's because the data we retrieved is being sent over the internet from our servers via HTTP. Don't worry, we'll explain more about that later.</p>
<h3 id="heading-http-requests-and-responses">HTTP Requests and Responses</h3>
<p>At the heart of HTTP is a simple request-response system. The "requesting" computer, also known as the "<a target="_blank" href="https://en.wikipedia.org/wiki/Client_\(computing\)">client</a>", asks another computer for some information. That computer, the "<a target="_blank" href="https://en.wikipedia.org/wiki/Server_\(computing\)">server</a>" sends back a response with the information that was requested.</p>
<p><img src="https://i.imgur.com/ReFw6nN.png" alt="Image" width="925" height="297" loading="lazy"></p>
<p>We'll talk about the specifics of how the "requests" and "responses" are formatted later. For now, just think of it as a simple question-and-answer system.</p>
<ul>
<li><p>Request: "What are the items in the Fantasy Quest game?"</p>
</li>
<li><p>Response: A list of the items in the Fantasy Quest game</p>
</li>
</ul>
<h3 id="heading-http-powers-websites">HTTP powers websites</h3>
<p>As we discussed, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview">HTTP</a>, or Hypertext Transfer Protocol, is a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Protocol">protocol</a> designed to transfer information between computers.</p>
<p>There are other protocols for communicating over the internet, but HTTP is the most popular and is <em>particularly great for websites and web applications</em>.</p>
<p>Each time you visit a website, your browser is making an HTTP request to that website's server. The server responds with all the text, images, and styling information that your browser needs to render its pretty website.</p>
<p><img src="https://i.imgur.com/EflKJzq.jpg" alt="Image" width="1080" height="1080" loading="lazy"></p>
<h3 id="heading-http-urls">HTTP URLs</h3>
<p>A URL, or <a target="_blank" href="https://www.freecodecamp.org/news/url-definition/">Uniform Resource Locator</a>, is essentially the address of another computer, or "server" on the internet. Part of the URL specifies how to reach the server, and part of it tells the server what information we want - but more on that later.</p>
<p>For now, it's important to understand that a URL represents a piece of information on another computer that we want access to. We can get access to it by making a <em>request</em>, and reading the <em>response</em> that the server replies with.</p>
<h3 id="heading-how-to-use-urls-in-http">How to Use URLs in HTTP</h3>
<p>The <code>http://</code> at the beginning of a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL">website URL</a> specifies that the <code>http</code> protocol will be used for communication.</p>
<p><img src="https://i.imgur.com/6jiaXBn.png" alt="Image" width="368" height="137" loading="lazy"></p>
<p>Other communication protocols use URLs as well, (hence "Uniform Resource Locator"). That's why we need to be specific when we're making HTTP requests by prefixing the URL with <code>http://</code></p>
<h3 id="heading-requests-and-responses-review">Requests and Responses Review</h3>
<ul>
<li><p>A "client" is a computer making an HTTP request</p>
</li>
<li><p>A "server" is a computer responding to an HTTP request</p>
</li>
<li><p>A computer can be a client, a server, both, or neither. "Client" and "server" are just words we use to describe what computers are doing within a communication system.</p>
</li>
<li><p>Clients send requests and receive responses</p>
</li>
<li><p>Servers receive requests and send responses</p>
</li>
</ul>
<h2 id="heading-javascripts-fetch-api">JavaScript's Fetch API</h2>
<p>In this course, we'll be using JavaScript's built-in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch API</a> to make HTTP requests.</p>
<p>The <code>fetch()</code> function is made available to us by the JavaScript language running in the browser. All we have to do is provide it with the parameters it requires.</p>
<h3 id="heading-how-to-use-fetch"><strong>How to Use Fetch</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, settings)
<span class="hljs-keyword">const</span> responseData = <span class="hljs-keyword">await</span> response.json()
</code></pre>
<p>We'll go in-depth on the various things happening in this standard <code>fetch</code> call later, but let's cover some basics for now.</p>
<ul>
<li><p><code>response</code> is the data that comes back from the server</p>
</li>
<li><p><code>url</code> is the URL we are making a request to</p>
</li>
<li><p><code>settings</code> is an object containing some request-specific settings</p>
</li>
<li><p>The <code>await</code> keyword tells JavaScript to wait until the request comes back from the server before continuing</p>
</li>
<li><p><code>response.json()</code> converts the response data from the server into a JavaScript object</p>
</li>
</ul>
<p>See if you can spot the issue with this code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pokemonResp = getItemData()

logPokemons(pokemonResp.results)

<span class="hljs-comment">// the bug is above this line</span>

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getItemData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    }
  })
  <span class="hljs-keyword">return</span> response.json()
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logPokemons</span>(<span class="hljs-params">pokemons</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pokemon <span class="hljs-keyword">of</span> pokemons) {
    <span class="hljs-built_in">console</span>.log(pokemon.name)
  } 
}
</code></pre>
<p>Hint: We're not waiting for the data to be sent back across the network.</p>
<h3 id="heading-web-clients">Web Clients</h3>
<p>A web client is a device making requests to a web server. A client can be any type of device but is often something users physically interact with. For example:</p>
<ul>
<li><p>A desktop computer</p>
</li>
<li><p>A mobile phone</p>
</li>
<li><p>A tablet</p>
</li>
</ul>
<p>In a website or web application, we call the user's device the "front-end".<br>A front-end client makes requests to a back-end server.</p>
<p><img src="https://i.imgur.com/zldXGet.jpg" alt="Image" width="1920" height="1080" loading="lazy"></p>
<h3 id="heading-web-servers">Web Servers</h3>
<p>Up to this point, most of the data you have worked with in your code has simply been generated and stored locally in variables.</p>
<p>While you'll always use variables to store and manipulate data while your program is running, most websites and apps use a web server to store, sort, and serve that data so that it sticks around for longer than a single session, and can be accessed by multiple devices.</p>
<h3 id="heading-listening-and-serving-data"><strong>Listening and serving data</strong></h3>
<p>Similar to how a server at a restaurant brings your food to the table, a <a target="_blank" href="https://en.wikipedia.org/wiki/Web_server">web server</a>) serves web resources, such as web pages, images, and other data. The server is turned on and "listening" for inbound requests constantly so that the second it receives a new request, it can send an appropriate response.</p>
<h3 id="heading-the-server-is-the-back-end">The server is the back-end</h3>
<p>While the "front-end" of a website or web application is the device the user interacts with, the "back-end" is the server that keeps all the data housed in a central location. If you're still confused, <a target="_blank" href="https://blog.boot.dev/backend/frontend-vs-backend-meaning/">check out this article comparing front-end and back-end development</a>.</p>
<h3 id="heading-a-server-is-just-a-computer">A server is just a computer</h3>
<p>"Server" is just the name we give to a computer that is taking on the role of serving data across a network connection.</p>
<p>A good server is turned on and available 24 hours a day, 7 days a week. While your laptop <em>can</em> be used as a server, it makes more sense to use a computer in a data center that's designed to be up and running constantly.</p>
<h2 id="heading-what-is-dns">What is DNS?</h2>
<h3 id="heading-web-addresses">Web Addresses</h3>
<p>In the real world, we use addresses to help us find where a friend lives, where a business is located, or where a party is being thrown.</p>
<p>In computing, web clients find other computers over the internet using <a target="_blank" href="https://en.wikipedia.org/wiki/Internet_Protocol">Internet Protocol or IP</a> addresses.</p>
<p>An IP address is a numerical label that serves two main functions:</p>
<ol>
<li><p>Location Addressing</p>
</li>
<li><p>Network Identification</p>
</li>
</ol>
<h3 id="heading-domain-names-and-ip-addresses">Domain names and IP Addresses</h3>
<p>Each device connected to the internet has a unique IP address. When we browse the internet, the domains we navigate to are all associated with a particular IP address.</p>
<p>For example, this Wikipedia URL points to a page about miniature pigs: <code>https://en.wikipedia.org/wiki/Miniature_pig</code><br>The <a target="_blank" href="https://en.wikipedia.org/wiki/Domain_Name_System">domain</a> portion of the URL is <code>en.wikipedia.org</code>. <code>en.wikipedia.org</code> converts to a specific IP address, and that IP address tells your computer exactly where to communicate with that Wikipedia page.</p>
<p>Cloudflare is a tech company that provides a cool public HTTP server that we can use to look up the IP address of any domain. Take a look at this sample code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchIPAddress</span>(<span class="hljs-params">domain</span>) </span>{
  <span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://cloudflare-dns.com/dns-query?name=<span class="hljs-subst">${domain}</span>&amp;type=A`</span>, {
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'accept'</span>: <span class="hljs-string">'application/dns-json'</span>
    }
  })
  <span class="hljs-keyword">const</span> respObject = <span class="hljs-keyword">await</span> resp.json()
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> record <span class="hljs-keyword">of</span> respObject.Answer) {
    <span class="hljs-keyword">return</span> record.data
  }
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}

<span class="hljs-keyword">const</span> domain = <span class="hljs-string">'api.boot.dev'</span>
<span class="hljs-keyword">const</span> ipAddress = <span class="hljs-keyword">await</span> fetchIPAddress(domain)
<span class="hljs-keyword">if</span> (!ipAddress) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'something went wrong in fetchIPAddress'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`found IP address for domain <span class="hljs-subst">${domain}</span>: <span class="hljs-subst">${ipAddress}</span>`</span>)
}
</code></pre>
<p>To recap, a "domain name" is part of a URL. It's the part that tells the computer <em>where the server is located on the internet</em> by being converted into a numerical IP address.</p>
<p>We'll cover exactly how an IP address is used by your computer to find a path to the server in a later networking course. For now, it's just important to understand that an IP address is what your computer is using at a lower level to communicate on a network.</p>
<p>Deploying a real website to the internet is actually quite simple. It involves only a couple of steps:</p>
<ol>
<li><p>Create a server that hosts your website files and connect it to the internet</p>
</li>
<li><p>Acquire a domain name</p>
</li>
<li><p>Connect the domain name to the IP address of your server</p>
</li>
<li><p>Your server is accessible via the internet!</p>
</li>
</ol>
<p><img src="https://i.imgur.com/vjjPt2a.png" alt="Image" width="310" height="163" loading="lazy"></p>
<p>As we discussed, the "domain name" or "hostname" is part of a URL. We'll get to the other parts of a URL later.</p>
<p>For example, the URL <code>https://example.com/path</code> has a hostname of <code>example.com</code>. The <code>https://</code> and <code>/path</code> portions are not part of the <code>domain name -&gt; IP address</code> mapping that we've been learning about.</p>
<h3 id="heading-using-the-url-api-in-javascript">Using the URL API in JavaScript</h3>
<p>The <code>URL</code> API is built into JavaScript. You can create a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL">new URL object</a> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> urlObj = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">'https://example.com/example-path'</span>)
</code></pre>
<p>And then you can <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL">extract just the hostname</a>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> urlObj.hostname
</code></pre>
<h3 id="heading-dns-review">DNS Review</h3>
<p>So we've talked about domain names and what their purpose is, but we haven't talked about the system that's used to do that conversion.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-dns/">DNS</a>, or the "Domain Name System", is the phonebook of the internet. Humans connect to websites through <a target="_blank" href="https://en.wikipedia.org/wiki/Domain_name">domain names</a>, like <a target="_blank" href="https://boot.dev">Boot.dev</a>.</p>
<p>DNS "resolves" these domain names to find the associated <a target="_blank" href="https://en.wikipedia.org/wiki/Internet_Protocol">IP addresses</a> so that web clients can load the resources for the specific address.</p>
<p><img src="https://i.imgur.com/yvfSbVL.png" alt="Image" width="1024" height="512" loading="lazy"></p>
<h3 id="heading-how-does-dns-work">How does DNS Work?</h3>
<p>We'll go into more detail on DNS in a future course, but to give you a simplified idea of how it works, let's introduce ICANN. <a target="_blank" href="https://www.icann.org/">ICANN</a> is a not-for-profit organization that manages DNS for the entire internet.</p>
<p>Whenever your computer attempts to resolve a domain name, it contacts one of ICANN's "<a target="_blank" href="https://en.wikipedia.org/wiki/Root_name_server">root nameservers</a>" whose address is included in your computer's networking configuration.</p>
<p>From there, that nameserver can gather the domain records for a specific domain name from their distributed DNS database.</p>
<p>If you think of DNS as a phonebook, ICANN is the publisher that keeps the phonebook in print and available.</p>
<h3 id="heading-subdomains">Subdomains</h3>
<p>We learned about how a domain name resolves to an IP address, which is just a computer on a network - often the internet.</p>
<p>A subdomain prefixes a domain name, allowing a domain to route network traffic to many different servers and resources.</p>
<p>For example, the <a target="_blank" href="https://boot.dev">Boot.dev</a> website is hosted on a different computer than our blog. Our blog, found at <a target="_blank" href="https://blog.boot.dev">blog.boot.dev</a> is hosted on our "blog" subdomain.</p>
<h2 id="heading-what-are-uris">What are URIs?</h2>
<p>We briefly touched on URLs earlier, but now let's dive a little deeper into the subject.</p>
<p>A <a target="_blank" href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier">URI</a>, or Uniform Resource <em>Identifier</em>, is a unique character sequence that identifies a resource that is (almost always) accessed via the internet.</p>
<p>Just like JavaScript has syntax rules, so do URIs. These rules help ensure uniformity so that any program can interpret the meaning of the URI in the same way.</p>
<p>URIs come in two main types:</p>
<ul>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/URL">URLs</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Uniform_Resource_Name">URNs</a></p>
</li>
</ul>
<p>We will focus specifically on URLs in this course, but it's important to know that URLs are only one kind of URI.</p>
<p><img src="https://i.imgur.com/VzqzckC.png" alt="Image" width="500" height="394" loading="lazy"></p>
<p>URLs have quite a few sections, some of which are required, others not.<br>Let's use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL">URL API</a> to parse a URL and print all the different parts. We'll learn more about each part later, for now, let's just split and print a URL.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printURLParts</span>(<span class="hljs-params">urlString</span>) </span>{
  <span class="hljs-keyword">const</span> urlObj = <span class="hljs-keyword">new</span> URL(urlString)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`protocol: <span class="hljs-subst">${urlObj.protocol}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`username: <span class="hljs-subst">${urlObj.username}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`password: <span class="hljs-subst">${urlObj.password}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`hostname: <span class="hljs-subst">${urlObj.hostname}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`port: <span class="hljs-subst">${urlObj.port}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`pathname: <span class="hljs-subst">${urlObj.pathname}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`search: <span class="hljs-subst">${urlObj.search}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`hash: <span class="hljs-subst">${urlObj.hash}</span>`</span>)
}

<span class="hljs-keyword">const</span> fantasyQuestURL = <span class="hljs-string">'http://dragonslayer:pwn3d@fantasyquest.com:8080/maps?sort=rank#id'</span>
printURLParts(fantasyQuestURL)
</code></pre>
<h3 id="heading-further-dissecting-a-url">Further dissecting a URL</h3>
<p>There are 8 main parts to a URL, though not all the sections are always present. Each piece plays a specific role in helping clients locate the specified resource.<br>The 8 sections are:</p>
<p><img src="https://i.imgur.com/iI3sUVh.png" alt="Image" width="1280" height="720" loading="lazy"></p>
<ul>
<li><p>The protocol is required</p>
</li>
<li><p>Usernames and passwords are optional</p>
</li>
<li><p>A domain is required</p>
</li>
<li><p>The default port for a given protocol is used if one is not provided</p>
</li>
<li><p>The default ( <code>/</code> ) path is used if one isn't provided</p>
</li>
<li><p>A query is optional</p>
</li>
<li><p>A fragment is optional</p>
</li>
</ul>
<h3 id="heading-dont-get-too-hung-up-on-memorizing-this-stuff">Don't get too hung up on memorizing this stuff</h3>
<p>Because names for the different sections are often used interchangeably, and because not all the parts of the URL are always present, it can be hard to keep things straight.</p>
<p>Don't worry about memorizing this stuff! Try to just get familiar with these URL concepts from a high level. Like any good developer, you can just look it up again the next time you need to know more.</p>
<h3 id="heading-the-protocol">The Protocol</h3>
<p>The "protocol", also referred to as the "scheme", is the first component of a URL. Its purpose is to define the rules by which the data being communicated is displayed, encoded, or formatted.</p>
<p>Some examples of different URL protocols:</p>
<ul>
<li><p>http</p>
</li>
<li><p>ftp</p>
</li>
<li><p>mailto</p>
</li>
<li><p>https</p>
</li>
</ul>
<p>For example:</p>
<ul>
<li><p><code>http://example.com</code></p>
</li>
<li><p><code>mailto:noreply@fantasyquest.app</code></p>
</li>
</ul>
<h3 id="heading-not-all-schemes-require-a">Not all schemes require a "//"</h3>
<p>The "http" in a URL is always followed by <code>://</code>. All URLs have the colon, but the <code>//</code> part is only included for schemes that have an <a target="_blank" href="https://www.rfc-editor.org/rfc/rfc3986#section-3.2">authority component</a>.</p>
<p>As you can see above, the <code>mailto</code> scheme doesn't use an authority component, so it doesn't need the slashes.</p>
<h3 id="heading-url-ports">URL Ports</h3>
<p>The port in a URL is a virtual point where network connections are made. Ports are managed by a computer's operating system and are numbered from <code>0</code> to <code>65,535</code>.</p>
<p>Whenever you connect to another computer over a network, you're connecting to a specific port on that computer, which is being listened to by a specific piece of software on that computer. A port can only be used by one program at a time, which is why there are so many possible ports.</p>
<p>The port component of a URL is often not visible when browsing normal sites on the internet, because 99% of the time you're using the default ports for the HTTP and HTTPS schemes: <code>80</code> and <code>443</code>, respectively.</p>
<p>Whenever you aren't using a default port, you need to specify it in the URL. For example, port <code>8080</code> is often used by web developers when they're running their server in "test mode" so that they don't use the "production" port "80".</p>
<p><img src="https://i.imgur.com/h3kBsRC.png" alt="Image" width="625" height="129" loading="lazy"></p>
<h3 id="heading-url-paths">URL Paths</h3>
<p>In the early days of the internet, a URL's path often was a reflection of the file path on the server to the resource the client was requesting.</p>
<p>For example, if the website <code>https://exampleblog.com</code> had a web server running within its <code>/home</code> directory, then a request to the <code>https://exampleblog.com/site/index.html</code> URL might expect the <code>index.html</code> file from within the <code>/home/site</code> directory to be returned.</p>
<p>Websites used to be very simple. They were just a collection of text documents stored on a server. A simple piece of server software could handle incoming HTTP requests and respond with the documents according to the path component of the URLs.</p>
<h3 id="heading-these-days-its-not-always-about-the-filesystem">These days, it's not always about the filesystem</h3>
<p>On many modern web servers, a URL's path isn't a reflection of the server's filesystem hierarchy. Paths in URLs are essentially just another type of parameter that can be passed to the server when making a request.</p>
<p>Conventionally, two different URL paths should denote different resources. For example, different pages on a website, or maybe different data types from a game server.</p>
<h3 id="heading-query-parameters">Query parameters</h3>
<p>Query parameters in a URL are <em>not</em> always present. In the context of websites, query parameters are often used for marketing analytics or for changing a variable on the web page. With website URLs, query parameters <em>rarely</em> change <em>which</em> page you're viewing, though they often will change the page's <em>contents</em>.</p>
<p>That said, query parameters can be used for anything the server chooses to use them for, just like the URL's path.</p>
<h3 id="heading-how-google-uses-query-parameters">How Google uses query parameters</h3>
<ol>
<li><p>Open a new tab and go to <a target="_blank" href="https://google.com">google.com</a></p>
</li>
<li><p>Search for "hello world"</p>
</li>
<li><p>Take a look at your current URL. It should start with <code>https://www.google.com/search?q=hello+world</code></p>
</li>
<li><p>Change the URL to say <code>https://www.google.com/search?q=hello+universe</code></p>
</li>
<li><p>Press "enter"</p>
</li>
</ol>
<p>You should see new search results for the query "hello universe". Google chose to use query parameters to represent the value of your search query. It makes sense - each search result page is <em>essentially</em> the same page as far as structure and formatting are concerned - it's just showing you different results based on the search query.</p>
<h2 id="heading-asyncawait">Async/Await</h2>
<p>You're probably already familiar with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Synchronous">synchronous</a> code, which means code that <em>runs in sequence</em>. Each line of code executes in order, one after the next.</p>
<p><img src="https://i.imgur.com/03FFGu0.png" alt="Image" width="587" height="335" loading="lazy"></p>
<p>Example of synchronous code:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print first"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print second"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print third"</span>);
</code></pre>
<p>Asynchronous or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous">async</a> code runs in <em>parallel</em>. That means code further down runs <em>at the same time that</em> a previous line of code is still running. A good way to visualize this is with the JavaScript function <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeout()</a>.</p>
<p><code>setTimeout</code> accepts a function and a number of milliseconds as inputs. It waits until the number of milliseconds has elapsed, and then it executes the function it was given.</p>
<p>Example of asynchronous code:</p>
<pre><code class="lang-js">jsconsole.log(<span class="hljs-string">"I print first"</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print third because I'm waiting 100 milliseconds"</span>), <span class="hljs-number">100</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print second"</span>);
</code></pre>
<p>Try altering the waiting times in the async code below to get the messages to print in the proper order:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> craftingCompleteWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> combiningMaterialsWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> smeltingIronBarsWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> shapingIronWait = <span class="hljs-number">0</span>

<span class="hljs-comment">// Don't touch below this line</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Iron Longsword Complete!'</span>), craftingCompleteWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Combining Materials...'</span>), combiningMaterialsWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Smelting Iron Bars...'</span>), smeltingIronBarsWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Shaping Iron...'</span>), shapingIronWait)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Firing up the forge...'</span>)

<span class="hljs-keyword">await</span> sleep(<span class="hljs-number">2500</span>)
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">ms</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, ms))
}
</code></pre>
<p>Expected order:</p>
<ol>
<li><p>Firing up the forge..</p>
</li>
<li><p>Smelting Iron Bars...</p>
</li>
<li><p>Combining Materials...</p>
</li>
<li><p>Shaping Iron...</p>
</li>
<li><p>Iron Longsword Complete!</p>
</li>
</ol>
<h3 id="heading-why-do-we-want-async-code">Why do we want async code?</h3>
<p>We try to keep most of our code synchronous because it's easier to understand, and therefore often has fewer bugs. But sometimes we <em>need</em> our code to be asynchronous.</p>
<p>For example, whenever you update your user settings on a website, your browser will need to communicate those new settings to the server. The time it takes your HTTP request to physically travel across all the wiring of the internet is usually around 100 milliseconds. It would be a very poor experience if your webpage were to freeze while waiting for the network request to finish. You wouldn't even be able to move the mouse while waiting!</p>
<p>By making network requests <em>asynchronously</em>, we let the webpage execute other code while waiting for the HTTP response to come back. This keeps the user experience snappy and user-friendly.</p>
<p>As a general rule, we should only use async code when we need to for performance reasons. Synchronous code is simpler.</p>
<p><img src="https://i.imgur.com/03FFGu0.png" alt="Image" width="587" height="335" loading="lazy"></p>
<h3 id="heading-promises-in-javascript">Promises in JavaScript</h3>
<p>A Promise in JavaScript is very similar to making a promise in the real world. When we make a promise, we are making a commitment to something.</p>
<p>For example, <em>I promise to explain JavaScript promises to you</em>. My promise to you has 2 potential outcomes: it is either fulfilled, meaning I eventually explained promises to you, or it is rejected, meaning I failed to keep my promise and didn't explain promises.</p>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise Object</a> represents the eventual fulfillment or rejection of our promise and holds the resulting values. In the meantime, while we're waiting for the promise to be fulfilled, our code continues executing.</p>
<p>Promises are the most popular modern way to write asynchronous code in JavaScript.</p>
<h3 id="heading-how-to-declare-a-promise">How to Declare a Promise</h3>
<p>Here is an example of a promise that will resolve and return the string "resolved!" or reject and return the string "rejected!" after 1 second.</p>
<pre><code class="lang-plaintext">const promise = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; {
    if (getRandomBool()) {
      resolve("resolved!")
    } else {
      reject("rejected!")
    }
  }, 1000)
})

function getRandomBool(){
  return Math.random() &lt; .5
}
</code></pre>
<h3 id="heading-how-to-use-a-promise">How to Use a Promise</h3>
<p>Now that we've created a promise, how do we use it?</p>
<p>The <code>Promise</code> object has <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">.then</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch">.catch</a> that make it easy to work with. Think of <code>.then</code> as the <em>expected</em> follow-up to a promise, and <code>.catch</code> as the "something went wrong" follow-up.</p>
<p>If a promise <em>resolves</em>, its <code>.then</code> function will execute. If the promise rejects, its <code>.catch</code> method will execute.</p>
<p>Here's an example of using <code>.then</code> and <code>.catch</code> with the promise we made above:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The promise finally <span class="hljs-subst">${message}</span>`</span>)
}).catch(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The promise finally <span class="hljs-subst">${message}</span>`</span>)
})

<span class="hljs-comment">// prints:</span>
<span class="hljs-comment">// The promise finally resolved!</span>
<span class="hljs-comment">// or</span>
<span class="hljs-comment">// the promise finally rejected!</span>
</code></pre>
<h3 id="heading-why-are-promises-useful">Why are Promises useful?</h3>
<p>Promises are the cleanest (but not the only) way to handle the common scenario where we need to make requests to a server, which is typically done via an HTTP request. In fact, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch()</a> function we were using earlier in the course returns a promise!</p>
<h3 id="heading-io-or-inputoutput">I/O, or "input/output"</h3>
<p>Almost every time you use a promise in JavaScript it will be to handle some form of I/O. I/O, or input/output, refers to when our code needs to interact with systems outside of the (relatively) simple world of local variables and functions.<br>Common examples of I/O include:</p>
<ul>
<li><p>HTTP requests</p>
</li>
<li><p>Reading files from the hard drive</p>
</li>
<li><p>Interacting with a Bluetooth device</p>
</li>
</ul>
<p>Promises help us perform I/O without forcing our entire program to freeze up while we wait for a response.</p>
<h3 id="heading-promises-and-the-await-keyword">Promises and the "await" keyword</h3>
<p>We have used the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a> keyword a few times in this course, so it's time we finally understand what's going on under the hood.</p>
<p>The <code>await</code> keyword is used to <em>wait</em> for a promise to resolve. Once it has been resolved, the <code>await</code> expression returns the value of the resolved <code>Promise</code>.</p>
<h3 id="heading-example-with-then-callback">Example with .then callback</h3>
<pre><code class="lang-js">promise.then(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Resolved with <span class="hljs-subst">${message}</span>`</span>)
}).
</code></pre>
<h3 id="heading-example-of-awaiting-a-promise">Example of awaiting a promise</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> message = <span class="hljs-keyword">await</span> promise
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Resolved with <span class="hljs-subst">${message}</span>`</span>)
</code></pre>
<h3 id="heading-the-async-keyword">The async keyword</h3>
<p>While the <code>await</code> keyword can be used in place of <code>.then()</code> to <em>resolve</em> a promise, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a> keyword can be used in place of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">new promise()</a> to <em>create</em> a new promise.</p>
<p>When a function is prefixed with the <code>async</code> keyword, it will <em>automatically</em> return a promise. That promise resolves with the value that your code returns from the function. You can think of <code>async</code> as "wrapping" your function within a promise.</p>
<p>These are equivalent:</p>
<h3 id="heading-new-promise">New Promise()</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromiseForUserData</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    fetchDataFromServerAsync().then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
      resolve(user)
    })
  })
}

<span class="hljs-keyword">const</span> promise = getPromiseForUserData()
</code></pre>
<h3 id="heading-async">Async</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromiseForUserData</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchDataFromServer()
  <span class="hljs-keyword">return</span> user
}

<span class="hljs-keyword">const</span> promise = getPromiseForUserData()
</code></pre>
<h3 id="heading-then-vs-await">.then() vs await</h3>
<p>In the early days of web browsers, promises and the <code>await</code> keyword didn't exist, so the only way to do something asynchronously was to use callbacks.</p>
<p>A "callback function" is a function that you hand to another function. That function then calls your callback later on. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeout</a> function we've used in the past is a good example.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"calling back now!"</span>)
}
<span class="hljs-keyword">const</span> milliseconds = <span class="hljs-number">1000</span>
<span class="hljs-built_in">setTimeout</span>(callbackFunction, milliseconds)
</code></pre>
<p>While even the <code>.then()</code> syntax is generally easier to use than callbacks without the <code>Promise</code> API, the <code>await</code> syntax makes them even easier to use. You should use <code>async</code> and <code>await</code> over <code>.then</code> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">new Promise()</a> as a general rule.</p>
<p>To demonstrate, which of these is easier to understand?</p>
<pre><code class="lang-js">fetchUser.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
  <span class="hljs-keyword">return</span> fetchLocationForUser(user)
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">location</span>)</span>{
  <span class="hljs-keyword">return</span> fetchServerForLocation(location)
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">server</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The server is <span class="hljs-subst">${server}</span>`</span>)
});
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser()
<span class="hljs-keyword">const</span> location = <span class="hljs-keyword">await</span> fetchLocationForUser(user)
<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">await</span> fetchServerForLocation(location)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The server is <span class="hljs-subst">${server}</span>`</span>)
</code></pre>
<p>They both do the same thing, but the second example is so much easier to understand! The <code>async</code> and <code>await</code> keywords weren't released until <em>after</em> the <code>.then</code> API, which is why there is still a lot of legacy <code>.then()</code> code out there.</p>
<h2 id="heading-error-handling">Error Handling</h2>
<p>When something goes wrong while a program is running, JavaScript uses the <code>try/catch</code> paradigm for handling those errors. Try/catch is fairly common, and <a target="_blank" href="https://boot.dev/learn/learn-python">Python</a> uses a similar mechanism.</p>
<h3 id="heading-first-an-error-is-thrown">First, an error is thrown</h3>
<p>For example, let's say we try to access a property on an undefined variable. JavaScript will automatically "throw" an error.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> speed = car.speed
<span class="hljs-comment">// The code crashes with the following error:</span>
<span class="hljs-comment">// "ReferenceError: car is not defined"</span>
</code></pre>
<h3 id="heading-trying-and-catching-errors">Trying and catching errors</h3>
<p>By wrapping that code in a try/catch block, we can handle the case where <code>car</code> is not yet defined.</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> speed = car.speed
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`An error was thrown: <span class="hljs-subst">${err}</span>`</span>)
  <span class="hljs-comment">// the code cleanly logs:</span>
  <span class="hljs-comment">// "An error was thrown: ReferenceError: car is not defined"</span>
}
</code></pre>
<h3 id="heading-bugs-vs-errors">Bugs vs Errors</h3>
<p>Error handling via try/catch is not the same as debugging. Likewise, errors are not the same as bugs.</p>
<ul>
<li><p>Good code with no bugs can still produce errors that are gracefully handled</p>
</li>
<li><p>Bugs are, by definition, bits of code that aren't working as intended</p>
</li>
</ul>
<h3 id="heading-what-is-debugging">What is Debugging?</h3>
<p>"Debugging" a program is the process of going through your code to find where it is not behaving as expected. Debugging is a manual process performed by the developer.</p>
<p>Examples of debugging:</p>
<ul>
<li><p>Adding a missing parameter to a function call</p>
</li>
<li><p>Updating a broken URL that an HTTP call was trying to reach</p>
</li>
<li><p>Fixing a date-picker component in an app that wasn't displaying properly</p>
</li>
</ul>
<h3 id="heading-what-is-error-handling">What is Error Handling?</h3>
<p>"Error handling" is code that can handle <em>expected</em> edge cases in your program. Error handling is an automated process that we design into our production code to protect it from things like weak internet connections, bad user input, or bugs in other people's code that we have to interface with.</p>
<p>Examples of error handling:</p>
<ul>
<li><p>Using a try/catch block to detect an issue with user input</p>
</li>
<li><p>Using a try/catch block to gracefully fail when no internet connection is available</p>
</li>
</ul>
<h3 id="heading-in-short-dont-use-trycatch-to-try-to-handle-bugs">In short, don't use try/catch to try to handle bugs</h3>
<p>If your code has a <a target="_blank" href="https://en.wikipedia.org/wiki/Software_bug">bug</a>, try/catch won't help you. You need to just go find the bug and fix it.</p>
<p>If something out of your control can produce issues in your code, you should use try/catch or other error-handling logic to deal with it.</p>
<p>For example, there could be a prompt in a game for users to type in a new character name, but we don't want them to use punctuation. Validating their input and displaying an error message if something is wrong with it would be a form of "error handling".</p>
<h3 id="heading-asyncawait-makes-error-handling-easier">async/await makes error handling easier</h3>
<p><code>try</code> and <code>catch</code> are the standard way to handle errors in JavaScript, the trouble is, the original Promise API with <code>.then</code> didn't allow us to make use of <code>try</code> and <code>catch</code> blocks.</p>
<p>Luckily, the <code>async</code> and <code>await</code> keywords <em>do</em> allow it - yet another reason to prefer the newer syntax.</p>
<h3 id="heading-catch-callback-on-promises">.catch() callback on promises</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch">.catch()</a> method works similarly to the .then() method, but it fires when a promise is <em>rejected</em> instead of resolved.</p>
<h3 id="heading-example-with-then-and-catch-callbacks">Example with .then and .catch callbacks</h3>
<pre><code class="lang-js">fetchUser().then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user fetched: <span class="hljs-subst">${user}</span>`</span>)
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`an error was thrown: <span class="hljs-subst">${err}</span>`</span>)
});
</code></pre>
<h3 id="heading-example-of-awaiting-a-promise-1">Example of awaiting a promise</h3>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser()
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user fetched: <span class="hljs-subst">${user}</span>`</span>)
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`an error was thrown: <span class="hljs-subst">${err}</span>`</span>)
}
</code></pre>
<p>As you can see, the <code>async/await</code> version looks just like normal <code>try/catch</code> JavaScript.</p>
<h2 id="heading-http-headers">HTTP Headers</h2>
<p>An <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header">HTTP header</a> allows clients and servers to pass <em>additional</em> information with each request or response. Headers are just case-insensitive <a target="_blank" href="https://en.wikipedia.org/wiki/Name%E2%80%93value_pair">key-value pairs</a> that pass additional <a target="_blank" href="https://en.wikipedia.org/wiki/Metadata">metadata</a> about the request or response.</p>
<p>HTTP requests from a web browser carry with them many headers, including but not limited to:</p>
<ul>
<li><p>The type of client (for example Google Chrome)</p>
</li>
<li><p>The Operating system (for example Windows)</p>
</li>
<li><p>The preferred language (for example US English)</p>
</li>
</ul>
<p>As developers, we can also define custom headers in each request.</p>
<h3 id="heading-headers-api">Headers API</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Headers">Headers</a> API allows us to perform various actions on our request and response headers such as retrieving, setting, and removing them. We can access the headers object through the <code>Request.headers</code> and <code>Response.headers</code> properties.</p>
<h3 id="heading-how-to-use-the-browsers-developer-tools">How to Use the Browser's Developer Tools</h3>
<p>Modern web browsers offer developers a powerful set of <em>developer tools</em>. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">Developer Tools</a> are a front-end web developer's best friend. For example, using the dev tools you can:</p>
<ul>
<li><p>View the web page's JavaScript console output</p>
</li>
<li><p>Inspect the page's HTML, CSS, and JavaScript code</p>
</li>
<li><p>View network requests and responses, along with their headers</p>
</li>
</ul>
<p>The method for accessing dev tools varies from browser to browser. If you're on Chrome, you can just right-click anywhere within a web page and click the "inspect" option. Follow this link for more info on <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools#:~:text=How%20do%20you%20pull%20it%20up%3F%20Three%20ways%3A">how to access dev tools</a>.</p>
<h3 id="heading-the-network-tab">The network tab</h3>
<p>While all of the tabs within the dev tools are very useful, we will be focusing specifically on the <em>Network tab</em> in this chapter so we can play with HTTP headers.</p>
<p>The Network tab monitors your browser's network activity and records all of the requests and responses the browser is making, including how long each of those requests and responses takes to fully process.</p>
<p>If you navigate to the Network tab and don't see any requests appear, try refreshing the page.</p>
<p><img src="https://i.imgur.com/STKdceG.png" alt="Image" width="580" height="372" loading="lazy"></p>
<h3 id="heading-why-are-headers-useful">Why are headers useful?</h3>
<p>Headers are useful for several reasons, from design to security. But most often headers are used as <a target="_blank" href="https://en.wikipedia.org/wiki/Metadata">metadata</a> or data <em>about</em> the request.</p>
<p>So, for example, let's say we wanted to ask for a player's level from a game's server. We need to send that player's ID to the server so it knows which player to send back the information for. That ID <em>is my request</em>, it's not information <em>about my request</em>.</p>
<p>A good example of a use case for headers is <a target="_blank" href="https://auth0.com/intro-to-iam/what-is-authentication/">authentication</a>. Often times a user's credentials are included in request headers. Credentials don't have much to do with the request <em>itself</em>, but simply authorize the requester to be allowed to make the request in question.</p>
<h2 id="heading-what-is-json">What is JSON?</h2>
<p>JavaScript Object Notation, or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON">JSON</a>, is a standard for representing <em>structured</em> data based on JavaScript's object syntax.</p>
<p>JSON is commonly used to transmit data in web apps using HTTP. The HTTP <code>fetch()</code> requests we have been using in this course have been returning data as JSON data.</p>
<h3 id="heading-json-syntax">JSON Syntax</h3>
<p>Because we already understand what JavaScript objects look like, understanding JSON is easy. JSON is just a stringified JavaScript object. The following is valid JSON data:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"movies"</span>: [
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Iron Man"</span>,
            <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Jon Favreau"</span>
        },
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"The Avengers"</span>,
            <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Joss Whedon"</span>
        }
    ]
}
</code></pre>
<h3 id="heading-how-to-parse-http-responses-as-json">How to Parse HTTP Responses as JSON</h3>
<p>JavaScript provides us with some easy tools to help us work with JSON. After making an HTTP request with the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch() API</a>, we get a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response object</a>. That response object offers us some methods that help us interact with the response.</p>
<p>One such method is the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response/json">.json()</a> method. The <code>.json()</code> method takes the response stream returned by a fetch request and returns a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves into a JavaScript object parsed from the JSON body of the HTTP response.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(...)
<span class="hljs-keyword">const</span> javascriptObjectResponse = <span class="hljs-keyword">await</span> resp.json()
</code></pre>
<p>It's important to note that the result of the <code>.json()</code> method is <em>NOT</em> JSON. It is the result of taking JSON data from the HTTP response body and parsing that input into a JavaScript Object.</p>
<h3 id="heading-json-review">JSON Review</h3>
<p>JSON is a <em>stringified representation</em> of a JavaScript object, which makes it perfect for saving to a file or sending in an HTTP request.</p>
<p>Remember, an actual JavaScript object is something that exists only within your program's variables. If we want to send an object outside our program, for example, across the internet in an HTTP request, we need to convert it to JSON first.</p>
<h3 id="heading-its-not-just-used-in-javascript">It's not just used in JavaScript</h3>
<p>Just because JSON is called <em>JavaScript</em> Object Notation doesn't mean it's only used by JavaScript! JSON is a common standard that is recognized and supported by every major programming language.</p>
<p>For example, even though Boot.dev's backend API is written in <a target="_blank" href="https://boot.dev/learn/learn-golang">Go</a>, we still use <a target="_blank" href="https://blog.boot.dev/golang/json-golang/">JSON</a> as the communication format between the front-end and backend.</p>
<p>By the way, this course has been about interacting with back-end servers from a front-end perspective. But if you're curious about how you can become a back-end engineer, <a target="_blank" href="https://blog.boot.dev/backend/become-backend-developer/">check out this guide</a> I've put together. For reference, it takes most people <a target="_blank" href="https://blog.boot.dev/backend/how-long-to-become-backend-dev/">between 6-18 months</a> to learn enough to get their first <a target="_blank" href="https://blog.boot.dev/backend/backend-job-description/">back-end job</a>.</p>
<h3 id="heading-common-json-use-cases">Common JSON use-cases</h3>
<ul>
<li><p>In HTTP request and response bodies</p>
</li>
<li><p>As formats for text files. <code>.json</code> files are often used as configuration files.</p>
</li>
<li><p>In NoSQL databases like MongoDB, ElasticSearch, and Firestore</p>
</li>
</ul>
<h3 id="heading-how-to-pronounce-json">How to Pronounce JSON</h3>
<p>I pronounce it "Jay-sawn", but I've also heard people pronounce it "Jason", like the name.</p>
<h3 id="heading-how-to-send-json">How to Send JSON</h3>
<p>JSON isn't just something we get from the server, we can also <em>send</em> JSON data.<br>In JavaScript, two of the main methods we have access to are <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse()</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a>.</p>
<h4 id="heading-jsonstringify"><code>JSON.stringify()</code></h4>
<p><code>JSON.stringify()</code> is particularly useful for <em>sending</em> JSON.</p>
<p>As you may expect, the JSON <code>stringify()</code> method does the opposite of parse. It takes a JavaScript object or value as input and converts it into a string. This is useful when we need to serialize the objects into strings to send them to our server or store them in a database.</p>
<p>Here's a snippet of code that sends a JSON payload to a remote server:</p>
<pre><code class="lang-plaintext">async function sendPayload(data, headers) {
  const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    headers: headers,
    body: JSON.stringify(data)
  })
  return response.json()
}
</code></pre>
<h3 id="heading-how-to-parse-json">How to Parse JSON</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse()</a> method takes a JSON string as input and constructs the JavaScript value/object described by the string. This allows us to work with the JSON as a normal JavaScript object.</p>
<p>Seeing as JSON objects have a tree-like structure, it can be helpful to know how to <a target="_blank" href="https://blog.boot.dev/javascript/how-to-recursively-traverse-objects/">traverse them recursively</a> if needs be.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> json = <span class="hljs-string">'{"title": "Avengers Endgame", "Rating":4.7, "inTheaters":false}'</span>;
<span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">JSON</span>.parse(json)

<span class="hljs-built_in">console</span>.log(obj.title)
<span class="hljs-comment">// Avengers Endgame</span>
</code></pre>
<h3 id="heading-xml">XML</h3>
<p>We can't talk about JSON without mentioning <a target="_blank" href="https://en.wikipedia.org/wiki/XML#:~:text=Extensible%20Markup%20Language%20\(XML\)%20is,%2Dreadable%20and%20machine%2Dreadable.">XML</a>. Extensible Markup Language, or <code>XML</code> is a text-based format for representing structured information, just like JSON - it just looks a bit different.</p>
<p>XML is a markup language like <a target="_blank" href="https://en.wikipedia.org/wiki/HTML">HTML</a>, but it's more generalized in that it does <em>not</em> use predefined tags. Just like how in a JSON object keys can be called anything, XML tags can also have any name.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">root</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">genre</span>&gt;</span>Action<span class="hljs-tag">&lt;/<span class="hljs-name">genre</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Iron Man<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">director</span>&gt;</span>Jon Favreau<span class="hljs-tag">&lt;/<span class="hljs-name">director</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">root</span>&gt;</span>
</code></pre>
<p>The same data in JSON form:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"id"</span>: <span class="hljs-string">"1"</span>,
  <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
  <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Iron Man"</span>,
  <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Jon Favreau"</span>
}
</code></pre>
<h3 id="heading-why-use-xml">Why use XML?</h3>
<p>XML and JSON both accomplish similar tasks, so which should you use?</p>
<p>XML used to be used for the same things that today JSON is used for. Configuration files, HTTP bodies, and other data-transfer use cases can work just fine using JSON or XML. Here's my advice: generally speaking, if JSON works, you should favor it over XML these days. JSON is lighter-weight, easier to read, and has better support in most modern programming languages.</p>
<p>There are some cases where XML might still be the better, or maybe even the necessary choice, but those cases will be rare.</p>
<h2 id="heading-http-methods">HTTP Methods</h2>
<p>HTTP defines a set of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">methods</a> that we use every time we make a request. We have used some of these methods in previous exercises, but it's time we dive into them and understand the differences and use cases behind the different methods.</p>
<h3 id="heading-the-get-method">The GET method</h3>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-get-request-tutorial/">GET method</a> is used to "get" a representation of a specified resource. You are not taking the data away from the server, but rather getting a representation, or copy, of the resource in its current state.</p>
<p>A get request is considered a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP">safe</a> method to call multiple times because it doesn't alter the state of the server.</p>
<h3 id="heading-how-to-make-a-get-request-using-the-fetch-api">How to Make a GET Request using the Fetch API</h3>
<p>The fetch() method accepts an optional <code>init</code> object parameter as its second argument that we can use to define things like:</p>
<ul>
<li><p><code>method</code>: The HTTP method of the request, like <code>GET</code>.</p>
</li>
<li><p><code>headers</code>: The headers to send.</p>
</li>
<li><p><code>mode</code>: Used for security, we'll talk about this in future courses</p>
</li>
<li><p><code>body</code>: The body of the request. Often encoded as JSON.</p>
</li>
</ul>
<p>Example <code>GET</code> request using fetch:</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'sec-ch-ua-platform'</span>: <span class="hljs-string">'macOS'</span>
  }
})
</code></pre>
<h3 id="heading-why-do-we-use-http-methods">Why do we use HTTP methods?</h3>
<p>As we touched on before, the primary purpose of HTTP methods is to indicate to the server what we want to do with the resource we're trying to interact with.</p>
<p>At the end of the day, an HTTP method is just a string, like <code>GET</code>, <code>POST</code>, <code>PUT</code>, or <code>DELETE</code>. But by <em>convention</em>, backend developers almost always write their server code so that the methods correspond with different "CRUD" actions.</p>
<p>The "CRUD" actions are:</p>
<ul>
<li><p>Create</p>
</li>
<li><p>Read</p>
</li>
<li><p>Update</p>
</li>
<li><p>Delete</p>
</li>
</ul>
<p>The bulk of the logic in most web applications is "CRUD" logic. The web interface allows users to create, read, update and delete various resources.</p>
<p>Think of a social media site - users are basically creating, reading, updating and deleting their social posts. They are also creating, reading, updating and deleting their user accounts. It's CRUD all the way down!</p>
<p>As it happens, the 4 most common HTTP methods map nicely to the CRUD actions:</p>
<ul>
<li><p><code>POST</code> = create</p>
</li>
<li><p><code>GET</code> = read</p>
</li>
<li><p><code>PUT</code> = update</p>
</li>
<li><p><code>DELETE</code> = delete</p>
</li>
</ul>
<h3 id="heading-post-requests">POST Requests</h3>
<p>An <a target="_blank" href="https://www.freecodecamp.org/news/javascript-post-request-how-to-send-an-http-post-request-in-js/">HTTP POST request</a> sends data to a server, typically to create a new resource. The <code>body</code> of the request is the <em>payload</em> that is being sent to the server with the request. Its type is indicated by the <code>Content-Type</code> header.</p>
<h3 id="heading-how-to-add-a-body">How to Add a <code>body</code></h3>
<p>The <code>body</code> of the request is the <em>payload</em> that is being sent to the server with the request. Its type is indicated by the <code>Content-Type</code> header - for us, that's going to be JSON.</p>
<p><code>POST</code> requests are generally <em>not</em> safe methods to call multiple times, because it alters the state of the server. You wouldn't want to accidentally create 2 accounts for the same user, for example.</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data)
})
</code></pre>
<h3 id="heading-http-status-codes">HTTP Status Codes</h3>
<p>Now that we understand how to write HTTP requests from scratch, we need to learn how to ensure that the server is doing what we want.</p>
<p>Earlier in the course, we learned about how to access the browser's <em>developer tools</em> and use those tools to inspect HTTP requests. We can use that same process to check on the requests we are making and verify what they are doing so we can address potential problems.</p>
<p>When looking at requests, we can check on the <code>Status Code</code> of the request to get some information if the request was successful or not.</p>
<ul>
<li><p><code>100-199</code>: Informational responses. These are very rare.</p>
</li>
<li><p><code>200-299</code>: Successful responses. Hopefully, most responses are 200's!</p>
</li>
<li><p><code>300-399</code>: Redirection messages. These are typically invisible because the browser or HTTP client will automatically do the redirect.</p>
</li>
<li><p><code>400-499</code>: Client errors. You'll see these often, especially when trying to debug a client application</p>
</li>
<li><p><code>500-599</code>: Server errors. You'll see these sometimes, usually only if there is a bug on the server.</p>
</li>
</ul>
<p>Here are some of the most common status codes, but you can see a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">full list here</a> if you're interested.</p>
<ul>
<li><p><code>200</code> - OK. This is by far the most common code, it just means that everything worked as expected.</p>
</li>
<li><p><code>201</code> - Created. This means that a resource was created successfully. Typically in response to a <code>POST</code> request.</p>
</li>
<li><p><code>301</code> - Moved permanently. This means the resource was moved to a new place, and the response will include where that new place is. Websites often use <code>301</code> redirects when they change their domain name, for example.</p>
</li>
<li><p><code>400</code> - Bad request. A general error indicating the client made a mistake in their request.</p>
</li>
<li><p><code>403</code> - Unauthorized. This means the client doesn't have the correct permissions. Maybe they didn't include a required authorization header, for example.</p>
</li>
<li><p><code>404</code> - Not found. You'll see this on websites quite often. It just means the resource doesn't exist.</p>
</li>
<li><p><code>500</code> - Internal server error. This means something went wrong on the server, likely a bug on their end.</p>
</li>
</ul>
<h3 id="heading-you-dont-need-to-memorize-them">You don't need to memorize them</h3>
<p>You need to know the basics, like "2XX is good", "4XX is a client error", and "5XX is a server error". That said, you don't need to memorize all the codes, they're easy to look up.</p>
<p><img src="https://i.imgur.com/FJl2z9O.jpg" alt="Image" width="549" height="454" loading="lazy"></p>
<p>Let's check some status codes!</p>
<p>The <code>.status</code> property on a Response object will give you the code. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStatusCode</span>(<span class="hljs-params">url, headers</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: headers
  })
  <span class="hljs-keyword">return</span> response.status
}
</code></pre>
<h3 id="heading-put-method">PUT Method</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">HTTP PUT method</a> creates a new resource or replaces a representation of the target resource with the contents of the request's <code>body</code>. In short, it updates a resource's properties.</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
   <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
   <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
   <span class="hljs-attr">headers</span>: {
   <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
   },
   <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data)
})
</code></pre>
<h3 id="heading-post-vs-put">POST vs PUT</h3>
<p>You may be thinking <code>PUT</code> is similar to <code>POST</code> or <code>PATCH</code>, and frankly, you'd be right. The main difference is that PUT is meant to be <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Idempotent">idempotent</a>, meaning multiple identical PUT requests should have the same effect on the server.</p>
<p>In contrast, several identical <code>POST</code> requests would have additional side effects, such as creating multiple copies of the resource.</p>
<h3 id="heading-http-patch-vs-put">HTTP Patch vs PUT</h3>
<p>You may encounter <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH">PATCH</a> methods from time to time. While it is not nearly as common as the other methods, like <code>PUT</code>, it's important to know about it and what it does. The <code>PATCH</code> method is intended to <em>partially</em> modify a resource.</p>
<p>Long story short, <code>PATCH</code> isn't nearly as popular as <code>PUT</code>, and many servers, even if they allow partial updates, will still just use the <code>PUT</code> method for that.</p>
<h3 id="heading-http-delete">HTTP Delete</h3>
<p>The <code>DELETE</code> method does exactly as you would expect: it's conventionally used to delete a specified resource.</p>
<pre><code class="lang-js"><span class="hljs-comment">// This deletes the location with ID: 52fdfc07-2182-454f-963f-5f0f9a621d72</span>
<span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://example-api.com/locations/52fdfc07-2182-454f-963f-5f0f9a621d72'</span>

<span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>
})
</code></pre>
<h2 id="heading-url-paths-and-parameters">URL Paths and Parameters</h2>
<p>The URL Path comes right after the domain (or port if one is provided) in a URL string.</p>
<p>In this URL, the path is <code>/root/next</code>: <code>http://testdomain.com/root/next</code>.</p>
<h3 id="heading-what-paths-meant-in-the-early-internet">What paths meant in the early internet</h3>
<p>In the early days of the internet, and sometimes still today, many web servers simply served raw files from the server's file system.</p>
<p>For example, if I wanted you to be able to access some text documents, I could start a web server in my <code>documents</code> directory. If you made a request to my server, you would be able to access different documents by using the path that matched my local file structure.</p>
<p>If I had a file in my local <code>/documents/hello.txt</code>, you could access it by making a <code>GET</code> request to <code>http://example.com/documents/hello.txt</code>.</p>
<h3 id="heading-how-paths-are-used-today">How paths are used today</h3>
<p>Most modern web servers don't use that simple mapping of <code>URL path</code> -&gt; <code>file path</code>. Technically, a URL path is just a string that the web server can do what it wants with, and modern websites take advantage of that flexibility.</p>
<p>Some common examples of what paths are used for include:</p>
<ul>
<li><p>The hierarchy of pages on a website, whether or not that reflects a server's file structure</p>
</li>
<li><p>Parameters being passed into an HTTP request, like an ID of a resource</p>
</li>
<li><p>The version of the API</p>
</li>
<li><p>The type of resource being requested</p>
</li>
</ul>
<h3 id="heading-restful-apis">RESTful APIs</h3>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/REST">Representational State Transfer, or REST</a>, is a popular convention that HTTP servers follow. Not all HTTP APIs are "REST APIs", or "RESTful", but it is <em>very</em> common.</p>
<p>RESTful servers follow a loose set of rules that makes it easy to build reliable and predictable web APIs. REST is more or less a set of conventions about how HTTP <em>should</em> be used.</p>
<h3 id="heading-separate-and-agnostic">Separate and agnostic</h3>
<p>The big idea behind REST is that resources are transferred via well-recognized, language-agnostic client/server interactions.</p>
<p>A RESTful style means the implementation of the client and server can be done independently of one another, as long as some simple standards, like the names of the available resources, have been established.</p>
<h3 id="heading-stateless">Stateless</h3>
<p>A RESTful architecture is stateless. This means that the server does not need to know what state the client is in, nor does the client need to know what state the server is in.</p>
<p>Statelessness in REST is enforced by interacting with resources instead of commands. Keep in mind, this doesn't mean the applications are stateless - on the contrary, what would "updating a resource" even mean if the server wasn't keeping track of its state?</p>
<h3 id="heading-paths-in-rest">Paths in REST</h3>
<p>In a RESTful API, the last section of the <code>path</code> of a URL should specify which resource is being accessed. Then, as we talked about in the "methods" section, depending on whether the request is a <code>GET</code>, <code>POST</code>, <code>PUT</code> or <code>DELETE</code>, the resource is read, created, updated, or deleted.</p>
<p>For example, in the <a target="_blank" href="https://pokeapi.co/">PokeAPI</a>:</p>
<ul>
<li><p><a target="_blank" href="https://pokeapi.co/api/v2/pokemon/"><code>https://pokeapi.co/api/v2/pokemon/</code></a></p>
</li>
<li><p><a target="_blank" href="https://pokeapi.co/api/v2/pokemon/"><code>https://pokeapi.co/api/v2/location/</code></a></p>
</li>
</ul>
<p>The first part of the path specifies that we're interacting with an API rather than a website. The next part specifies the version, in this case, version 2, or <code>v2</code>.</p>
<p>Finally, the last part denotes which resource is being accessed, be it a <code>location</code> or <code>pokemon</code>.</p>
<h3 id="heading-url-query-parameters">URL Query Parameters</h3>
<p>A URL's query parameters appear next in the URL structure but are <em>not</em> always present - they're optional. For example:</p>
<p><a target="_blank" href="https://www.google.com/search?q=boot.dev">https://www.google.com/search?q=boot.dev</a></p>
<p><code>q=boot.dev</code> is a query parameter. Like headers, query parameters are <code>key / value</code> pairs. In this case, <code>q</code> is the key and <code>boot.dev</code> is the value.</p>
<h3 id="heading-the-documentation-of-an-http-server">The Documentation of an HTTP Server</h3>
<p>You may be wondering:</p>
<blockquote>
<p>How the heck am I supposed to memorize how all these different servers work???</p>
</blockquote>
<p>The good news is that <em>you don't need to</em>. When you work with a backend server, it's the responsibility of that server's developers to provide you with instructions, or <em>documentation</em> that explains how to interact with it.</p>
<p>For example, the documentation should tell you:</p>
<ul>
<li><p>The domain of the server</p>
</li>
<li><p>The resources you can interact with (HTTP paths)</p>
</li>
<li><p>The supported query parameters</p>
</li>
<li><p>The supported HTTP methods</p>
</li>
<li><p>Anything else you'll need to know to work with the server</p>
</li>
</ul>
<p><img src="https://i.imgur.com/GIlWhYF.jpg" alt="Image" width="500" height="553" loading="lazy"></p>
<p>The server has control</p>
<p>As we mentioned earlier, the server has complete control over how the path in a URL is interpreted and used in a request. The same goes for query parameters.</p>
<p>Not all servers support query parameters for every type of request, it just depends, so you'll need to consult the docs.</p>
<h3 id="heading-multiple-query-parameters">Multiple Query Parameters</h3>
<p>We mentioned that query parameters are <code>key/value</code> pairs - that means we can have multiple pairs.</p>
<p><code>http://example.com?firstName=lane&amp;lastName=wagner</code></p>
<p>In the example above:</p>
<ul>
<li><p><code>firstName</code> = <code>lane</code></p>
</li>
<li><p><code>lastName</code> = <code>wagner</code></p>
</li>
</ul>
<p>The <code>?</code> separates the query parameters from the rest of the URL. The <code>&amp;</code> is then used to separate <em>every pair</em> of query parameters after that.</p>
<p>For example, make this request to limit the number of Pokémon returned from the PokeAPI to <code>2</code>:</p>
<pre><code class="lang-plaintext">https://pokeapi.co/api/v2/location/?limit=2
</code></pre>
<h2 id="heading-what-is-https">What is HTTPs?</h2>
<p>Hypertext Transfer Protocol <em>Secure</em> or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-https-http-vs-https-meaning-and-how-it-works/">HTTPS</a> is an extension of the HTTP protocol. HTTPS secures the data transfer between client and server by <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Encryption">encrypting</a> all of the communication.</p>
<p>HTTPS allows a client to safely share sensitive information with the server through an HTTP request, such as credit card information, passwords, or bank account numbers.</p>
<p>HTTPS requires that the client use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/SSL">SSL</a> or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-tls-transport-layer-security-encryption-explained-in-plain-english/">TLS</a> to protect requests and traffic by encrypting the information in the request. HTTPS is just HTTP with extra security.</p>
<p><img src="https://i.imgur.com/iOkQUdG.png" alt="Image" width="517" height="487" loading="lazy"></p>
<p><em>HTTP vs HTTPS</em></p>
<h3 id="heading-https-keeps-your-messages-private-but-not-your-identity">HTTPS keeps your messages private, but not your identity</h3>
<p>We won't cover <em>how</em> encryption works in this course, but we will in later courses. For now, it's important to note that while HTTPS encrypts <em>what you are saying</em>, it doesn't necessarily protect <em>who you are</em>. Tools like <a target="_blank" href="https://nordvpn.com/what-is-a-vpn/">VPNs</a> are needed for remaining anonymous online.</p>
<h3 id="heading-https-ensures-that-youre-talking-to-the-right-person-or-server">HTTPS ensures that you're talking to the right person (or server)</h3>
<p>In addition to encrypting the information within a request, HTTPS uses <a target="_blank" href="https://en.wikipedia.org/wiki/Digital_signature">digital signatures</a> to prove that you're communicating with the server that you think you are.</p>
<p>If a hacker were to intercept an HTTPS request by tapping into a network cable, they wouldn't be able to successfully pretend they are your bank's web server.</p>
<p>Assuming that a server supports HTTPs, you use it by simply changing the protocol on your request URL: <code>https://boot.dev</code></p>
<h3 id="heading-want-to-put-what-youve-learned-into-practice-with-a-project">Want to put what you've learned into practice with a project?</h3>
<p>Check out this <a target="_blank" href="https://boot.dev/build/link-analyzer">project guide where you'll build a web crawler in JavaScript</a> from scratch. It will have you using the Fetch API and parsing JSON data like a pro! You don't need to build the project, but it's a great way to practice what you're learned.</p>
<h2 id="heading-congratulations-on-making-it-to-the-end">Congratulations on making it to the end!</h2>
<p>If you're interested in doing the interactive coding assignments and quizzes for this course you can check out the <a target="_blank" href="https://boot.dev/learn/learn-object-oriented-programming">Learn HTTP course</a> over on <a target="_blank" href="https://boot.dev/">Boot.dev</a>.</p>
<p>This course is a part of my <a target="_blank" href="https://boot.dev/tracks/backend">full back-end developer career path</a>, made up of other courses and projects if you're interested in checking those out.</p>
<p>If you want to see the other content I'm creating related to web development, check out some of my links below:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/wagslane">Lane on Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://youtube.com/@bootdotdev">Lane on YouTube</a></p>
</li>
<li><p><a target="_blank" href="https://wagslane.dev">Lane's Personal Site</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Object Oriented Programming in Python – Full Crash Course ]]>
                </title>
                <description>
                    <![CDATA[ Object Oriented programming, or "OOP" for short, is a way of writing code that relies on the concepts of classes and objects.  The main benefit of writing your code in an object-oriented way is to structure your program into simple, reusable pieces o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/crash-course-object-oriented-programming-in-python/</link>
                <guid isPermaLink="false">66b9e9e58e39a257778833a4</guid>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Thu, 20 Oct 2022 22:24:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/udaXTUR.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Object Oriented programming, or "OOP" for short, is a way of writing code that relies on the concepts of classes and objects. </p>
<p>The main benefit of writing your code in an object-oriented way is to structure your program into simple, reusable pieces of code.</p>
<p>Stick with me through this article and you'll have a full understanding of the core tenets of OOP by the end. All the coding examples will be in <a target="_blank" href="https://boot.dev/learn/learn-python">Python</a>, but the concepts apply generally to all coding languages.</p>
<p>I've included all the learning material you'll need here in this article. But if you would like to go more in-depth with live coding exercises and quizzes, you can find those <a target="_blank" href="https://boot.dev/learn/learn-object-oriented-programming">here</a> on <a target="_blank" href="https://boot.dev/">Boot.dev</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-the-goal-of-oop-is-cleaner-code">The Goal of Object Oriented Programming</a></li>
<li><a class="post-section-overview" href="#heading-classes-allow-for-even-more-reusability">Classes in OOP</a></li>
<li><a class="post-section-overview" href="#heading-oop-pillar-1-encapsulation">OOP Pillar #1 –Encapsulation</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/463de7a5-749b-49da-96e9-223a08fc983b/oop-pillar-2-abstraction">OOP Pillar #2 –Abstraction</a></li>
<li><a class="post-section-overview" href="#heading-oop-pillar-3-inheritance">OOP Pillar #3 –Inheritance</a></li>
<li><a class="post-section-overview" href="#heading-oop-pillar-4-polymorphism">OOP Pillar #4 –Polymorphism</a></li>
</ol>
<h2 id="heading-the-goal-of-oop-is-cleaner-code">The Goal of OOP is Cleaner Code</h2>
<p>Object oriented programming and other paradigms like <a target="_blank" href="https://boot.dev/learn/learn-functional-programming">functional programming</a> are all about making code easier to work with and understand. We call code that is easy to work with "clean code".</p>
<blockquote>
<p>Any fool can write code that a computer can understand. Good programmers write code that humans can understand. – Martin Fowler</p>
</blockquote>
<h3 id="heading-clean-code-is-not">Clean code is not:</h3>
<ul>
<li>A way to make your programs run faster</li>
<li>A way to make your program use less memory</li>
<li>Necessary to create certain kinds of programs</li>
<li>Strictly better than non-OOP code</li>
</ul>
<h3 id="heading-clean-code-is">Clean code is:</h3>
<ul>
<li>Designed to make code easier to work with in many situations</li>
<li>Something that helps humans model and simulate the real world</li>
<li>A way to make finding and fixing bugs easier</li>
<li>A way to make new feature development faster</li>
<li>The best way to stay sane as a software engineer</li>
</ul>
<p>A couple of examples of "clean code" practices include <a target="_blank" href="https://blog.boot.dev/clean-code/code-comments/">writing good comments</a>, using <a target="_blank" href="https://blog.boot.dev/clean-code/dry-code/">DRY code</a>, and <a target="_blank" href="https://blog.boot.dev/clean-code/naming-variables/">naming variables well</a>, just to name a few.</p>
<h2 id="heading-oop-is-a-way-to-write-dry-code">OOP is a Way to Write DRY Code</h2>
<p>Let's pretend we have some code that looks like this:</p>
<pre><code class="lang-python">soldier_one_dps = soldier_one[<span class="hljs-string">"damage"</span>] * soldier_one[<span class="hljs-string">"attacks_per_second"</span>]

soldier_two_dps = soldier_two[<span class="hljs-string">"damage"</span>] * soldier_two[<span class="hljs-string">"attacks_per_second"</span>]
</code></pre>
<p>We can use a function to refactor the code a bit:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_soldier_dps</span>(<span class="hljs-params">soldier</span>):</span>
    <span class="hljs-keyword">return</span> soldier[<span class="hljs-string">"damage"</span>] * soldier[<span class="hljs-string">"attacks_per_second"</span>]

soldier_one_dps = get_soldier_dps(soldier_one)
soldier_two_dps = get_soldier_dps(soldier_two)
</code></pre>
<p>We don't want too much of our code doing the exact same thing. When code is duplicated, it leads to many potential problems. In our example, let's pretend the <code>soldier</code> dictionary changed, and now the key that stores the "damage" value is called <code>dmg</code>.</p>
<p>In the first example, we would need to update two lines of code. In the second example, we only need to make the change in one place.</p>
<p>It's not a big deal when two lines are the same and exist right next to each other. However, imagine if we had done this hundreds of times in ten or twenty different code files! All of sudden, it makes a lot sense to stop repeating yourself and write more reusable functions. We call that <a target="_blank" href="https://blog.boot.dev/clean-code/dry-code/">DRY (don't repeat yourself) code</a>.</p>
<h2 id="heading-classes-allow-for-even-more-reusability">Classes Allow for Even More Reusability</h2>
<p>A <a target="_blank" href="https://boot.dev/course/f9a48bbc-d1ff-4388-bf0c-23c6e3c60ae0/46f1f86f-9b7c-4a8b-8883-4b407c0e675b">class</a> is a special type of value in an object-oriented programming language like Python. Just like a string, integer, or float, a class is a <em>custom</em> type that has some special properties.</p>
<p>An object is just an instance of a class type. "Instance" is just a big word for "one of a thing". For example, here, <code>health</code> is an instance of an integer type.</p>
<pre><code class="lang-python">health = <span class="hljs-number">50</span>
</code></pre>
<h3 id="heading-how-do-i-create-a-class">How do I create a class?</h3>
<p>In Python you just need to use the <code>class</code> keyword, and you can set custom properties in the following way.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    health = <span class="hljs-number">5</span>
</code></pre>
<p>Then to create an instance of a <code>Soldier</code> we simply call the class. Notice that a class isn't a function, and it doesn't take input parameters directly.</p>
<pre><code class="lang-python">first_soldier = Soldier()
print(first_soldier.health)
<span class="hljs-comment"># prints "5"</span>
</code></pre>
<h3 id="heading-methods-on-a-class">Methods on a class</h3>
<p>You might be wondering why classes are useful – they seem like regular Python dictionaries but worse! </p>
<p>What makes classes really cool is that they allow us to define custom <a target="_blank" href="https://en.wikipedia.org/wiki/Method_(computer_programming)">methods</a> on them. A method is a function that is associated with a class, and it has access to all the properties of the object.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    health = <span class="hljs-number">5</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">take_damage</span>(<span class="hljs-params">self, damage</span>):</span>
        self.health -= damage

soldier_one = Soldier()
soldier_one.take_damage(<span class="hljs-number">2</span>)
print(soldier_one.health)
<span class="hljs-comment"># prints "3"</span>
</code></pre>
<h3 id="heading-the-special-self-value">The special "self" value</h3>
<p>As you can see, methods are nested within the <code>class</code> declaration. Methods always take a special parameter as their first argument called <code>self</code>. The <code>self</code> variable is a reference to the object itself, so by using it you can read and update the properties of the object.</p>
<p>Notice that methods are called directly on an object using the dot operator.</p>
<pre><code class="lang-python">object.method()
</code></pre>
<h3 id="heading-how-to-return-values-from-a-method">How to return values from a method</h3>
<p>If a regular function doesn't return anything, it's typically not a very useful function. But methods often don't return anything explicitly because they often mutate the properties of the object instead.</p>
<p>However, they <em>can</em> return values as well!</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    armor = <span class="hljs-number">2</span>
    num_weapons = <span class="hljs-number">2</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_speed</span>(<span class="hljs-params">self</span>):</span>
        speed = <span class="hljs-number">10</span>
        speed -= self.armor
        speed -= self.num_weapons
        <span class="hljs-keyword">return</span> speed

soldier_one = Soldier()
print(soldier_one.get_speed())
<span class="hljs-comment"># prints "6"</span>
</code></pre>
<h3 id="heading-methods-vs-functions">Methods vs Functions</h3>
<p>A function is a piece of code that is called by a name. You can pass it data to operate on via parameters and it can optionally return data. All data that is passed to a function is explicitly passed through parameters.</p>
<p>A method is a piece of code that is called by a name <em>that is associated with an object</em>. Methods and functions are similar but have two key differences.</p>
<ol>
<li>A method is <em>implicitly</em> passed the object on which it was called. In other words, you won't see all the inputs in the parameter list</li>
<li>A method is able to operate on data that is contained within the class. In other words, you won't see all the outputs in the <code>return</code> statement.</li>
</ol>
<h2 id="heading-the-oop-debate">The OOP Debate</h2>
<p>Because functions are more explicit, some developers argue that <a target="_blank" href="https://blog.boot.dev/clean-code/benefits-of-functional-programming/">functional programming</a> is better than object oriented programming. In reality, neither paradigm is "better", and the best developers learn and understand both styles and use them as they see fit.</p>
<p>For example, while methods are more implicit and often make code more difficult to read, they also make it easier to group a program's data and behavior together in one place. This can lead to a codebase that's more organized. The tradeoff is one of readability at the file level for readability at the project level.</p>
<h2 id="heading-constructors-in-python">Constructors in Python</h2>
<p>It's quite rare in the real-world to see a class that defines properties in the way we've been doing it so far.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    armor = <span class="hljs-number">2</span>
    num_weapons = <span class="hljs-number">2</span>
</code></pre>
<p>It's much more practical to use a <a target="_blank" href="https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)">constructor</a>. In Python, a constructor is made with the <a target="_blank" href="https://docs.python.org/3/reference/datamodel.html#object.__init__"><strong>init</strong>() method</a>, and it is automatically called when a new object is created. So, with a constructor the code would look like this.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.armor = <span class="hljs-number">2</span>
        self.num_weapons = <span class="hljs-number">2</span>
</code></pre>
<p>However, because the constructor is a method, we can now make the starting armor and number of weapons configurable with some parameters.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Soldier</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, armor, num_weapons</span>):</span>
        self.armor = armor
        self.num_weapons = num_weapons

soldier = Soldier(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>)
print(soldier.armor)
<span class="hljs-comment"># prints "5"</span>
print(soldier.num_weapons)
<span class="hljs-comment"># prints "10"</span>
</code></pre>
<h2 id="heading-class-variables-vs-instance-variables">Class Variables vs Instance Variables</h2>
<p>So far we've worked with both class variables and instance variables, but we haven't really talked about the difference yet.</p>
<h3 id="heading-instance-variables">Instance variables</h3>
<p>Instance variables vary from object to object and are declared in the constructor.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Wall</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.height = <span class="hljs-number">10</span>

south_wall = Wall()
south_wall.height = <span class="hljs-number">20</span> <span class="hljs-comment"># only updates this instance of a wall</span>
print(south_wall.height)
<span class="hljs-comment"># prints "20"</span>

north_wall = Wall()
print(north_wall.height)
<span class="hljs-comment"># prints "10"</span>
</code></pre>
<h3 id="heading-class-variables">Class variables</h3>
<p>Class variables remain the same between instances of the same class and are declared at the top-level of a class.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Wall</span>():</span>
    height = <span class="hljs-number">10</span>

south_wall = Wall()
print(south_wall.height)
<span class="hljs-comment"># prints "10"</span>

Wall.height = <span class="hljs-number">20</span> <span class="hljs-comment"># updates all instances of a Wall</span>

print(south_wall.height)
<span class="hljs-comment"># prints "20"</span>
</code></pre>
<h3 id="heading-class-vs-instance-variables-which-should-i-use"><strong>Class vs instance variables – which should I use?</strong></h3>
<p>Generally speaking, <em>stay away from class variables</em>. Just like global variables, class variables are usually a bad idea because they make it hard to keep track of which parts of your program are making data updates. </p>
<p>However, it is important to understand how they work because you may see them out in the wild.</p>
<h1 id="heading-the-four-pillars-of-oop">The Four Pillars of OOP</h1>
<h2 id="heading-oop-pillar-1-encapsulation">OOP Pillar #1 – Encapsulation</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">Encapsulation</a> is one of the strongest tools in your tool belt as a software engineer. Like we covered in the beginning of this tutorial, writing code that machines understand is easy. But writing code that humans can understand is very difficult.</p>
<p>Encapsulation is the practice of hiding information inside of a "<a target="_blank" href="https://en.wikipedia.org/wiki/Black_box">black box</a>" so that other developers working with the code don't have to worry about it. </p>
<p>A basic example of encapsulation would be a function. The caller of a function doesn't need to worry too much about what happens inside – they just need to understand the inputs and outputs.</p>
<pre><code class="lang-python">pythonacceleration = calc_acceleration(initial_speed, final_speed, time)
</code></pre>
<p>In the example above, to use the <code>calc_acceleration</code> function, we don't really need to understand what goes on inside. That's the goal of encapsulation: it makes our lives easier as developers and helps us write cleaner code.</p>
<h3 id="heading-encapsulation-in-oop">Encapsulation in OOP</h3>
<p>In the context of object-oriented programming, we can practice good encapsulation by using private and public members. </p>
<p>The idea is that if we want the users of our class to interact with something directly, we make it <em>public</em>. If they don't need to use a certain method or property, we make that <em>private</em> in order to keep the usage instructions for our class simple.</p>
<h3 id="heading-encapsulation-in-python">Encapsulation in Python</h3>
<p>In order to enforce encapsulation in Python, developers prefix properties and classes that they intend to be private with a double underscore.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Wall</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, height</span>):</span>
        <span class="hljs-comment"># this stops us from accessing the __height</span>
        <span class="hljs-comment"># property directly on an instance of a Wall</span>
        self.__height = height

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_height</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.__height
</code></pre>
<p>In the example above, we don't want users of the <code>Wall</code> class to be able to change its height. We make the <code>__height</code> property private and expose a public <code>get_height</code> method so that users can still read the height of a wall without being tempted to update it. </p>
<p>This will stop developers from being able to do something like:</p>
<pre><code class="lang-python"><span class="hljs-comment"># front_wall is an instance of a Wall</span>
front_wall.__height = <span class="hljs-number">10</span> <span class="hljs-comment"># this results in an error</span>
</code></pre>
<h3 id="heading-encapsulation-does-not-make-systems-more-secure">Encapsulation does NOT make systems more secure</h3>
<p>Like we talked about earlier, encapsulation is the practice of hiding some code complexity inside a "<a target="_blank" href="https://en.wikipedia.org/wiki/Black_box">black box</a>" so that other developers working with the code don't have to worry about it. Adding encapsulation to our programs through "public" and "private" members makes our code easier to work with. It makes it "cleaner".</p>
<p>To be clear, encapsulation doesn't make the code more secure in the <a target="_blank" href="https://boot.dev/learn/learn-cryptography">cryptographic</a> or cyber-security sense of the word. That's a point I was personally confused about when I was first learning about private and public class members in school. </p>
<p>Things like <a target="_blank" href="https://blog.boot.dev/cryptography/how-sha-2-works-step-by-step-sha-256/">SHA-256</a> hashes, <a target="_blank" href="https://blog.boot.dev/cryptography/hmac-and-macs-in-jwts/">JWTs for authentication</a>, and <a target="_blank" href="https://blog.boot.dev/cryptography/aes-256-cipher-python-cryptography-examples/">ciphers</a> are a completely separate topic that have nothing to do with classes or encapsulation.</p>
<p>Encapsulation is a mechanism for making code easier to work with and less buggy. We stop <em>ourselves</em> from accessing private data because we've decided it doesn't make sense to be used outside from outside of the class.</p>
<h2 id="heading-oop-pillar-2-abstraction">OOP Pillar #2 – Abstraction</h2>
<p>Abstraction is one of the key concepts of object-oriented programming. The goal of abstraction is to handle complexity by hiding unnecessary details. </p>
<p>Abstraction and encapsulation typically go hand in hand, and if we aren't careful with our definitions, they can seem like the same thing.</p>
<h3 id="heading-abstraction-vs-encapsulation">Abstraction vs encapsulation</h3>
<p>While definitions are always changing, I like to think about abstraction and encapsulation in the following way.</p>
<ul>
<li>Abstraction is a technique that helps us identify what information and behavior should be encapsulated, and what should be exposed.</li>
<li>Encapsulation is the technique for organizing the code to encapsulate what should be hidden, and make visible what is intended to be visible.</li>
</ul>
<p>If you want a longer read on the topic, check out <a target="_blank" href="https://web.archive.org/web/20210513154547/https://www.tonymarston.net/php-mysql/abstraction.txt">this essay</a>.</p>
<h3 id="heading-so-are-we-encapsulating-or-abstracting-our-code-when-we-make-things-private">So are we <em>encapsulating</em> or <em>abstracting</em> our code when we make things private?</h3>
<p>Both. We are almost always doing both. The process of using the double underscore is a form of encapsulation. The process of <em>deciding</em> which data <em>deserves</em> to be hidden behind the double underscore is abstraction. </p>
<p>Let's look at a concrete example.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> random

my_random_number = random.randrange(<span class="hljs-number">5</span>)
</code></pre>
<p>In this example we're using the <code>random</code> library to generate a random number. As it turns out, <a target="_blank" href="https://blog.boot.dev/cryptography/what-is-entropy-in-cryptography/">generating random numbers</a> is a <em><em>really hard</em></em> problem. </p>
<p>The operating system actually uses the physical hardware state of the computer as an input to seed the randomness. </p>
<p>However, the developers of the <code>random</code> library have <em>abstracted</em> that complexity away and <em>encapsulated</em> a lot of that data and behavior so we don't need to worry about it. We just say "I want a random number less or equal to than 5" and the library takes care of it for us.</p>
<p>The decision to take a single number as input to the <code>randrange</code> function was a decision of abstraction. When writing production-level software, getting the abstractions right is crucial, because they are the hardest things to change later. </p>
<p>Think about the consequences of the <code>random</code> package maintainers changing the input parameters to the <code>randrange</code> function! It would break code all over the world.</p>
<h2 id="heading-how-oop-developers-think">How OOP Developers Think</h2>
<p>Methods can actually be private as well. In other words, we can encapsulate <em>behavior</em> as well as <em>data</em>.</p>
<h3 id="heading-grouping-data-and-behavior"><strong>Grouping data and behavior</strong></h3>
<p>Classes in object-oriented programming are all about grouping data and behavior together in one place: an object. </p>
<p>Object oriented programmers tend to think about programming as a modeling problem. They think, "how can I write a <code>Human</code> class that simulates the data and behavior of a real human?"</p>
<p>We aren't focusing on <a target="_blank" href="https://boot.dev/learn/learn-functional-programming">functional programming</a> in this course. But to provide some contrast, functional programmers tend to think of their code as inputs and outputs. "When a human performs an action, what are the inputs to that action, and how do the outputs affect my program state?"</p>
<h3 id="heading-both-paradigms-are-valuable"><strong>Both paradigms are valuable</strong></h3>
<p>While OOP isn't the only paradigm in programming, it's a tried and true one that is useful in a variety of circumstances. </p>
<p>In any event, if you personally have an understanding of multiple ways of thinking about code, you'll be a much better developer over all.</p>
<h2 id="heading-oop-pillar-3-inheritance">OOP Pillar #3 – Inheritance</h2>
<p>We've made it to the Holy-grail of object-oriented programming: <a target="_blank" href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">inheritance</a>. Inheritance is really the defining trait of object oriented languages. </p>
<p>Languages without classes like <a target="_blank" href="https://boot.dev/learn/learn-golang">Go</a>lang and <a target="_blank" href="https://www.freecodecamp.org/news/rust-in-replit/">Rust</a> provide encapsulation and abstraction features. In fact, almost <em>every</em> language does. Inheritance, on the other hand, tends to be unique to class-based languages like <a target="_blank" href="https://boot.dev/learn/learn-python">Python</a>, <a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-by-coding-7-games/">JavaScript</a>, <a target="_blank" href="https://www.freecodecamp.org/news/the-java-handbook/">Java</a>, and Ruby.</p>
<h3 id="heading-what-is-inheritance">What is inheritance?</h3>
<p>Inheritance allows one class (aka "the child class") to <em>inherit</em> the properties and methods of another class (aka "the parent class").</p>
<p>This powerful language feature helps us avoid writing a lot of the same code twice. It allows us to <a target="_blank" href="https://blog.boot.dev/clean-code/dry-code/">DRY (don't repeat yourself)</a> up our code.</p>
<h3 id="heading-inheritance-in-python-syntax">Inheritance in Python – Syntax</h3>
<p>In Python, one class can inherit from another using the following syntax:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-comment"># parent "Animal" class</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cow</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-comment"># child class "Cow" inherits "Animal"</span>
</code></pre>
<p>In order to use the constructor of the parent class, we can use Python's built in <code>super()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, num_legs</span>):</span>
        self.num_legs = num_legs

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cow</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># call the parent constructor to</span>
        <span class="hljs-comment"># give the cow some legs</span>
        super().__init__(<span class="hljs-number">4</span>)
</code></pre>
<h3 id="heading-when-should-i-use-inheritance">When should I use inheritance?</h3>
<p>Inheritance is a powerful tool, but it is a <em>really</em> bad idea to try to overuse it. You should only use inheritance when every instance of the child class can also be considered the same type as the parent class.</p>
<p>When a child class inherits from a parent, it inherits <em>everything</em>. If you only want to share <em>some</em> functionality, inheritance probably is not the best answer. In that case you would probably just want to share some functions, or maybe make a new parent class that both classes inherit from.</p>
<h3 id="heading-all-cats-are-animals-but-not-all-animals-are-cats">All cats are animals but not all animals are cats</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/LwZVCId.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-inheritance-hierarchy">Inheritance hierarchy</h3>
<p>There is no limit to how deeply we can nest an inheritance tree. For example, a <code>Cat</code> can inherit from <code>Animal</code> which inherits from <code>LivingThing</code>. </p>
<p>That said, we should always be careful that each time we inherit from a base class that the child is a <em><em>strict</em></em> subset of the parent. You should never think to yourself "my child class needs a couple of the parent's methods, but not these other ones" and still decide to inherit from that parent.</p>
<h3 id="heading-multiple-children">Multiple children</h3>
<p>So far we've worked with linear class inheritance. In reality, inheritance structures often form trees, not lines. A class can have as many direct child classes as the programmer wants.</p>
<p>You'll often find in production software that it's more likely that an inheritance tree is wide than deep. In other words, instead of a deep tree like:</p>
<p><code>Organism -&gt; Animal -&gt; Mammal -&gt; Feline -&gt; Cat</code></p>
<p>You will more often see a wide tree:</p>
<pre><code>Dragon -&gt; Drake
       -&gt; Wyvern
       -&gt; Hydra
       -&gt; Druk
</code></pre><h3 id="heading-why-are-inheritance-trees-often-wide-instead-of-deep">Why are <strong>inheritance</strong> trees often wide instead of deep?</h3>
<p>Like we talked about earlier, in good software a child class is a strict subset of its parent class. </p>
<p>In a deep tree, that means the children need to be perfect members of all the parent class "types". That simply doesn't happen very often in the real world. It's much more likely that you'll have a base class that simply has many sibling classes that are slightly different variations of the base.</p>
<pre><code>Vehicle -&gt; Truck
        -&gt; Car
        -&gt; Boat
        -&gt; Train
</code></pre><h2 id="heading-oop-pillar-4-polymorphism">OOP Pillar #4 – Polymorphism</h2>
<p>While inheritance is the most unique trait that object-oriented languages make claim to, polymorphism is probably the most powerful.</p>
<p>Polymorphism is the ability of a variable, function, or object to take on multiple forms. For example, in a programming language that supports inheritance, classes in the same hierarchical tree may have methods with the same name but <em>different</em> behaviors.</p>
<h3 id="heading-polymorphism-with-shapes">Polymorphism with shapes</h3>
<p>Let's look at a simple example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Creature</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">move</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"the creature moves"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dragon</span>(<span class="hljs-params">Creature</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">move</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"the dragon flies"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Kraken</span>(<span class="hljs-params">Creature</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">move</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"the kraken swims"</span>)

<span class="hljs-keyword">for</span> creature <span class="hljs-keyword">in</span> [Creature(), Dragon(), Kraken()]:
    creature.move()
<span class="hljs-comment"># prints:</span>
<span class="hljs-comment"># the creature moves</span>
<span class="hljs-comment"># the dragon flies</span>
<span class="hljs-comment"># the kraken swims</span>
</code></pre>
<p>In this example the child classes, <code>Dragon</code> and <code>Kraken</code> are <strong>overriding</strong> the behavior of their parent class's <code>move()</code> method.</p>
<h3 id="heading-polymorphisms-roots">Polymorphisms Roots</h3>
<p>Take a look at the Greek roots of "polymorphism".</p>
<ul>
<li>"poly" means "many"</li>
<li>"morph" means "to change" or "form"</li>
</ul>
<p>Polymorphism in programming is the ability to present the same interface (function or method signatures) for many different underlying forms (data types).</p>
<p>A classic example is a <code>Shape</code> class that <code>Rectangle</code>, <code>Circle</code>, and <code>Triangle</code> can inherit from. </p>
<p>With polymorphism, each of these classes will have different underlying data. The circle needs a center and radius. The rectangle needs two co-ordinates for the top left and bottom right corners. The triangle needs coordinates for the corners.</p>
<p>By making each class responsible for its data <strong>and</strong> its code, you can achieve polymorphism. </p>
<p>In this example, each class would have its own <code>Draw()</code> method. This allows the code that uses the different shapes to be simple and easy, and more importantly, it can treat shapes as the <strong>same</strong> even though they are <strong>different</strong>. It hides the complexities of the difference behind a clean abstraction.</p>
<pre><code class="lang-python">shapes = [Circle(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>), Rectangle(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>)]
<span class="hljs-keyword">for</span> shape <span class="hljs-keyword">in</span> shapes:
    print(shape.Draw())
</code></pre>
<p>This is in contrast to the functional way of doing things where you would have had separate functions that have <strong>different</strong> function signatures, like <code>draw_rectangle(x1, y1, x2, y2)</code> and <code>draw_circle(center, radius)</code>.</p>
<h3 id="heading-wait-what-is-a-function-signature">Wait, what is a "function signature"?</h3>
<p>A function signature includes the name, inputs, and outputs of a function or method. For example, these two classes have the same method signatures.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Human</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hit_by_fire</span>(<span class="hljs-params">self</span>):</span>
        self.health -= <span class="hljs-number">5</span>
        <span class="hljs-keyword">return</span> self.health

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Archer</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hit_by_fire</span>(<span class="hljs-params">self</span>):</span>
        self.health -= <span class="hljs-number">10</span>
        <span class="hljs-keyword">return</span> self.health
</code></pre>
<p>Both methods have the same name, take <code>0</code> inputs, and return integers. If <em>any</em> of those things are different, they would have different function signatures.</p>
<p>Here is an example of different signatures.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Human</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hit_by_fire</span>(<span class="hljs-params">self</span>):</span>
        self.health -= <span class="hljs-number">5</span>
        <span class="hljs-keyword">return</span> self.health

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Archer</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hit_by_fire</span>(<span class="hljs-params">self, dmg</span>):</span>
        self.health -= dmg
        <span class="hljs-keyword">return</span> self.health
</code></pre>
<h3 id="heading-when-overriding-methods-use-the-same-function-signature">When overriding methods, use the same function signature</h3>
<p>If you change the function signature of a parent class when overriding a method, it could be a disaster. </p>
<p>The whole point of overriding a method is so that the caller of your code <em>doesn't have to worry</em> about what different things are going on inside the methods of different object types.</p>
<h3 id="heading-operator-overloading">Operator overloading</h3>
<p>Another kind of built-in polymorphism in Python is the ability to override an operator in Python depending upon the operands used.</p>
<p>Arithmetic operators work for built-in types like integers and strings.</p>
<pre><code class="lang-python">print(<span class="hljs-number">3</span> + <span class="hljs-number">4</span>)
<span class="hljs-comment"># prints "7"</span>

print(<span class="hljs-string">"three "</span> + <span class="hljs-string">"four"</span>)
<span class="hljs-comment"># prints "three four"</span>
</code></pre>
<p>Custom classes, on the other hand, don't have any built-in support for those operators:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, x, y</span>):</span>
        self.x = x
        self.y = y


p1 = Point(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
p2 = Point(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
p3 = p1 + p2
<span class="hljs-comment"># TypeError: unsupported operand type(s) for +: 'Point' and 'Point'</span>
</code></pre>
<p>However, we can add our own support! The <code>__add__</code> method is used by the Python interpreter when instances of a class are being added with the <code>+</code> operator.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, x, y</span>):</span>
        self.x = x
        self.y = y

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__add__</span>(<span class="hljs-params">self, point</span>):</span>
        x = self.x + point.x
        y = self.y + point.y
        <span class="hljs-keyword">return</span> Point(x, y)

p1 = Point(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
p2 = Point(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
p3 = p1 + p2
<span class="hljs-comment"># p3 is (6, 8)</span>
</code></pre>
<p>When you call <code>p1 + p2</code> under the hood the interpreter just calls <code>p1.__add__(p2)</code>.</p>
<p>Here's a list of how the operators translate into method names. If you're not familiar with logical and bitwise operators in Python, you can check out <a target="_blank" href="https://www.youtube.com/watch?v=1rUzblmGHzk">this video</a>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Operator</td><td>Method</td></tr>
</thead>
<tbody>
<tr>
<td>Addition</td><td>+</td><td><strong>add</strong></td></tr>
<tr>
<td>Subtraction</td><td>-</td><td><strong>sub</strong></td></tr>
<tr>
<td>Multiplication</td><td>*</td><td><strong>mul</strong></td></tr>
<tr>
<td>Power</td><td>**</td><td><strong>pow</strong></td></tr>
<tr>
<td>Division</td><td>/</td><td><strong>truediv</strong></td></tr>
<tr>
<td>Floor Division</td><td>//</td><td><strong>floordiv</strong></td></tr>
<tr>
<td>Remainder (modulo)</td><td>%</td><td><strong>mod</strong></td></tr>
<tr>
<td>Bitwise Left Shift</td><td>&lt;&lt;</td><td><strong>lshift</strong></td></tr>
<tr>
<td>Bitwise Right Shift</td><td>&gt;&gt;</td><td><strong>rshift</strong></td></tr>
<tr>
<td>Bitwise AND</td><td>&amp;</td><td><strong>and</strong></td></tr>
<tr>
<td>Bitwise OR</td><td>\</td><td></td><td><strong>or</strong></td></tr>
<tr>
<td>Bitwise XOR</td><td>^</td><td><strong>xor</strong></td></tr>
<tr>
<td>Bitwise NOT</td><td>~</td><td><strong>invert</strong></td></tr>
</tbody>
</table>
</div><h3 id="heading-how-to-overload-built-in-methods">How to overload built-in methods</h3>
<p>Last but not least, let's take a look at some of the built-in methods we can overload in Python. While there isn't a default behavior for the arithmetic operators like we just saw, there <em>is</em> a default behavior for <strong>printing</strong> a class.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, x, y</span>):</span>
        self.x = x
        self.y = y


p1 = Point(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
print(p1)
<span class="hljs-comment"># prints "&lt;Point object at 0xa0acf8&gt;"</span>
</code></pre>
<p>That's not super useful! Let's teach instances of our <code>Point</code> object to print themselves. The <code>__repr__</code> method (short for "represent") lets us do just that. It takes no inputs but returns a string that will be printed to the console when someone passes an instance of the class to Python's <code>print()</code> function.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, x, y</span>):</span>
        self.x = x
        self.y = y

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"(<span class="hljs-subst">{self.x}</span>,<span class="hljs-subst">{self.y}</span>)"</span>

p1 = Point(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
print(p1)
<span class="hljs-comment"># prints "(4,5)"</span>
</code></pre>
<h2 id="heading-great-job-making-it-to-the-end">Great Job Making it to the End!</h2>
<p>Thanks for joining me in this written course about object oriented programming. </p>
<p>If you're interested in doing the live coding assignments and quizzes for this course you can do so on the <a target="_blank" href="https://boot.dev/learn/learn-object-oriented-programming">Learn OOP course</a> over on <a target="_blank" href="https://boot.dev/">Boot.dev</a>. </p>
<p>Alternatively, if you'd like to check out the next course in the <a target="_blank" href="https://boot.dev/tracks/computer-science">back-end developer career path</a> you can start the <a target="_blank" href="https://boot.dev/learn/learn-algorithms">Learn Algorithms</a> course here.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Architect a Full-Stack Application from Start to Finish ]]>
                </title>
                <description>
                    <![CDATA[ Software architecture is a massive topic. That said, I think I can give you a simple method you can use to approach the architecture of a full-stack application.  In particular, I want to talk about the order in which you should think about and build... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-full-stack-application-from-start-to-finish/</link>
                <guid isPermaLink="false">66b9e9e8a29acc044a5aff50</guid>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Applications ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Tue, 04 Oct 2022 17:49:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/jeremy-thomas-FO7bKvgETgQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Software architecture is a massive topic. That said, I think I can give you a simple method you can use to approach the architecture of a full-stack application. </p>
<p>In particular, I want to talk about the <em>order</em> in which you should think about and build out the pieces of a typical web application.</p>
<p>My advice is that <strong>for each feature</strong> you should:</p>
<ol>
<li>Design the front-end</li>
<li>Build the front-end</li>
<li>Build the persistence layer (back-end database and data models)</li>
<li>Build the API (back-end application)</li>
</ol>
<p><em>The best way is a front -&gt; back -&gt; middle approach.</em></p>
<h2 id="heading-why-start-with-the-front-end">Why Start with the Front-End?</h2>
<p>Assuming you're working with a good product team (or maybe you're a team of one so you <em>are</em> the product team) the most important thing is the end-user experience. As a result, it makes the most sense to start on the front-end. </p>
<p>Only by designing and building the front-end will you learn what kinds of requirements you'll have for the back-end of your application.</p>
<p>The user of front-end code is the customer. The user of back-end code is front-end code.</p>
<h2 id="heading-how-do-you-build-a-front-end-without-a-back-end-to-connect-to">How Do you Build a Front-End without a Back-End to Connect to?</h2>
<p>This is the beauty of starting with the front-end. Start by mocking up all of the data that fills in your UI. For example, instead of writing code like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(userUrl)
<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> resp.json()
</code></pre>
<p>You would simply write:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">username</span>: <span class="hljs-string">"bobbyjoe"</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">"bobbyjoe@example.com"</span>,
    <span class="hljs-attr">profilePictureUrl</span>: <span class="hljs-string">"https://fakewebsite.com/fakeimageurl.jpeg"</span>
}
</code></pre>
<p>Then you would write all the rest of the front-end code like you normally would. By the time you're done, you'll know <em>exactly</em> what kind of data you'll need your back-end to store and serve. </p>
<p>And by the time you do get around to building the back-end, you can just swap out those mock JSON objects for <code>fetch</code> requests.</p>
<h2 id="heading-create-the-data-model-and-database-schema">Create the Data Model and Database Schema</h2>
<p>Okay, so you've built out the front-end for your new feature, and you've mocked all the data that you've decided will need to be stored on the back-end. Now it's time to decide how you'll model that data inside your database.</p>
<p>I like to go straight from the front-end to the database. This is because the way you store data in the database is more important to get right than the way you serve the data from your API – well, at least if the consumer of your API is your own team (or you).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/well.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Obi Wan writing APIs for himself</em></p>
<p><a target="_blank" href="https://wagslane.dev/posts/keep-your-data-raw-at-rest/">Changing database schemas is <em>hard</em></a>. It's much easier to slap a <code>/v2</code> endpoint on your back-end than to rewrite your persistence layer. </p>
<p>For that reason, thinking about how you're going to store your data, and giving priority to that design, will generally lead to less headache down the road.</p>
<p>Typically, once you have the front-end built you have all the information you need to design a solid database schema.</p>
<p>For example, maybe you know you need:</p>
<ul>
<li>To store users, each with an email and profile picture</li>
<li>To allow users to join, create, and leave organizations</li>
</ul>
<p>With that in mind, and assuming you're using a relational SQL database like Postgres, you can probably start with something like:</p>
<ul>
<li>A <code>users</code> table with <code>id</code>, <code>created_at</code>, <code>email</code>, and  <code>profile_picture_url</code> fields</li>
<li>A <code>organizations</code> table with <code>id</code>, <code>created_at</code>, and <code>name</code> fields</li>
<li>A <code>users_organizations</code> table with <code>id</code>, <code>user_id</code>, <code>organization_id</code>, and <code>role</code> fields</li>
</ul>
<p>Users go in the <code>users</code> table, organizations go in the <code>organizations</code> table, and the <code>users_organizations</code> table is a joining table to keep track of which users are a part of which organizations and what their role is. For example, they might be an <code>admin</code> or a <code>member</code>. </p>
<p>If you're unfamiliar with all this SQL terminology, you can check out my <a target="_blank" href="https://boot.dev/learn/learn-sql">Learn SQL course</a> on <a target="_blank" href="https://boot.dev/">Boot.dev</a>.</p>
<h2 id="heading-lastly-build-the-back-end-application">Lastly, Build the Back-end Application</h2>
<p>Now that you know which data your front-end needs, and how you can best model it in your database, you final task is to glue it all together with a back-end API. </p>
<p>Start with the simplest API you can.</p>
<p>Don't build complex joining capabilities to start. Don't build crazy pagination or filtering features if you don't need them. You can always add new endpoints and parameters later in order to fulfill performance needs as they arise. I'm a big fan of <a target="_blank" href="https://wagslane.dev/posts/optimize-for-simplicit-first/">optimizing for simplicity first</a>.</p>
<p>Anyhow, that's not to say you won't need anything more complex than a few CRUD endpoints – you might. If you do, at least you have all the information in front of you in order to make a well-informed decision. </p>
<p>Don't build more than what the front-end requires, and try to use the simple data models you created in the database.</p>
<p>With all that in mind, expect to go back and forth on a few things. Don't feel bad if you missed a feature on the front-end and need to go back and add it. Or maybe you overlooked how slow a certain view in your app would load if you store the data in a certain way in your database. This can be an iterative process, and it should be.</p>
<h2 id="heading-one-final-note-dont-do-waterfall">One Final Note: Don't Do Waterfall</h2>
<p>I want to double stress the fact that you should be doing this on a <em>per-feature</em> basis. I'm not advocating that you plan an entire application up front. You should still be practicing iterative product development.</p>
<p>Good luck, and if you need help learning back-end development feel free to check out what I'm building over on <a target="_blank" href="https://boot.dev/">Boot.dev</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ From WordPress to Hugo – How I Migrated a 250+ Page Site and the Scripts I Used ]]>
                </title>
                <description>
                    <![CDATA[ I recently decided to switch Boot.dev's blog from WordPress to a static site generator. I decided on Hugo, partly because I’m a huge fan of the Go programming language, but also because it just seemed like the best option from a dev-experience perspe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/wordpress-to-hugo-scripts/</link>
                <guid isPermaLink="false">66b9e9f3fbdfcf519c5e1a68</guid>
                
                    <category>
                        <![CDATA[ Hugo ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Static Site Generators ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WordPress ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Tue, 30 Aug 2022 23:25:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/1__D5sbQUd4XwTy9yt67BCCA-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I recently decided to switch <a target="_blank" href="https://boot.dev">Boot.dev's</a> blog from WordPress to a static site generator.</p>
<p>I decided on <a target="_blank" href="https://gohugo.io/">Hugo</a>, partly because I’m a huge fan of the Go programming language, but also because it just seemed like the best option from a dev-experience perspective. </p>
<p>Here’s why I decided to move away from WordPress:</p>
<ul>
<li>I wanted to write and store all my posts in Markdown.</li>
<li>I wanted to version control all my posts in Git/Github.</li>
<li>I wanted to be able to use ctrl+shift+f to find and edit the content on my blog.</li>
<li>I wanted a less buggy way to do “global blocks”</li>
<li>I didn’t want to spend hours fine-tuning performance. My posts are just text and images, so page speed scores should be 100 by default!</li>
<li>I wanted to use straight CSS for styling, making it easier for my blog and app to have identical styling.</li>
<li>I wanted to host the site for free</li>
</ul>
<p>With all those goals in mind, Hugo was a perfect choice. I’ve been super happy since making the switch, but there were some hiccups along the way. </p>
<p>WordPress takes care of some of the nuances of SEO-tuning for you, and if you forget to redo them yourself, you’ll end up sacrificing rankings.</p>
<h2 id="heading-how-to-export-wordpress-posts-as-markdown">How to Export WordPress Posts as Markdown</h2>
<p>Manually copying and pasting all of your posts out of the WordPress GUI into Markdown files could take a <em>very</em> long time. Especially if you have hundreds of posts like I do. </p>
<p>In order to speed up the process, I used <a target="_blank" href="https://wordpress.org/plugins/wp-gatsby-markdown-exporter/">this Markdown plugin</a> to export all of my posts as markdown at once. It’s called “Gatsby Markdown Exporter”, but it works for Hugo just as well.</p>
<p>I’m not going to go over the basics of getting up and running with Hugo, as I’m going to assume you are already familiar with it. But if you’re not, you can read the <a target="_blank" href="https://gohugo.io/getting-started/quick-start/">quick start guide here</a>.</p>
<h2 id="heading-how-to-use-hugos-built-in-seo-templates">How to Use Hugo’s Built-in SEO Templates</h2>
<p>WordPress and its various SEO plugins take care of a lot of SEO-related hocus-pocus for you. So when you move to a static site generator you often have to do some of that stuff yourself.</p>
<p>As it turns out, Hugo has some turn-key solutions for most of this, so using the right <a target="_blank" href="https://gohugo.io/templates/internal/">internal templates</a> can get you all the open-graph, schema, and Twitter meta tags out of the box.</p>
<p>For me, that meant simply adding these 3 lines to my <code>layouts/partials/header.html</code> file within the <code>&lt;head&gt;</code> tag:</p>
<pre><code class="lang-html">{{ template "_internal/opengraph.html" . }}
{{ template "_internal/twitter_cards.html" . }}
{{ template "_internal/schema.html" . }}
</code></pre>
<p>Now we'll get into the scripts I wrote to help me with this process.</p>
<h2 id="heading-script-1-checking-for-broken-links">Script 1 — Checking for Broken Links</h2>
<p>You can solve a lot of your WordPress woes by installing plugins for various tasks. Well, assuming those plugins don’t break your entire WP installation.</p>
<p>With Hugo, I just write little text-manipulation or HTTP scripts to do my bidding.</p>
<p>This first script is just a simple iterator that crawls the site and reports any broken links. You can see the <a target="_blank" href="https://github.com/bootdotdev/blog/blob/main/scripts/linkcheck/main.go">full source code here</a>. It's small edit of the script the Go team uses to check for broken links on the Go programming language's website.</p>
<h2 id="heading-script-2-minifying-images">Script 2 — Minifying Images</h2>
<p>When working with WordPress, you would typically upload a blog post image, and some SEO plugin would optimize that image’s size for you. </p>
<p>In Hugo, no such optimizations are made for you. It simply serves the exact image you add to your “static” folder.</p>
<p>I wrote a little script to optimize my images. It does the following:</p>
<ul>
<li>Takes an input image of nearly any type (.png, .jpeg, .gif, etc).</li>
<li>Converts it to the <code>.webp</code> format (a performant format).</li>
<li>Shrinks the image to a max image size I've configured if it’s too large.</li>
</ul>
<p>This script is written in Node.js and <a target="_blank" href="https://github.com/bootdotdev/blog/blob/main/scripts/image-min.js">the source code can be found here</a>.</p>
<h2 id="heading-script-3-managing-global-shortcodes">Script 3 — Managing Global Shortcodes</h2>
<p>WordPress had a feature called “global blocks”. They're super useful for things like newsletter signup boxes that show up in the middle of your articles, but that you want to be able to update in a single place. </p>
<p>In Hugo, you can use <a target="_blank" href="https://gohugo.io/content-management/shortcodes/">shortcodes</a> to achieve a similar purpose.</p>
<p>Unfortunately, it’s the inserting and removing of the shortcodes <em>themselves</em> that actually becomes tedious at scale. </p>
<p>For example, let’s say I added my newsletter signup shortcode after the 5th paragraph in all my articles, but now I want it to come after the 7th paragraph. I have to go manually copy/paste the short code!</p>
<p>Well, not anymore. Again, this is the great thing about storing all your blog posts in a text format — we can script some simple solutions. I wrote two scripts, and their source code can be found here:</p>
<ul>
<li><a target="_blank" href="https://github.com/bootdotdev/blog/blob/main/scripts/rmshorts/main.go">rmshorts</a></li>
<li><a target="_blank" href="https://github.com/bootdotdev/blog/blob/main/scripts/addshorts/main.go">addshorts</a></li>
</ul>
<p>These two scripts allow me move my global blocks with ease. For example, to remove all instances of <code>myshortcode</code> from the blog:</p>
<pre><code class="lang-bash">rmshorts myshortcode
</code></pre>
<p>Then to add <code>myshortcode</code> as its own paragraph after the 2nd section of every blog post across the site:</p>
<pre><code class="lang-bash">addshorts myshortcode 2
</code></pre>
<p>This has been a huge time saver.</p>
<h2 id="heading-script-4-converting-docx-to-markdown">Script 4 — Converting .docx to Markdown</h2>
<p>Last but not least, I work with some non-technical writers. My writers aren’t used to writing Markdown. Google docs is their tool of choice. </p>
<p>I have no problem with that, as I want them to be effective. My solution was to write a <a target="_blank" href="https://github.com/bootdotdev/blog/blob/main/scripts/docxmd.sh">little bash script</a> that uses <a target="_blank" href="https://pandoc.org/">pandoc</a> under the hood to convert the Google Docs to Markdown files.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>I hope some of these scripts are valuable to you, and I really can’t recommend enough making the switch to a static site generator. If you’re willing to put in a few hours to get a great working environment up and running for your blog it will save you a lot of time and money in the long run.</p>
<p>Remember, always automate the boring stuff!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
