<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ariel Orozco]]></title><description><![CDATA[I'm a passionate Software Engineer that enjoys designing and implementing applications that leverage Cloud Services, Distributed Systems and Microservices.]]></description><link>https://arielorozco.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1621826461770/o8Stx5j3X.png</url><title>Ariel Orozco</title><link>https://arielorozco.com</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 18 May 2026 05:49:24 GMT</lastBuildDate><atom:link href="https://arielorozco.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Best Practices for Writing Clean and Efficient Go Code]]></title><description><![CDATA[The Go programming language, or Golang, is well-known for its simplicity, performance, and support for concurrency. However, like any language, writing efficient, maintainable, and readable code in Go requires adherence to certain best practices. Her...]]></description><link>https://arielorozco.com/best-practices-for-writing-clean-and-efficient-go-code</link><guid isPermaLink="true">https://arielorozco.com/best-practices-for-writing-clean-and-efficient-go-code</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[clean code]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Mon, 11 Nov 2024 02:52:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731293483256/05653213-74ac-422c-b169-aa3b71067c1b.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Go programming language, or Golang, is well-known for its simplicity, performance, and support for concurrency. However, like any language, writing efficient, maintainable, and readable code in Go requires adherence to certain best practices. Here are some conventions and tips to keep in mind when coding in Go.</p>
<h2 id="heading-1-follow-go-naming-conventions">1. Follow Go Naming Conventions</h2>
<p>Naming is crucial for code readability. Here are a few Go naming conventions to remember:</p>
<ul>
<li><p><strong>Use camelCase</strong> for variable and function names (<code>myVariable</code>, <code>processData</code>).</p>
</li>
<li><p><strong>Use PascalCase</strong> for exported names (names accessible from other packages), such as <code>CalculateTotal</code>.</p>
</li>
<li><p><strong>Avoid underscores</strong> in names; Go's convention favors simplicity and clean names.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">calculateTax</span><span class="hljs-params">(income <span class="hljs-keyword">float64</span>)</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> income * <span class="hljs-number">0.15</span>
}
</code></pre>
<h2 id="heading-2-keep-functions-short-and-focused">2. Keep Functions Short and Focused</h2>
<p>Functions in Go should ideally perform a single task, promoting code modularity and reusability. A function that does too much is harder to test, debug, and understand.</p>
<h3 id="heading-example">Example</h3>
<p>Instead of writing a large, multi-purpose function, try breaking it down:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetchUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(User, error)</span></span> {
    <span class="hljs-comment">// code to fetch user by id</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processUser</span><span class="hljs-params">(user User)</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-comment">// code to process user data</span>
}
</code></pre>
<h2 id="heading-3-handle-errors-explicitly">3. Handle Errors Explicitly</h2>
<p>Go promotes error handling over exceptions, encouraging developers to check for errors explicitly. Avoid silently ignoring errors; handle them gracefully or log them.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> err := processUser(user); err != <span class="hljs-literal">nil</span> {
    log.Printf(<span class="hljs-string">"Error processing user: %v"</span>, err)
    <span class="hljs-keyword">return</span> err
}
</code></pre>
<h2 id="heading-4-use-gos-standard-library">4. Use Go’s Standard Library</h2>
<p>The Go standard library offers many tools to simplify code development without extra dependencies. Libraries for handling strings, files, networking, and concurrency are mature and efficient.</p>
<p>Example: Use the <code>net/http</code> package for HTTP requests instead of external libraries unless there’s a specific need.</p>
<h2 id="heading-5-avoid-global-variables">5. Avoid Global Variables</h2>
<p>Global variables can create unpredictable side effects, particularly in concurrent Go programs. Instead, encapsulate variables within functions or structs.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span> {
    db *sql.DB
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *UserService)</span> <span class="hljs-title">FindUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(User, error)</span></span> {
    <span class="hljs-comment">// database operation here</span>
}
</code></pre>
<h2 id="heading-6-use-context-for-cancellation-and-deadlines">6. Use Context for Cancellation and Deadlines</h2>
<p>For functions that involve I/O or might take a while, use the <code>context</code> package to support timeouts or cancellation, which is especially useful for HTTP and database operations.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetchData</span><span class="hljs-params">(ctx context.Context)</span> <span class="hljs-title">error</span></span> {
    req, err := http.NewRequestWithContext(ctx, <span class="hljs-string">"GET"</span>, <span class="hljs-string">"http://example.com"</span>, <span class="hljs-literal">nil</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }
    <span class="hljs-comment">// Perform request</span>
}
</code></pre>
<h2 id="heading-7-keep-imports-organized">7. Keep Imports Organized</h2>
<p>Organize imports into three sections:</p>
<ol>
<li><p>Standard libraries</p>
</li>
<li><p>Third-party libraries</p>
</li>
<li><p>Local packages</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"net/http"</span>
    <span class="hljs-string">"github.com/some/package"</span>
    <span class="hljs-string">"myproject/mypackage"</span>
)
</code></pre>
<h2 id="heading-8-write-unit-tests">8. Write Unit Tests</h2>
<p>Testing is essential in Go. Use table-driven tests, which are popular in Go due to their ability to cover multiple scenarios with concise code.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestAdd</span><span class="hljs-params">(t *testing.T)</span></span> {
    tests := []<span class="hljs-keyword">struct</span> {
        input1, input2, expected <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">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>},
        {<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
    }
    <span class="hljs-keyword">for</span> _, test := <span class="hljs-keyword">range</span> tests {
        result := Add(test.input1, test.input2)
        <span class="hljs-keyword">if</span> result != test.expected {
            t.Errorf(<span class="hljs-string">"Expected %d but got %d"</span>, test.expected, result)
        }
    }
}
</code></pre>
<h2 id="heading-9-use-go-routines-wisely">9. Use Go Routines Wisely</h2>
<p>Go routines provide lightweight concurrency, but overuse can lead to memory leaks. Use them only when necessary, and always clean up resources to avoid potential issues.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processInBackground</span><span class="hljs-params">(ctx context.Context, jobs &lt;-<span class="hljs-keyword">chan</span> Job)</span></span> {
    <span class="hljs-keyword">for</span> {
        <span class="hljs-keyword">select</span> {
        <span class="hljs-keyword">case</span> job := &lt;-jobs:
            <span class="hljs-keyword">go</span> handleJob(job)
        <span class="hljs-keyword">case</span> &lt;-ctx.Done():
            <span class="hljs-keyword">return</span>
        }
    }
}
</code></pre>
<hr />
<p>Following these best practices will help you write Go code that is clean, efficient, and maintainable, making your projects easier to scale and debug in the long run. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Testing in Golang]]></title><description><![CDATA[Testing is a crucial part of software development, ensuring that your code works as expected and reducing the number of bugs and issues. In Go, testing is built into the language, making it straightforward to write tests. This blog post will provide ...]]></description><link>https://arielorozco.com/testing-in-golang</link><guid isPermaLink="true">https://arielorozco.com/testing-in-golang</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Mon, 15 Jul 2024 17:21:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721064056925/707b2649-eb86-499b-8a96-658848f08c67.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Testing is a crucial part of software development, ensuring that your code works as expected and reducing the number of bugs and issues. In Go, testing is built into the language, making it straightforward to write tests. This blog post will provide a comprehensive guide on testing in Go, covering unit tests, integration tests, table-driven tests, mocking, using testing libraries like Testify, and setting up continuous integration (CI) for Go projects.</p>
<h2 id="heading-introduction-to-testing-in-go">Introduction to Testing in Go</h2>
<p>Go comes with a built-in testing package, <code>testing</code>, which provides tools to write and run tests. By convention, test files are placed in the same package as the code they test, with filenames ending in <code>_test.go</code>. Functions that serve as tests are prefixed with <code>Test</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestHelloWorld</span><span class="hljs-params">(t *testing.T)</span></span> {
    t.Log(<span class="hljs-string">"Hello, world"</span>)
}
</code></pre>
<p>Running tests is simple: use the <code>go test</code> command.</p>
<h2 id="heading-unit-tests">Unit Tests</h2>
<p>Unit tests focus on testing individual components or functions in isolation. Here’s an example of a unit test for a simple function:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> math

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Add</span><span class="hljs-params">(a, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> a + b
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestAdd</span><span class="hljs-params">(t *testing.T)</span></span> {
    result := Add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
    <span class="hljs-keyword">if</span> result != <span class="hljs-number">5</span> {
        t.Errorf(<span class="hljs-string">"Add(2, 3) = %d; want 5"</span>, result)
    }
}
</code></pre>
<p>In this example, the <code>Add</code> function is tested to ensure it returns the correct result.</p>
<h2 id="heading-table-driven-tests">Table-Driven Tests</h2>
<p>Table-driven tests allow you to test multiple scenarios with the same code, making your tests more concise and easier to manage. Here’s how to implement table-driven tests:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> math

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestAdd</span><span class="hljs-params">(t *testing.T)</span></span> {
    tests := []<span class="hljs-keyword">struct</span> {
        a, b, expected <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">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>},
        {<span class="hljs-number">10</span>, <span class="hljs-number">-5</span>, <span class="hljs-number">5</span>},
    }

    <span class="hljs-keyword">for</span> _, tt := <span class="hljs-keyword">range</span> tests {
        result := Add(tt.a, tt.b)
        <span class="hljs-keyword">if</span> result != tt.expected {
            t.Errorf(<span class="hljs-string">"Add(%d, %d) = %d; want %d"</span>, tt.a, tt.b, result, tt.expected)
        }
    }
}
</code></pre>
<p>This approach allows you to add new test cases easily by simply adding new entries to the test table.</p>
<h2 id="heading-mocking">Mocking</h2>
<p>Mocking is essential for testing functions that depend on external systems or complex interactions. Go doesn’t have a built-in mocking library, but you can create your own mocks or use third-party libraries. Here’s an example using a simple manual mock:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> user

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

<span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">interface</span> {
    GetUser(id <span class="hljs-keyword">string</span>) (User, error)
}

<span class="hljs-keyword">type</span> MockUserService <span class="hljs-keyword">struct</span> {
    mockGetUser <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(id <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(User, error)</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(m *MockUserService)</span> <span class="hljs-title">GetUser</span><span class="hljs-params">(id <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(User, error)</span></span> {
    <span class="hljs-keyword">return</span> m.mockGetUser(id)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestGetUser</span><span class="hljs-params">(t *testing.T)</span></span> {
    mockService := &amp;MockUserService{
        mockGetUser: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(id <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(User, error)</span></span> {
            <span class="hljs-keyword">return</span> User{ID: id, Name: <span class="hljs-string">"John Doe"</span>}, <span class="hljs-literal">nil</span>
        },
    }

    user, err := mockService.GetUser(<span class="hljs-string">"123"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> || user.ID != <span class="hljs-string">"123"</span> {
        t.Errorf(<span class="hljs-string">"expected user with ID 123, got %v, %v"</span>, user, err)
    }
}
</code></pre>
<h2 id="heading-using-testing-libraries-testify">Using Testing Libraries: Testify</h2>
<p>Testify is a popular testing library for Go that provides a more expressive way to write tests. It includes assertions and mock capabilities.</p>
<h3 id="heading-installing-testify">Installing Testify</h3>
<pre><code class="lang-plaintext">go get github.com/stretchr/testify
</code></pre>
<h3 id="heading-using-testify">Using Testify</h3>
<p>Here’s how to rewrite the <code>Add</code> function test using Testify:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> math

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"testing"</span>
    <span class="hljs-string">"github.com/stretchr/testify/assert"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestAdd</span><span class="hljs-params">(t *testing.T)</span></span> {
    assert := assert.New(t)
    assert.Equal(<span class="hljs-number">5</span>, Add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>), <span class="hljs-string">"they should be equal"</span>)
}
</code></pre>
<p>Testify’s assertions provide a clear and concise way to write tests, making them easier to read and maintain.</p>
<h2 id="heading-setting-up-continuous-integration">Setting Up Continuous Integration</h2>
<p>Continuous Integration (CI) ensures that your tests are run automatically whenever you push changes to your repository. Here’s how to set up CI for a Go project using GitHub Actions.</p>
<h3 id="heading-github-actions-configuration">GitHub Actions Configuration</h3>
<p>Create a <code>.github/workflows/ci.yml</code> file in your repository with the following content:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">Go</span>

<span class="hljs-attr">on:</span>
  <span class="hljs-attr">push:</span>
    <span class="hljs-attr">branches:</span> [ <span class="hljs-string">main</span> ]
  <span class="hljs-attr">pull_request:</span>
    <span class="hljs-attr">branches:</span> [ <span class="hljs-string">main</span> ]

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">build:</span>

    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

    <span class="hljs-attr">steps:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">code</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Set</span> <span class="hljs-string">up</span> <span class="hljs-string">Go</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-go@v2</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-attr">go-version:</span> <span class="hljs-number">1.16</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">dependencies</span>
      <span class="hljs-attr">run:</span> <span class="hljs-string">go</span> <span class="hljs-string">mod</span> <span class="hljs-string">tidy</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Run</span> <span class="hljs-string">tests</span>
      <span class="hljs-attr">run:</span> <span class="hljs-string">go</span> <span class="hljs-string">test</span> <span class="hljs-string">./...</span>
</code></pre>
<p>This configuration will run your tests every time you push changes to the <code>main</code> branch or create a pull request targeting the <code>main</code> branch.</p>
<p>Testing in Go is powerful and flexible, enabling you to write comprehensive tests from unit tests to integration tests. Using table-driven tests and mocking can make your tests more robust and maintainable. Libraries like Testify can further enhance your testing experience. Finally, setting up continuous integration ensures that your tests are always run, helping you catch issues early.</p>
<p>By following these practices, you can ensure that your Go projects are reliable, maintainable, and ready for production.</p>
]]></content:encoded></item><item><title><![CDATA[Optimizing Performance in Go Applications]]></title><description><![CDATA[Go, often celebrated for its simplicity and efficiency, is a language designed with performance in mind. However, like any other language, writing performant Go applications requires understanding its nuances and leveraging the right tools and techni...]]></description><link>https://arielorozco.com/optimizing-performance-in-go-applications</link><guid isPermaLink="true">https://arielorozco.com/optimizing-performance-in-go-applications</guid><category><![CDATA[golang]]></category><category><![CDATA[metrics]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Sun, 07 Jul 2024 01:37:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/w7ZyuGYNpRQ/upload/fec87798109dd5628e113edc3829aa76.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Go, often celebrated for its simplicity and efficiency, is a language designed with performance in mind. However, like any other language, writing performant Go applications requires understanding its nuances and leveraging the right tools and techniques. This blog post will guide you through various tips and techniques for optimizing the performance of your Go applications, covering profiling, benchmarking, and common performance bottlenecks.</p>
<h4 id="heading-understanding-performance-in-go">Understanding Performance in Go</h4>
<p>Performance optimization in Go involves a deep understanding of how Go manages memory, handles concurrency, and executes code. Before diving into specific techniques, it’s essential to identify performance goals and understand the baseline performance of your application.</p>
<h4 id="heading-profiling-go-applications">Profiling Go Applications</h4>
<p>Profiling is the process of measuring an application's performance to identify bottlenecks and areas for improvement. Go provides robust built-in tools for profiling.</p>
<ol>
<li><p><strong>Using</strong> <code>pprof</code> for Profiling: The <code>net/http/pprof</code> package offers easy profiling for HTTP servers. You can integrate it into your application to gather various performance metrics.</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> (
     <span class="hljs-string">"net/http"</span>
     _ <span class="hljs-string">"net/http/pprof"</span>
 )

 <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">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
         log.Println(http.ListenAndServe(<span class="hljs-string">"localhost:6060"</span>, <span class="hljs-literal">nil</span>))
     }()
     <span class="hljs-comment">// Your application code here</span>
 }
</code></pre>
</li>
<li><p><strong>CPU Profiling</strong>: CPU profiling helps identify which functions consume the most CPU time. You can start CPU profiling by adding the following code:</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> (
     <span class="hljs-string">"os"</span>
     <span class="hljs-string">"runtime/pprof"</span>
 )

 <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
     f, err := os.Create(<span class="hljs-string">"cpu.prof"</span>)
     <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
         log.Fatal(err)
     }
     pprof.StartCPUProfile(f)
     <span class="hljs-keyword">defer</span> pprof.StopCPUProfile()
     <span class="hljs-comment">// Your application code here</span>
 }
</code></pre>
</li>
<li><p><strong>Memory Profiling</strong>: Memory profiling helps you understand your application's memory usage and find memory leaks. Use the following code to start memory profiling:</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> (
     <span class="hljs-string">"os"</span>
     <span class="hljs-string">"runtime/pprof"</span>
 )

 <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-comment">// Your application code here</span>

     f, err := os.Create(<span class="hljs-string">"mem.prof"</span>)
     <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
         log.Fatal(err)
     }
     pprof.WriteHeapProfile(f)
     f.Close()
 }
</code></pre>
</li>
</ol>
<h4 id="heading-benchmarking-go-code">Benchmarking Go Code</h4>
<p>Benchmarking allows you to measure the performance of specific functions or code blocks. The <code>testing</code> package in Go provides support for writing benchmarks.</p>
<ol>
<li><p><strong>Writing Benchmarks</strong>: Create a file ending with <code>_test.go</code> and write benchmark functions. Each benchmark function should start with <code>Benchmark</code> and accept a <code>*testing.B</code> parameter.</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> <span class="hljs-string">"testing"</span>

 <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkExample</span><span class="hljs-params">(b *testing.B)</span></span> {
     <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ {
         <span class="hljs-comment">// Code you want to benchmark</span>
     }
 }
</code></pre>
</li>
<li><p><strong>Running Benchmarks</strong>: Use the <code>go test</code> command with the <code>-bench</code> flag to run benchmarks.</p>
<pre><code class="lang-sh"> go <span class="hljs-built_in">test</span> -bench=.
</code></pre>
</li>
</ol>
<h4 id="heading-common-performance-bottlenecks">Common Performance Bottlenecks</h4>
<p>Identifying common performance bottlenecks can save you significant time during optimization. Here are some typical areas where Go applications might suffer:</p>
<ol>
<li><p><strong>Garbage Collection (GC)</strong>: Go's garbage collector can impact performance, especially in applications with high memory allocation and deallocation rates. Minimize allocations by reusing objects and using pools.</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> <span class="hljs-string">"sync"</span>

 <span class="hljs-keyword">var</span> pool = sync.Pool{
     New: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">interface</span></span>{} { <span class="hljs-keyword">return</span> <span class="hljs-built_in">new</span>(MyStruct) },
 }

 <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">GetFromPool</span><span class="hljs-params">()</span> *<span class="hljs-title">MyStruct</span></span> {
     <span class="hljs-keyword">return</span> pool.Get().(*MyStruct)
 }

 <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">PutToPool</span><span class="hljs-params">(s *MyStruct)</span></span> {
     pool.Put(s)
 }
</code></pre>
</li>
<li><p><strong>Inefficient Concurrency</strong>: Go's concurrency model is powerful, but misuse can lead to performance issues. Avoid excessive goroutines and ensure proper synchronization.</p>
<pre><code class="lang-go"> <span class="hljs-keyword">var</span> wg sync.WaitGroup
 <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
     wg.Add(<span class="hljs-number">1</span>)
     <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-keyword">int</span>)</span></span> {
         <span class="hljs-keyword">defer</span> wg.Done()
         <span class="hljs-comment">// Your concurrent code here</span>
     }(i)
 }
 wg.Wait()
</code></pre>
</li>
<li><p><strong>Suboptimal I/O Operations</strong>: I/O operations, especially involving files and networks, can be slow. Use buffered I/O to improve performance.</p>
<pre><code class="lang-go"> <span class="hljs-keyword">import</span> (
     <span class="hljs-string">"bufio"</span>
     <span class="hljs-string">"os"</span>
 )

 <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readFile</span><span class="hljs-params">(filePath <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">([]<span class="hljs-keyword">string</span>, error)</span></span> {
     file, err := os.Open(filePath)
     <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
         <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, err
     }
     <span class="hljs-keyword">defer</span> file.Close()

     <span class="hljs-keyword">var</span> lines []<span class="hljs-keyword">string</span>
     scanner := bufio.NewScanner(file)
     <span class="hljs-keyword">for</span> scanner.Scan() {
         lines = <span class="hljs-built_in">append</span>(lines, scanner.Text())
     }
     <span class="hljs-keyword">return</span> lines, scanner.Err()
 }
</code></pre>
</li>
<li><p><strong>Inefficient Data Structures</strong>: Choosing the right data structure is crucial for performance. Use slices and maps appropriately, and avoid unnecessary data copying.</p>
<pre><code class="lang-go"> <span class="hljs-comment">// Use slices for dynamic arrays</span>
 <span class="hljs-keyword">var</span> data []<span class="hljs-keyword">int</span>
 data = <span class="hljs-built_in">append</span>(data, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)

 <span class="hljs-comment">// Use maps for fast lookups</span>
 dict := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"foo"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"bar"</span>: <span class="hljs-number">2</span>}
</code></pre>
</li>
</ol>
<p>Optimizing the performance of Go applications requires a combination of profiling, benchmarking, and addressing common bottlenecks. By understanding and applying these techniques, you can significantly improve the efficiency and responsiveness of your applications. Remember that optimization is an ongoing process, and continually monitoring and refining your code will yield the best results.</p>
<p>With the right tools and practices, you can harness the full potential of Go to build high-performance applications that meet your users' demands. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in Go: Best Practices and Patterns]]></title><description><![CDATA[Error handling is a critical aspect of writing robust and reliable software applications. In Go, error handling is designed to be explicit, making it easier to identify and address potential issues. In this blog post, we'll explore the best practices...]]></description><link>https://arielorozco.com/error-handling-in-go-best-practices-and-patterns</link><guid isPermaLink="true">https://arielorozco.com/error-handling-in-go-best-practices-and-patterns</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[error handling]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Thu, 29 Feb 2024 03:47:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709178376101/b59cd534-bd15-412d-9add-4f220c409304.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Error handling is a critical aspect of writing robust and reliable software applications. In Go, error handling is designed to be explicit, making it easier to identify and address potential issues. In this blog post, we'll explore the best practices and patterns for handling errors in Go, covering error types, handling panics, and strategies for writing clean and effective error-handling code.</p>
<h3 id="heading-understanding-errors-in-go">Understanding Errors in Go</h3>
<p>In Go, errors are represented by the <code>error</code> interface, which is defined as follows:</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>This interface has a single method, <code>Error()</code>, which returns a string describing the error. Any type that implements this method can be used as an error in Go.</p>
<p>Errors in Go are typically handled using the <code>if err != nil</code> pattern. For example:</p>
<pre><code class="lang-go">result, err := someFunction()
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    <span class="hljs-comment">// Handle the error</span>
    log.Fatal(err)
}
<span class="hljs-comment">// Continue with the rest of the code</span>
</code></pre>
<p>This pattern ensures that errors are checked and handled explicitly, making the code more readable and maintainable.</p>
<h3 id="heading-types-of-errors">Types of Errors</h3>
<p>In Go, errors can be categorized into two main types: regular errors and panics.</p>
<ol>
<li><p><strong>Regular Errors</strong>: Regular errors are errors that occur during the execution of a program and are expected to happen under certain conditions. These errors are typically returned from functions and are handled using the <code>if err != nil</code> pattern as shown above.</p>
</li>
<li><p><strong>Panics</strong>: Panics are unexpected errors that occur at runtime and cause the program to terminate abruptly. Unlike regular errors, panics are not explicitly handled using the <code>if err != nil</code> pattern. Instead, they are typically used to indicate unrecoverable errors, such as out-of-memory conditions or unexpected runtime behavior.</p>
</li>
</ol>
<h3 id="heading-handling-panics">Handling Panics</h3>
<p>In Go, panics can be recovered using the <code>recover()</code> function, which is typically called within a deferred function. 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> {
    <span class="hljs-keyword">defer</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">if</span> r := <span class="hljs-built_in">recover</span>(); r != <span class="hljs-literal">nil</span> {
            <span class="hljs-comment">// Handle the panic</span>
            log.Println(<span class="hljs-string">"Recovered from panic:"</span>, r)
        }
    }()

    <span class="hljs-comment">// Code that may panic</span>
    <span class="hljs-built_in">panic</span>(<span class="hljs-string">"something went wrong"</span>)
}
</code></pre>
<p>By using deferred functions and the <code>recover()</code> function, you can recover from panics and gracefully handle unexpected errors in your Go programs.</p>
<h3 id="heading-best-practices-for-error-handling">Best Practices for Error Handling</h3>
<p>When handling errors in Go, it's important to follow some best practices to ensure that your code is clean, readable, and maintainable. Here are some tips:</p>
<ol>
<li><p>Check errors early and handle them explicitly.</p>
</li>
<li><p>Provide context when returning errors to give more information about what went wrong.</p>
</li>
<li><p>Avoid swallowing errors by logging or returning them to the caller.</p>
</li>
<li><p>Use custom error types to differentiate between different types of errors and provide additional information.</p>
</li>
<li><p>Use panic and recover judiciously and only for unrecoverable errors.</p>
</li>
</ol>
<p>Error handling is an essential aspect of writing reliable and robust software applications in Go. By following the best practices and patterns outlined in this blog post, you can write clean, readable, and maintainable code that handles errors effectively and gracefully. Remember to check errors early, provide context, and use custom error types to differentiate between different types of errors. With these practices in mind, you can build more resilient Go applications that are better equipped to handle unexpected errors and failures.</p>
]]></content:encoded></item><item><title><![CDATA[Building Microservices in Go: A Practical Guide with gRPC]]></title><description><![CDATA[Microservices architecture has gained immense popularity due to its flexibility, scalability, and resilience. Among the myriad of languages suitable for building microservices, Go (Golang) stands out for its simplicity, performance, and built-in supp...]]></description><link>https://arielorozco.com/building-microservices-in-go-a-practical-guide-with-grpc</link><guid isPermaLink="true">https://arielorozco.com/building-microservices-in-go-a-practical-guide-with-grpc</guid><category><![CDATA[golang]]></category><category><![CDATA[gRPC]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Thu, 08 Feb 2024 15:38:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707406664772/7a2d80bb-ae87-4db6-8607-25f2ff0c57e3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microservices architecture has gained immense popularity due to its flexibility, scalability, and resilience. Among the myriad of languages suitable for building microservices, Go (Golang) stands out for its simplicity, performance, and built-in support for concurrency. In this guide, we'll delve into building microservices in Go using gRPC, a modern and efficient RPC (Remote Procedure Call) framework.</p>
<h3 id="heading-introduction-to-microservices-and-grpc">Introduction to Microservices and gRPC</h3>
<p>Microservices are an architectural style where applications are composed of small, independently deployable services that work together. Each microservice focuses on a specific business capability, and they communicate with each other via APIs.</p>
<p>gRPC, developed by Google, is a high-performance, language-agnostic RPC framework that simplifies the process of building microservices. It uses Protocol Buffers (protobuf) as its Interface Definition Language (IDL) for describing both the service interface and the structure of the payload messages.</p>
<h3 id="heading-setting-up-the-development-environment">Setting Up the Development Environment</h3>
<p>Before diving into building microservices, ensure you have Go installed on your system. Additionally, you'll need the protoc compiler for generating Go code from protobuf definitions. You can install it using the following command:</p>
<pre><code class="lang-bash">$ go get -u github.com/golang/protobuf/protoc-gen-go
</code></pre>
<h3 id="heading-defining-the-service-interface">Defining the Service Interface</h3>
<p>The first step in building a microservice with gRPC is defining the service interface using Protocol Buffers. Let's consider a simple example of a user management service with methods for creating, retrieving, updating, and deleting users.</p>
<pre><code class="lang-go"><span class="hljs-comment">// user.proto</span>

syntax = <span class="hljs-string">"proto3"</span>;

service UserService {
    rpc CreateUser(UserRequest) returns (UserResponse);
    rpc GetUser(UserIdRequest) returns (UserResponse);
    rpc UpdateUser(UserRequest) returns (UserResponse);
    rpc DeleteUser(UserIdRequest) returns (UserResponse);
}

message UserRequest {
    <span class="hljs-keyword">string</span> name = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">string</span> email = <span class="hljs-number">2</span>;
}

message UserIdRequest {
    <span class="hljs-keyword">string</span> id = <span class="hljs-number">1</span>;
}

message UserResponse {
    <span class="hljs-keyword">string</span> id = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">string</span> name = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">string</span> email = <span class="hljs-number">3</span>;
}
</code></pre>
<h3 id="heading-implementing-the-service-in-go">Implementing the Service in Go</h3>
<p>Once the service interface is defined, we can implement the service in Go. gRPC provides tools to generate Go code from the protobuf definition, including server and client interfaces.</p>
<pre><code class="lang-go"><span class="hljs-comment">// user.go</span>

<span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"context"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net"</span>

    <span class="hljs-string">"google.golang.org/grpc"</span>

    pb <span class="hljs-string">"yourmodule/user"</span>
)

<span class="hljs-keyword">type</span> userService <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *userService)</span> <span class="hljs-title">CreateUser</span><span class="hljs-params">(ctx context.Context, req *pb.UserRequest)</span> <span class="hljs-params">(*pb.UserResponse, error)</span></span> {
    <span class="hljs-comment">// Implementation for creating a user</span>
}

<span class="hljs-comment">// Implement other methods (GetUser, UpdateUser, DeleteUser) similarly</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    lis, err := net.Listen(<span class="hljs-string">"tcp"</span>, <span class="hljs-string">":50051"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatalf(<span class="hljs-string">"failed to listen: %v"</span>, err)
    }
    s := grpc.NewServer()
    pb.RegisterUserServiceServer(s, &amp;userService{})
    <span class="hljs-keyword">if</span> err := s.Serve(lis); err != <span class="hljs-literal">nil</span> {
        log.Fatalf(<span class="hljs-string">"failed to serve: %v"</span>, err)
    }
}
</code></pre>
<h3 id="heading-testing-the-microservice">Testing the Microservice</h3>
<p>To test the microservice, you can create a gRPC client in Go or use tools like BloomRPC. Here's a simple Go client for testing the user management service:</p>
<pre><code class="lang-go"><span class="hljs-comment">// client.go</span>

<span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"context"</span>
    <span class="hljs-string">"log"</span>

    <span class="hljs-string">"google.golang.org/grpc"</span>

    pb <span class="hljs-string">"yourmodule/user"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    conn, err := grpc.Dial(<span class="hljs-string">"localhost:50051"</span>, grpc.WithInsecure())
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatalf(<span class="hljs-string">"did not connect: %v"</span>, err)
    }
    <span class="hljs-keyword">defer</span> conn.Close()
    client := pb.NewUserServiceClient(conn)

    <span class="hljs-comment">// Test user creation</span>
    createUserResponse, err := client.CreateUser(context.Background(), &amp;pb.UserRequest{Name: <span class="hljs-string">"John Doe"</span>, Email: <span class="hljs-string">"john@example.com"</span>})
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatalf(<span class="hljs-string">"could not create user: %v"</span>, err)
    }
    log.Printf(<span class="hljs-string">"User created with ID: %s"</span>, createUserResponse.Id)

    <span class="hljs-comment">// Test other methods (GetUser, UpdateUser, DeleteUser) similarly</span>
}
</code></pre>
<p>In this guide, we've demonstrated how to build microservices in Go using gRPC. We started by defining the service interface using Protocol Buffers, implemented the service in Go, and tested it using a gRPC client. gRPC simplifies the process of building microservices by providing a powerful and efficient RPC framework, making it an excellent choice for developing scalable and resilient systems.</p>
<p>Building microservices with Go and gRPC offers a robust foundation for building modern, cloud-native applications. As you explore further, you'll discover additional features and patterns that can enhance the scalability, performance, and maintainability of your microservices architecture. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Go Generics: Writing Flexible Code]]></title><description><![CDATA[Go has been a language that prides itself on simplicity and efficiency. However, it has long been criticized for its lack of support for generics. The good news is that with the release of Go 1.18 in early 2022, generics are now officially part of th...]]></description><link>https://arielorozco.com/go-generics-writing-flexible-code</link><guid isPermaLink="true">https://arielorozco.com/go-generics-writing-flexible-code</guid><category><![CDATA[General Programming]]></category><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[generics]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Tue, 24 Oct 2023 16:53:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698166538598/61d8a079-8799-4f6e-b8e9-bfa3e7a1051c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Go has been a language that prides itself on simplicity and efficiency. However, it has long been criticized for its lack of support for generics. The good news is that with the release of Go 1.18 in early 2022, generics are now officially part of the language. This is a game-changer for Go developers as it opens up new possibilities for writing more versatile and reusable code. In this blog post, we'll explore the concept of generics in Go, why they are valuable, and how to use them with practical examples.</p>
<h3 id="heading-what-are-generics-and-why-are-they-useful">What are Generics and Why Are They Useful?</h3>
<p>Generics in programming refer to writing code that can work with different data types while maintaining type safety. In the context of Go, generics allow developers to write functions and data structures that are not tied to specific data types. This enhances code reusability and flexibility.</p>
<p>Before the introduction of generics, Go developers often resorted to interfaces and code duplication to handle different data types. Generics eliminate the need for these workarounds, making the code more concise and easier to maintain.</p>
<p>Generics are particularly useful in scenarios where you want to write reusable functions or data structures that work with a wide range of data types, such as containers (e.g., slices, maps) and algorithms (e.g., sorting, filtering).</p>
<h3 id="heading-using-generics-in-go">Using Generics in Go</h3>
<p>In Go 1.18, generics are introduced through type parameters, which are specified inside angle brackets ("&lt;" and "&gt;"). These parameters define the data types that a generic function or data structure can operate on. Let's dive into how to use generics in Go with some code examples.</p>
<h3 id="heading-writing-a-generic-function">Writing a Generic Function</h3>
<p>Here's an example of a generic function that finds the maximum element in a slice of any type:</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">FindMax</span>[<span class="hljs-title">T</span> <span class="hljs-title">comparable</span>]<span class="hljs-params">(slice []T)</span> <span class="hljs-title">T</span></span> {
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(slice) == <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> T{}
    }

    max := slice[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">for</span> _, item := <span class="hljs-keyword">range</span> slice {
        <span class="hljs-keyword">if</span> item &gt; max {
            max = item
        }
    }
    <span class="hljs-keyword">return</span> max
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    ints := []<span class="hljs-keyword">int</span>{<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">5</span>}
    maxInt := FindMax(ints)
    fmt.Println(<span class="hljs-string">"Max integer:"</span>, maxInt)

    floats := []<span class="hljs-keyword">float64</span>{<span class="hljs-number">3.14</span>, <span class="hljs-number">1.618</span>, <span class="hljs-number">2.718</span>, <span class="hljs-number">0.577</span>}
    maxFloat := FindMax(floats)
    fmt.Println(<span class="hljs-string">"Max float:"</span>, maxFloat)
}
</code></pre>
<p>In this example, <code>FindMax</code> is a generic function that takes a slice of any comparable type and returns the maximum element. The type parameter <code>T</code> is used to indicate that it can work with various data types.</p>
<h3 id="heading-writing-a-generic-data-structure">Writing a Generic Data Structure</h3>
<p>Generics can also be applied to data structures. Here's an example of a generic stack implementation:</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-keyword">type</span> Stack[T any] []T

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Stack[T])</span> <span class="hljs-title">Push</span><span class="hljs-params">(item T)</span></span> {
    *s = <span class="hljs-built_in">append</span>(*s, item)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Stack[T])</span> <span class="hljs-title">Pop</span><span class="hljs-params">()</span> <span class="hljs-title">T</span></span> {
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(*s) == <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> T{}
    }
    item := (*s)[<span class="hljs-built_in">len</span>(*s)<span class="hljs-number">-1</span>]
    *s = (*s)[:<span class="hljs-built_in">len</span>(*s)<span class="hljs-number">-1</span>]
    <span class="hljs-keyword">return</span> item
}

<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> intStack Stack[<span class="hljs-keyword">int</span>]
    intStack.Push(<span class="hljs-number">1</span>)
    intStack.Push(<span class="hljs-number">2</span>)
    intStack.Push(<span class="hljs-number">3</span>)
    fmt.Println(<span class="hljs-string">"Popped:"</span>, intStack.Pop())

    <span class="hljs-keyword">var</span> stringStack Stack[<span class="hljs-keyword">string</span>]
    stringStack.Push(<span class="hljs-string">"Hello"</span>)
    stringStack.Push(<span class="hljs-string">"World"</span>)
    fmt.Println(<span class="hljs-string">"Popped:"</span>, stringStack.Pop())
}
</code></pre>
<p>In this example, we define a generic stack data structure that can work with any data type. The <code>Stack[T any]</code> syntax allows us to create a stack with elements of type <code>T</code>.</p>
<p>Generics are a long-awaited feature in Go that greatly enhances the language's expressiveness and code reusability. With generics, developers can write more flexible and efficient code, eliminating the need for type assertions, interfaces, and code duplication.</p>
<p>The introduction of generics in Go 1.18 opens up exciting possibilities for the Go community, making it easier to create versatile libraries and build more maintainable and robust applications. Embrace the power of generics and level up your Go programming skills. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Applying SOLID Principles in Golang: Writing Clean and Maintainable Code]]></title><description><![CDATA[The SOLID principles are a set of five design principles that help software developers create clean, maintainable, and scalable code. These principles were introduced by Robert C. Martin and have become fundamental guidelines in the world of software...]]></description><link>https://arielorozco.com/applying-solid-principles-in-golang-writing-clean-and-maintainable-code</link><guid isPermaLink="true">https://arielorozco.com/applying-solid-principles-in-golang-writing-clean-and-maintainable-code</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Mon, 09 Oct 2023 18:48:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696877181110/8fc614c5-00e4-434f-be54-5e7d139bd38c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The SOLID principles are a set of five design principles that help software developers create clean, maintainable, and scalable code. These principles were introduced by Robert C. Martin and have become fundamental guidelines in the world of software development. In this blog post, we'll explore each of the SOLID principles and demonstrate how to apply them in the context of the Go programming language (Golang) with practical code examples.</p>
<h2 id="heading-1-single-responsibility-principle-srp"><strong>1. Single Responsibility Principle (SRP)</strong></h2>
<p>The Single Responsibility Principle states that a class or module should have only one reason to change. In other words, it should have only one responsibility.</p>
<p>In Golang, this principle can be applied by creating small, focused functions or methods that perform a single task. Let's consider an example where we have a <code>UserService</code> responsible for user management:</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-keyword">type</span> User <span class="hljs-keyword">struct</span> {
    ID   <span class="hljs-keyword">int</span>
    Name <span class="hljs-keyword">string</span>
}

<span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span> {
    users []User
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(us *UserService)</span> <span class="hljs-title">AddUser</span><span class="hljs-params">(user User)</span></span> {
    us.users = <span class="hljs-built_in">append</span>(us.users, user)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(us *UserService)</span> <span class="hljs-title">GetUserByID</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(User, error)</span></span> {
    <span class="hljs-keyword">for</span> _, user := <span class="hljs-keyword">range</span> us.users {
        <span class="hljs-keyword">if</span> user.ID == id {
            <span class="hljs-keyword">return</span> user, <span class="hljs-literal">nil</span>
        }
    }
    <span class="hljs-keyword">return</span> User{}, fmt.Errorf(<span class="hljs-string">"User not found"</span>)
}
</code></pre>
<p>In this example, the <code>UserService</code> class has a single responsibility: managing user data. It defines methods to add and retrieve users, adhering to the SRP.</p>
<h2 id="heading-2-openclosed-principle-ocp"><strong>2. Open/Closed Principle (OCP)</strong></h2>
<p>The Open/Closed Principle states that software entities (classes, modules, functions) should be open for extension but closed for modification. In other words, you should be able to add new functionality without altering existing code.</p>
<p>In Golang, you can achieve this principle by using interfaces and composition. Let's extend our previous example to support user authentication without modifying the <code>UserService</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Authenticator <span class="hljs-keyword">interface</span> {
    Authenticate(username, password <span class="hljs-keyword">string</span>) <span class="hljs-keyword">bool</span>
}

<span class="hljs-keyword">type</span> AuthenticatedUserService <span class="hljs-keyword">struct</span> {
    UserService
    Authenticator
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(aus *AuthenticatedUserService)</span> <span class="hljs-title">AddUserWithAuth</span><span class="hljs-params">(user User, username, password <span class="hljs-keyword">string</span>)</span></span> {
    <span class="hljs-keyword">if</span> aus.Authenticate(username, password) {
        aus.AddUser(user)
    }
}
</code></pre>
<p>Now, we've created an <code>AuthenticatedUserService</code> that embeds the <code>UserService</code> and implements an <code>Authenticate</code> method. This allows us to add authentication functionality without changing the original <code>UserService</code>.</p>
<h2 id="heading-3-liskov-substitution-principle-lsp"><strong>3. Liskov Substitution Principle (LSP)</strong></h2>
<p>The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In Golang, this principle is closely related to interfaces.</p>
<p>Consider the following example involving shapes:</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> Rectangle <span class="hljs-keyword">struct</span> {
    Width  <span class="hljs-keyword">float64</span>
    Height <span class="hljs-keyword">float64</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r Rectangle)</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-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
}
</code></pre>
<p>Here, both <code>Rectangle</code> and <code>Circle</code> implement the <code>Shape</code> interface, allowing them to be used interchangeably wherever a <code>Shape</code> is expected.</p>
<h2 id="heading-4-interface-segregation-principle-isp"><strong>4. Interface Segregation Principle (ISP)</strong></h2>
<p>The Interface Segregation Principle states that clients should not be forced to depend on interfaces they do not use. In Golang, this principle is essential when designing interfaces.</p>
<p>Let's say we have an interface for a document printer:</p>
<pre><code class="lang-go">goCopy codetype Printer <span class="hljs-keyword">interface</span> {
    Print()
    Scan()
    Fax()
}
</code></pre>
<p>If a client only needs to print documents, they should not be forced to implement <code>Scan</code> and <code>Fax</code> methods. Instead, we can break this interface into smaller, more focused ones:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Printer <span class="hljs-keyword">interface</span> {
    Print()
}

<span class="hljs-keyword">type</span> Scanner <span class="hljs-keyword">interface</span> {
    Scan()
}

<span class="hljs-keyword">type</span> FaxMachine <span class="hljs-keyword">interface</span> {
    Fax()
}
</code></pre>
<p>Now, clients can choose the interfaces they need, adhering to the ISP.</p>
<h2 id="heading-5-dependency-inversion-principle-dip"><strong>5. Dependency Inversion Principle (DIP)</strong></h2>
<p>The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details; details should depend on abstractions.</p>
<p>In Golang, we can apply this principle by using interfaces and dependency injection. Here's an example of a <code>NotificationService</code> that sends notifications through different channels:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Notifier <span class="hljs-keyword">interface</span> {
    Notify(message <span class="hljs-keyword">string</span>)
}

<span class="hljs-keyword">type</span> EmailNotifier <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(en EmailNotifier)</span> <span class="hljs-title">Notify</span><span class="hljs-params">(message <span class="hljs-keyword">string</span>)</span></span> {
    fmt.Println(<span class="hljs-string">"Sending email:"</span>, message)
}

<span class="hljs-keyword">type</span> SMSNotifier <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(sn SMSNotifier)</span> <span class="hljs-title">Notify</span><span class="hljs-params">(message <span class="hljs-keyword">string</span>)</span></span> {
    fmt.Println(<span class="hljs-string">"Sending SMS:"</span>, message)
}

<span class="hljs-keyword">type</span> NotificationService <span class="hljs-keyword">struct</span> {
    Notifier
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewNotificationService</span><span class="hljs-params">(notifier Notifier)</span> *<span class="hljs-title">NotificationService</span></span> {
    <span class="hljs-keyword">return</span> &amp;NotificationService{Notifier: notifier}
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    emailNotifier := EmailNotifier{}
    smsNotifier := SMSNotifier{}

    emailService := NewNotificationService(emailNotifier)
    smsService := NewNotificationService(smsNotifier)

    emailService.Notify(<span class="hljs-string">"Hello, World!"</span>)
    smsService.Notify(<span class="hljs-string">"Important message"</span>)
}
</code></pre>
<p>By injecting the <code>Notifier</code> interface into the <code>NotificationService</code>, we follow the DIP, allowing for easy switching between different notification methods without modifying the high-level module.</p>
<p>Applying the SOLID principles in Golang leads to cleaner, more maintainable code. These principles guide us in designing software that is flexible, extensible, and easy to understand, ultimately improving the quality and longevity of our codebase. Remember that SOLID is not a strict set of rules but rather a set of guidelines to help us make informed design decisions.</p>
]]></content:encoded></item><item><title><![CDATA[How to Use the ChatGPT API with PHP: A Step-by-Step Guide]]></title><description><![CDATA[In recent years, natural language processing (NLP) models have made tremendous advancements in understanding and generating human-like text. OpenAI's GPT-3 model, powered by the ChatGPT API, is one such breakthrough. It allows developers to integrate...]]></description><link>https://arielorozco.com/how-to-use-the-chatgpt-api-with-php-a-step-by-step-guide</link><guid isPermaLink="true">https://arielorozco.com/how-to-use-the-chatgpt-api-with-php-a-step-by-step-guide</guid><category><![CDATA[chatgpt]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Wed, 20 Sep 2023 19:12:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/agFmImWyPso/upload/cd6e082e57e8d9dd5f9c1acca97236f0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In recent years, natural language processing (NLP) models have made tremendous advancements in understanding and generating human-like text. OpenAI's GPT-3 model, powered by the ChatGPT API, is one such breakthrough. It allows developers to integrate the power of AI language generation into their applications. In this tutorial, we will explore how to use the ChatGPT API with PHP, and we'll provide you with easy-to-follow code examples to get you started.</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Before we dive into the code, ensure you have the following prerequisites in place:</p>
<ol>
<li><p><strong>OpenAI API Key</strong>: You need to sign up for access to the ChatGPT API and obtain your API key. You can do this by visiting the <a target="_blank" href="https://beta.openai.com/signup/"><strong>OpenAI website</strong></a>.</p>
</li>
<li><p><strong>PHP</strong>: Make sure you have PHP installed on your system. You can check your PHP version by running <code>php -v</code> in your terminal.</p>
</li>
<li><p><strong>cURL Library</strong>: PHP's cURL library allows us to make HTTP requests. Ensure it is enabled in your PHP configuration. You can check for cURL support by running <code>php -m | grep curl</code>.</p>
</li>
</ol>
<h2 id="heading-setting-up-your-php-project"><strong>Setting Up Your PHP Project</strong></h2>
<p>Let's create a simple PHP project structure:</p>
<pre><code class="lang-plaintext">/chatgpt-php
│   index.php
│
└───vendor
    └───guzzlehttp
            guzzle
</code></pre>
<p>To set up this structure, create a directory named <code>chatgpt-php</code> and navigate to it in your terminal. Then, run the following commands:</p>
<pre><code class="lang-bash">mkdir vendor
<span class="hljs-built_in">cd</span> vendor
composer require guzzlehttp/guzzle
</code></pre>
<p>This will create a basic project structure and install the Guzzle HTTP client, which we'll use to make API requests.</p>
<h2 id="heading-making-a-chatgpt-api-request"><strong>Making a ChatGPT API Request</strong></h2>
<p>Now, let's write PHP code to make a request to the ChatGPT API. Create a new file called <code>index.php</code> in the <code>chatgpt-php</code> directory and add the following code:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">'vendor/autoload.php'</span>;

<span class="hljs-comment">// Replace 'YOUR_API_KEY' with your actual API key</span>
$apiKey = <span class="hljs-string">'YOUR_API_KEY'</span>;

<span class="hljs-comment">// Define the endpoint URL</span>
$endpoint = <span class="hljs-string">'https://api.openai.com/v1/engines/davinci-codex/completions'</span>;

<span class="hljs-comment">// Create a new Guzzle HTTP client</span>
$client = <span class="hljs-keyword">new</span> \GuzzleHttp\Client();

<span class="hljs-comment">// Define the prompt for ChatGPT</span>
$prompt = <span class="hljs-string">'Translate the following English text to French:'</span>;

<span class="hljs-comment">// Make a POST request to the API</span>
$response = $client-&gt;post($endpoint, [
    <span class="hljs-string">'headers'</span> =&gt; [
        <span class="hljs-string">'Authorization'</span> =&gt; <span class="hljs-string">"Bearer <span class="hljs-subst">$apiKey</span>"</span>,
    ],
    <span class="hljs-string">'json'</span> =&gt; [
        <span class="hljs-string">'prompt'</span> =&gt; $prompt,
        <span class="hljs-string">'max_tokens'</span> =&gt; <span class="hljs-number">50</span>, <span class="hljs-comment">// Adjust the max tokens as needed</span>
    ],
]);

<span class="hljs-comment">// Decode the response JSON</span>
$data = json_decode($response-&gt;getBody(), <span class="hljs-literal">true</span>);

<span class="hljs-comment">// Extract and print the AI-generated text</span>
$generatedText = $data[<span class="hljs-string">'choices'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'text'</span>];
<span class="hljs-keyword">echo</span> $generatedText;
</code></pre>
<p>In this code:</p>
<ul>
<li><p>We import the Guzzle HTTP client to make HTTP requests.</p>
</li>
<li><p>Replace <code>'YOUR_API_KEY'</code> with your actual ChatGPT API key.</p>
</li>
<li><p>We define the API endpoint for ChatGPT.</p>
</li>
<li><p>A prompt is set, which will be used to instruct ChatGPT.</p>
</li>
<li><p>We make a POST request to the API, passing in the API key, prompt, and other optional parameters such as <code>max_tokens</code> to limit the response length.</p>
</li>
<li><p>Finally, we decode the JSON response and extract and print the AI-generated text.</p>
</li>
</ul>
<h2 id="heading-running-the-php-script"><strong>Running the PHP Script</strong></h2>
<p>To run the PHP script, navigate to the <code>chatgpt-php</code> directory in your terminal and execute:</p>
<pre><code class="lang-bash">php index.php
</code></pre>
<p>You should see the AI-generated text as a response in your terminal.</p>
<p>You have successfully made your first ChatGPT API request using PHP. You can now integrate this powerful language model into your PHP applications to automate tasks, generate text, or assist users with natural language understanding. Experiment with different prompts and parameters to see the full potential of ChatGPT in action. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Domain Driven Design & Go]]></title><description><![CDATA[Domain-driven design (DDD) is a software development approach that emphasizes the importance of understanding the business domain in order to create effective software solutions. By identifying and modeling key business concepts, DDD helps developers...]]></description><link>https://arielorozco.com/domain-driven-design-go</link><guid isPermaLink="true">https://arielorozco.com/domain-driven-design-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Tue, 18 Apr 2023 17:07:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681838518105/7206bfc3-9742-4035-8d5d-8b142f40db2a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Domain-driven design (DDD) is a software development approach that emphasizes the importance of understanding the business domain in order to create effective software solutions. By identifying and modeling key business concepts, DDD helps developers create software that aligns with the needs of the business.</p>
<p>If you're working on a Go project and are interested in applying DDD principles, here are some tips to get started:</p>
<ol>
<li><strong>Start with a clear understanding of the business domain</strong></li>
</ol>
<p>Before you can start designing your software, you need to have a deep understanding of the business domain you are working in. This means taking the time to talk to stakeholders, read documentation, and analyze existing systems. You should be able to identify the key business concepts, relationships, and processes that will need to be modeled in your software.</p>
<ol>
<li><strong>Create a domain model</strong></li>
</ol>
<p>Once you have a clear understanding of the business domain, the next step is to create a domain model. This is a conceptual model that captures the key business concepts and their relationships. The domain model should be created in close collaboration with business stakeholders and subject matter experts.</p>
<p>In Go, you can create your domain model as a set of structs and interfaces that represent the key concepts in your domain. You should also define the relationships between these concepts using embedded structs or interfaces.</p>
<ol>
<li><strong>Implement domain services</strong></li>
</ol>
<p>Once you have a domain model in place, the next step is to implement domain services. Domain services are the business logic that operates on the domain objects. In Go, domain services can be implemented as functions or methods that take in domain objects and return domain objects or values.</p>
<p>It's important to keep the domain services focused on the core business logic and avoid including implementation details or technical concerns. This will help keep your code clean and maintainable.</p>
<ol>
<li><strong>Use value objects</strong></li>
</ol>
<p>Value objects are domain objects that have no identity beyond their value. They are immutable and can be shared freely between different parts of the system. In Go, value objects can be implemented as structs with no mutable fields.</p>
<p>Using value objects can help simplify your code and make it more expressive. They can also help ensure that your code is correct by enforcing business rules at the type level.</p>
<ol>
<li><strong>Use bounded contexts</strong></li>
</ol>
<p>A bounded context is a way of grouping together domain objects and services that are related to a specific part of the business domain. By using bounded contexts, you can create a clear separation of concerns between different parts of your system.</p>
<p>In Go, you can implement bounded contexts as separate packages that contain the domain objects and services related to a specific part of the business domain. This can help keep your code organized and maintainable.</p>
<ol>
<li><strong>Write tests</strong></li>
</ol>
<p>Finally, it's important to write tests for your domain code. Tests can help ensure that your code is correct and that it behaves as expected. They can also help catch regressions when changes are made to the code.</p>
<p>In Go, you can write tests using the built-in testing framework. You should aim to write tests that cover all the important scenarios and edge cases in your domain logic.</p>
<p>Applying domain-driven design principles in Go can help you create software that aligns with the needs of the business. By starting with a clear understanding of the business domain, creating a domain model, implementing domain services, using value objects, defining bounded contexts, and writing tests, you can create clean, maintainable, and effective software solutions.</p>
]]></content:encoded></item><item><title><![CDATA[Build Scalable Applications with AWS Lambda and Go]]></title><description><![CDATA[The way we design, build and deploy web applications has changed a lot in the past few years. In the beginning, It all seemed like a simple task, our code lived all inside a big folder with a bunch of files in it, then we just uploaded the files usin...]]></description><link>https://arielorozco.com/build-scalable-applications-with-aws-lambda-and-go</link><guid isPermaLink="true">https://arielorozco.com/build-scalable-applications-with-aws-lambda-and-go</guid><category><![CDATA[AWS]]></category><category><![CDATA[aws lambda]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[serverless]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Thu, 26 Aug 2021 19:22:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1630004337840/Fr8rBLhfw.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The way we design, build and deploy web applications has changed a lot in the past few years. In the beginning, It all seemed like a simple task, our code lived all inside a big folder with a bunch of files in it, then we just uploaded the files using FTP and hoped everything would work out flawlessly. If something went wrong it was hard to keep the track of errors in an overwhelming number of lines of legacy code. </p>
<p>Deploying and managing our application was a time-consuming task that required us to be aware of the underlying infrastructure, servers that needed to be upgraded as our application and business growth, and all of this time that we spend on these tasks could have been spent on developing new features and improving our application instead. </p>
<p>Nowadays it has become easier to design and deploy applications that are able to scale, even automatically, as your business grows. With the rise of distributed systems and microservices, it is not necessary anymore to have all of your code and logic all in one place, we can rely on event-driven architecture to communicate between decoupled services.</p>
<p>We are going to take a brief overview on how AWS Lambda and the Serverless Framework work together to take advantage of all of these new ways of building scalable applications, all of this on top of the Go programming language, which brings us even more advantages while developing our application. </p>
<h2 id="the-rise-of-cloud-computing">The Rise of Cloud Computing</h2>
<p>If you think about it, everything has been "in the cloud" since the beginning, but the way we understand the term "Cloud Computing"  has changed with the rise of new technologies. Back in the day, you had to purchase a server, no matter if it was virtual or physical, you had to guess how much resources you were going to need and pay everything up front, and later if needed more space, memory, or resources you had to purchase them and upgrade your server.</p>
<p>Today "Cloud Computing" is the way we deliver computing services (servers, databases, storage, software, resources, networking) over the internet to build applications that can offer faster innovation, flexible resources and that can scale you, this means that you will lower your operating cost because you only pay for the services you use, and you run your infrastructure more efficiently because it scales as your business needs to change. </p>
<h3 id="top-benefits-of-cloud-computing">Top benefits of Cloud Computing</h3>
<ul>
<li><strong>Cost savings</strong>: you only pay for IT as you consume it</li>
<li><strong>Elasticity</strong>: no need to over-provision resources, you can scale those resources instantly as your business needs change</li>
<li><strong>Agility</strong>: you have access to a broad range of technologies, so you can innovate faster and build nearly anything you want</li>
</ul>
<p>There are several Cloud Providers out there that offer great services, some of them by well-known companies, like Microsoft, Google, and Amazon. One of the most used is Amazon AWS, which has a lot of services to choose from, being AWS Lambda one of them.</p>
<h2 id="distributed-systems">Distributed Systems</h2>
<p>It is very likely that you have been using distributed systems and you don't even know about it. On their most simple definition, a distributed system is a group of computers working together that share messages with each other to achieve a common goal. All of this will appear as it is a single computer to the end-user. </p>
<p>To better understand this, we can bring back the example where you upload all of your application code to a server, here your code lives on a single computer (virtual or physical), all of the business logic is inside of it and all of the components communicate within each other, if something fails on the infrastructure, all of the application goes down.</p>
<p>The distributed system allows us, in a certain way, to split our business logic into different components, they can be on different physical servers, virtual machines, or containers, and most likely located in different locations. So, by doing this, the system can maximize resources and information while preventing failures, so if one system fails, it won't affect the availability of the entire service. </p>
<h3 id="advantages-of-distributed-systems">Advantages of Distributed Systems</h3>
<ul>
<li><strong>Horizontal Scaling</strong>: it is easy and inexpensive to add additional machines as necessary</li>
<li><strong>Fault Tolerance</strong>: if one server or data center fails, others could still work without affecting the whole system</li>
<li><strong>Performance</strong>: they are very efficient because workloads can be broken and sent to multiple machines</li>
</ul>
<p>Most modern web applications are based upon distributed systems, building a scalable application heavily relies on this concept, even more, if it is built on top of any cloud provider services.</p>
<h2 id="from-monolith-to-microservices">From Monolith to Microservices</h2>
<p>Nowadays monolithic applications are still the backbone of most large organizations, but they are often tied to complex processes, which make them really fragile to changes on the codebase. They are built as a single unit where all of the components coexist within the same application, so any changes to the system involve building and deploying a new version of the entire application.</p>
<p>One of the modern and current software paradigms is to build smaller, independently deployable units of code, so you can break down the application into smaller services by applying the single responsibility principle. You design your system so each module is a standalone microservice responsible for a distinct business domain.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630004616966/VDvsb18k9.png" alt="image-20210121164237002.png" /></p>
<p>Designing your application as microservices is something that will give you great benefits if your plan is to build a scalable application that leverages the use of cloud computing and distributed systems. </p>
<h2 id="faas-function-as-a-service">FaaS (Function-as-a-Service)</h2>
<p>FaaS or "Function as a Service" is a type of Cloud Computing service that allows you to execute code in response to events without thinking about the complexity of the underlying infrastructure typically associated when you are deploying microservices applications. Provisioning and managing the infrastructure is handled automatically by your Cloud Service provider, so you can focus only on the individual function in your code and it allows you to create new applications composed of tiny building blocks.</p>
<h3 id="benefits-of-faas">Benefits of FaaS</h3>
<ul>
<li><strong>Focus more on the code</strong>: you can have to worry about infrastructure, this allows you to focus on the application code</li>
<li><strong>Scale automatically</strong>: functions are scaled automatically, independently, and really fast</li>
<li><strong>Pay only for the resources you use</strong>: you pay only when the function is executed, and usually, this is really cheap</li>
</ul>
<p>AWS Lambda is the Function-as-a-Service option provided by Amazon AWS, it gives us all of these benefits plus the convenience of being on the AWS platform, which is very useful if you want to take advantage of all of the other services.</p>
<h2 id="event-driven-architecture">Event-Driven Architecture</h2>
<p>AWS Lambda relies pretty much on the Event-Driven Architecture. This type of architecture allows your application to detect events whenever you want to trigger any business logic and do an action in response to that. This replaces the traditional "request/response" pattern where services would have to wait for a reply before they can move on to the next task.</p>
<p>An event can be anything, it can go from an item added to a cart, an order that was placed, an image uploaded to a server, a record updated on the database. This type of pattern uses events to trigger and communicate between services and it is very common in modern web applications that are built on top of microservices.</p>
<h2 id="the-future-is-serverless">The future is Serverless</h2>
<p>Serverless is a software development approach that eliminates the need to manage infrastructure by using Cloud Computing services (Functions-as-a-Service) to execute the code and external services and APIs to leverage the application.</p>
<p>We have to take into consideration that the term "Serverless" does not mean that servers are no longer being involved, it simply means that developers no longer need to be aware of the underlying infrastructure, computing resources are used as services, without managing physical capacities or limits.</p>
<h2 id="the-serverless-framework">The Serverless Framework</h2>
<p>The <a target="_blank" href="https://www.serverless.com/">Serverless Framework</a> makes it easy to write event-driven functions for various providers, including AWS. For each provider, a series of events can be configured to invoke the function. All of this is done programmatically by editing a YAML configuration file and running some commands on the terminal. Also, you can integrate this with existing Continuous Integration and Continuous Delivery frameworks.</p>
<p>This really makes the task of deploying and updating the code of our function really easy and fast. Also, when you create your serverless project there are plenty of templates ready for you if you want to use them, so you don't have to start from scratch. Particularly on AWS you can accomplish this by using the AWS console and doing everything from there, but every time you want to update your code you will have to compress it on a zip file and upload it with the AWS console, also there are other things that you have to take into consideration, like IAM users, roles and policies.  </p>
<p>The Serverless framework takes care of all of this, so you can focus just on the code.</p>
<h2 id="aws-lambda">AWS Lambda</h2>
<p><a target="_blank" href="https://aws.amazon.com/lambda/">AWS Lambda</a> is an event-driven serverless computing platform. It lets you run your code without provisioning or managing servers and it runs your code only when needed and scales automatically, you pay only for the compute time that you consume, so they don't charge you when nothing is running.</p>
<p>This is how it works</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630004799577/BKpcElQTQ.png" alt="image-20210121162649062.png" /></p>
<p>Currently, AWS Lambda supports several programming languages through the use of runtimes, like node.js, Python, Ruby, Java, and Go. To use other languages in Lambda you can implement a custom runtime, so the possibilities are endless. </p>
<p>If you are using AWS Lambda, you can also take advantage of all of the other AWS Cloud Services. You can trigger events when a photo is uploaded to Amazon S3, listen to streams of data from Amazon Kinesis, trigger a function when data gets added to DynamoDB, or even use Amazon API Gateway to build a serverless REST API. The possibilities are endless.</p>
<h3 id="pricing">Pricing</h3>
<p>You only pay for what you use and charged based on the number of requests and duration of your function. We are not going to deep dive into this topic, but rest assured that it's ridiculously cheap to run a Lambda function, even with the "Free Tier" you can play around a lot and probably run a small service. FOr more information, you can take a look at the <a target="_blank" href="https://aws.amazon.com/lambda/pricing/">AWS Lambda Pricing</a> page.</p>
<h3 id="when-should-i-use-aws-lambda">When should I use AWS Lambda?</h3>
<p>First, you have to think in an Event-Driven way. If there's a feature on your application that needs to be run in response to an event, and that feature does not need to be running all of the time, then probably that is a good use case for AWS Lamba, here are some examples:</p>
<ul>
<li>Rapid document conversion</li>
<li>Image resizing and processing </li>
<li>Handling uploaded AWS S3 objects </li>
<li>Operating serverless websites</li>
<li>Automated backups and everyday tasks</li>
<li>Real-time data processing</li>
</ul>
<h2 id="why-go">Why Go?</h2>
<p>Go is without a doubt one of the fastest-growing programming languages today, it has been adopted by a large number of companies, but is has been really active in the Cloud Computing scenario. This is why AWS, one of the biggest Cloud Computing providers, has added support for Go in AWS Lambda since the beginning of 2018.</p>
<p>Some of the major advantages of using Go with AWS Lambda are:</p>
<ul>
<li><strong>Runtime versioning</strong>: the Go runtime for AWS Lambda supports any 1.x release, so whenever a new version of Go is released it is possible to use it right away, without having to wait for support on the updated runtime</li>
<li><strong>Concurrency</strong>: concurrency was built into the core design of Go, this allows us to create more efficient functions with the great benefit of Goroutines</li>
<li><strong>Pricing</strong>: the pricing model for AWS Lambda is per invocation, plus the duration of the invocation rounded up to the nearest 100ms. Go is not as memory hungry as other dynamic languages, and there's a direct relation between CPU performance and the allocated memory, so this makes it very efficient</li>
</ul>
<h2 id="sample-application">Sample Application</h2>
<p>To get a better idea of how <strong>AWS Lambda</strong> and the <strong>Serverless Framework</strong> work together we are going to build a simple function that just exposes an HTTP endpoint that receives a parameter on the URL and returns a JSON response. Nothing trivial, but I'm a true believer that with small and simple examples you understand a new concept better, also by doing this you will see how easy and quick is to build and deploy a Lambda function with the framework. </p>
<h3 id="prerequisites">Prerequisites</h3>
<ul>
<li><p><a target="_blank" href="https://portal.aws.amazon.com/billing">Create an AWS Account</a></p>
</li>
<li><p><a target="_blank" href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console">Create an IAM User on AWS Console</a> (save the <em>access key</em> and <em>secret key</em>)</p>
</li>
<li><p>Install <a target="_blank" href="https://golang.org/">Go</a></p>
</li>
<li><p>Install Serverless (you will need to <a target="_blank" href="https://nodejs.org/es/download/">install node.js</a> first)</p>
<pre><code>$ <span class="hljs-built_in">npm</span> install -g serverless
</code></pre></li>
</ul>
<h3 id="function-code">Function Code</h3>
<p>The code is pretty straightforward, most of the Lambda functions are build following the same pattern, it also depends on which AWS services and integrations you are using, also the purpose of your function. The most important aspect here is that you are always going to need a <strong>Handler</strong> function, which is the one that takes care of all of the logic, and this is the one that you call on your <em>main()</em> function.</p>
<pre><code><span class="hljs-keyword">package</span> main

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

    <span class="hljs-string">"github.com/aws/aws-lambda-go/events"</span>
    <span class="hljs-string">"github.com/aws/aws-lambda-go/lambda"</span>
)

<span class="hljs-comment">// This function is the one that is going to be called</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Handler</span><span class="hljs-params">(request events.APIGatewayProxyRequest)</span> <span class="hljs-params">(events.APIGatewayProxyResponse, error)</span></span> {

    <span class="hljs-comment">// Get the 'name' parameter from the URL</span>
    name := request.PathParameters[<span class="hljs-string">"name"</span>]

    <span class="hljs-comment">// Create the message that is going to be returned</span>
    message := fmt.Sprintf(<span class="hljs-string">" { \"Message\" : \"AWS Lambda is Awesome! Right %s? \" } "</span>, name)

    <span class="hljs-comment">// Return the response </span>
    <span class="hljs-keyword">return</span> events.APIGatewayProxyResponse{Body: message, StatusCode: <span class="hljs-number">200</span>}, <span class="hljs-literal">nil</span>
}

<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-comment">// Start the Handler</span>
    lambda.Start(Handler)
}
</code></pre><h3 id="serverless-framework-setup">Serverless Framework Setup</h3>
<ol>
<li>Configure Serverless: replace with your <em>access key</em> and <em>secret key</em>. <code>serverless-admin</code> is going to be the name of your profile, this can be whatever you want</li>
</ol>
<pre><code>$ serverless config credentials --provider aws --key <span class="hljs-tag">&lt;<span class="hljs-name">your_key</span>&gt;</span> --secret <span class="hljs-tag">&lt;<span class="hljs-name">your_secret</span>&gt;</span> --profile serverless-admin
</code></pre><ol>
<li>Create the <code>serverless.yml</code> file (for full configuration options you can <a target="_blank" href="https://www.serverless.com/framework/docs/">check the documentation</a>)</li>
</ol>
<pre><code><span class="hljs-string">yaml</span>
   <span class="hljs-attr">service:</span> <span class="hljs-string">lambda-sample</span>

   <span class="hljs-attr">frameworkVersion:</span> <span class="hljs-string">'2'</span>

   <span class="hljs-attr">provider:</span>
     <span class="hljs-attr">name:</span> <span class="hljs-string">aws</span>
     <span class="hljs-attr">runtime:</span> <span class="hljs-string">go1.x</span>
     <span class="hljs-attr">lambdaHashingVersion:</span> <span class="hljs-number">20201221</span>
     <span class="hljs-attr">profile:</span> <span class="hljs-string">serverless-admin</span>
     <span class="hljs-attr">region:</span> <span class="hljs-string">us-east-2</span>

   <span class="hljs-attr">package:</span>
     <span class="hljs-attr">exclude:</span>
       <span class="hljs-bullet">-</span> <span class="hljs-string">./**</span>
     <span class="hljs-attr">include:</span>
       <span class="hljs-bullet">-</span> <span class="hljs-string">./bin/**</span>

   <span class="hljs-attr">functions:</span>
     <span class="hljs-attr">hello:</span>
       <span class="hljs-attr">handler:</span> <span class="hljs-string">bin/hello</span>
       <span class="hljs-attr">events:</span>
         <span class="hljs-bullet">-</span> <span class="hljs-attr">http:</span>
             <span class="hljs-attr">path:</span> <span class="hljs-string">hello/{name}</span>
             <span class="hljs-attr">method:</span> <span class="hljs-string">get</span>
</code></pre><ol>
<li><p>Place the function code inside  <code>hello/main.go</code></p>
</li>
<li><p>Build the app</p>
</li>
</ol>
<pre><code>$ env GOOS=linux <span class="hljs-keyword">go</span> build -ldflags=<span class="hljs-string">"-s -w"</span> -o bin/hello hello/main.<span class="hljs-keyword">go</span>
</code></pre><ol>
<li>Deploy the app</li>
</ol>
<pre><code>$ sls deploy -v
   <span class="hljs-symbol">Serverless:</span> Packaging service...
   <span class="hljs-symbol">Serverless:</span> Excluding development dependencies...
   <span class="hljs-symbol">Serverless:</span> Creating Stack...
   <span class="hljs-symbol">Serverless:</span> Checking Stack create progress...
   CloudFormation - CREATE_IN_PROGRESS - AWS::CloudFormation::Stack - hello-dev
   CloudFormation - CREATE_IN_PROGRESS - AWS::S3::Bucket - ServerlessDeploymentBucket
   CloudFormation - CREATE_IN_PROGRESS - AWS::S3::Bucket - ServerlessDeploymentBucket
   CloudFormation - CREATE_COMPLETE - AWS::S3::Bucket - ServerlessDeploymentBucket
   CloudFormation - CREATE_IN_PROGRESS - AWS::S3::BucketPolicy - ServerlessDeploymentBucketPolicy
   CloudFormation - CREATE_IN_PROGRESS - AWS::S3::BucketPolicy - ServerlessDeploymentBucketPolicy
   CloudFormation - CREATE_COMPLETE - AWS::S3::BucketPolicy - ServerlessDeploymentBucketPolicy
   CloudFormation - CREATE_COMPLETE - AWS::CloudFormation::Stack - hello-dev
   <span class="hljs-symbol">Serverless:</span> Stack create finished...
   <span class="hljs-symbol">Serverless:</span> Uploading CloudFormation file to S3...
   <span class="hljs-symbol">Serverless:</span> Uploading artifacts...
   <span class="hljs-symbol">Serverless:</span> Uploading service hello.zip file to S3 (<span class="hljs-number">2.76</span> MB)...
   <span class="hljs-symbol">Serverless:</span> Validating template...
   <span class="hljs-symbol">Serverless:</span> Updating Stack...
   <span class="hljs-symbol">Serverless:</span> Checking Stack update progress...
   CloudFormation - UPDATE_IN_PROGRESS - AWS::CloudFormation::Stack - hello-dev
   CloudFormation - CREATE_IN_PROGRESS - AWS::IAM::Role - IamRoleLambdaExecution
   CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - HelloLogGroup
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
   CloudFormation - CREATE_IN_PROGRESS - AWS::IAM::Role - IamRoleLambdaExecution
   CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::RestApi - ApiGatewayRestApi
   CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - HelloLogGroup
   CloudFormation - CREATE_COMPLETE - AWS::Logs::LogGroup - HelloLogGroup
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
   CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Resource - ApiGatewayResourceHello
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHelloNameVar
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHelloNameVar
   CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Resource - ApiGatewayResourceHelloNameVar
   CloudFormation - CREATE_COMPLETE - AWS::IAM::Role - IamRoleLambdaExecution
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - HelloLambdaFunction
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - HelloLambdaFunction
   CloudFormation - CREATE_COMPLETE - AWS::Lambda::Function - HelloLambdaFunction
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloNameVarGet
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloNameVarGet
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - HelloLambdaPermissionApiGateway
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Version - HelloLambdaVersion0llM5cHtVxK5BhSODXsBnppzF2TM1roM6OfXw2qXINc
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - HelloLambdaPermissionApiGateway
   CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Method - ApiGatewayMethodHelloNameVarGet
   CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Version - HelloLambdaVersion0llM5cHtVxK5BhSODXsBnppzF2TM1roM6OfXw2qXINc
   CloudFormation - CREATE_COMPLETE - AWS::Lambda::Version - HelloLambdaVersion0llM5cHtVxK5BhSODXsBnppzF2TM1roM6OfXw2qXINc
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1611337803492
   CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1611337803492
   CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Deployment - ApiGatewayDeployment1611337803492
   CloudFormation - CREATE_COMPLETE - AWS::Lambda::Permission - HelloLambdaPermissionApiGateway
   CloudFormation - UPDATE_COMPLETE_CLEANUP_IN_PROGRESS - AWS::CloudFormation::Stack - hello-dev
   CloudFormation - UPDATE_COMPLETE - AWS::CloudFormation::Stack - hello-dev
   <span class="hljs-symbol">Serverless:</span> Stack update finished...
   Service Information
   <span class="hljs-symbol">service:</span> hello
   <span class="hljs-symbol">stage:</span> dev
   <span class="hljs-symbol">region:</span> us-east-<span class="hljs-number">2</span>
   <span class="hljs-symbol">stack:</span> hello-dev
   <span class="hljs-symbol">resources:</span> <span class="hljs-number">12</span>
   api <span class="hljs-symbol">keys:</span>
     None
   <span class="hljs-symbol">endpoints:</span>
     GET - <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/upr8kq3qsc.execute-api.us-east-2.amazonaws.com/dev</span><span class="hljs-regexp">/hello/</span>{name}
   <span class="hljs-symbol">functions:</span>
     <span class="hljs-symbol">hello:</span> hello-dev-hello
   <span class="hljs-symbol">layers:</span>
     None

   Stack Outputs
   <span class="hljs-symbol">HelloLambdaFunctionQualifiedArn:</span> <span class="hljs-symbol">arn:</span><span class="hljs-symbol">aws:</span><span class="hljs-symbol">lambda:</span>us-east-<span class="hljs-number">2</span><span class="hljs-symbol">:</span><span class="hljs-number">132653656301</span><span class="hljs-symbol">:function</span><span class="hljs-symbol">:hello-dev-hello</span><span class="hljs-symbol">:</span><span class="hljs-number">1</span>
   <span class="hljs-symbol">ServiceEndpoint:</span> <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/upr8kq3qsc.execute-api.us-east-2.amazonaws.com/dev</span>
   <span class="hljs-symbol">ServerlessDeploymentBucketName:</span> hello-dev-serverlessdeploymentbucket-rdd115w8vsw1
</code></pre><p>And that is it! As you can see the deploy output returns the URL where your endpoint is, in this case, <code>https://upr8kq3qsc.execute-api.us-east-2.amazonaws.com/dev/hello/{name}</code> (where you replace {name} with what you want to send to the function). If you visit that URL from your browser you will get:</p>
<pre><code>{
     <span class="hljs-attribute">Message</span>: <span class="hljs-string">"AWS Lambda is Awesome! Right, Ariel? "</span>
}
</code></pre><h3 id="additional-notes">Additional Notes</h3>
<ul>
<li>As you can see the only thing you needed was the <code>serverless.yml</code> configuration file to deploy your function. In this example everything was created from scratch, but I encourage you to try out any of the sample templates that are generated for you, they even come with some boilerplate code, so you can play around with them. You can generate an AWS Go template running this command:</li>
</ul>
<pre><code>$ sls create --template aws-go --path sample
  <span class="hljs-symbol">Serverless:</span> Generating boilerplate...
  <span class="hljs-symbol">Serverless:</span> Generating boilerplate <span class="hljs-keyword">in</span> <span class="hljs-string">"/code/lambda/sample"</span>
   ______<span class="hljs-number">_</span>                             _<span class="hljs-number">_</span>
  <span class="hljs-params">|   _   .-----.----.--.--.-----.----|</span>  .-----.-----.-----.
  <span class="hljs-params">|   |</span>__<span class="hljs-number">_</span><span class="hljs-params">|  -__|</span>   <span class="hljs-number">_</span><span class="hljs-params">|  |</span>  <span class="hljs-params">|  -__|</span>   <span class="hljs-number">_</span><span class="hljs-params">|  |</span>  -_<span class="hljs-number">_</span><span class="hljs-params">|__ --|</span>_<span class="hljs-number">_</span> --<span class="hljs-params">|
  |</span>___<span class="hljs-number">_</span>   <span class="hljs-params">|_____|</span>_<span class="hljs-number">_</span><span class="hljs-params">|  \___/|</span>____<span class="hljs-number">_</span><span class="hljs-params">|__|</span> <span class="hljs-params">|__|</span>____<span class="hljs-number">_</span><span class="hljs-params">|_____|</span>____<span class="hljs-number">_</span><span class="hljs-params">|
  |</span>   <span class="hljs-params">|   |</span>             The Serverless Application Framework
  <span class="hljs-params">|       |</span>                           serverless.com, v2.<span class="hljs-number">19.0</span>
   -------<span class="hljs-string">'

  Serverless: Successfully generated boilerplate for template: "aws-go"</span>
</code></pre><ul>
<li>When you use a template, a <em>Makefile</em> is generated for you, so you can build your app with this command:</li>
</ul>
<pre><code>$ <span class="hljs-built_in">make</span> build
</code></pre><ul>
<li>You can also <em>build and deploy</em> at the same time</li>
</ul>
<pre><code>$ <span class="hljs-built_in">make</span> deploy
</code></pre><ul>
<li>Only deploy the function. It usually takes some time when you deploy your entire app, but you have to do it only once unless you are adding new dependencies. Remember to build with <code>make build</code> first</li>
</ul>
<pre><code>$  sls deploy <span class="hljs-keyword">function</span> -f hello
</code></pre><ul>
<li>View the logs</li>
</ul>
<pre><code>$ sls logs -f hello -t
</code></pre><ul>
<li>And finally, remove the function</li>
</ul>
<pre><code>$ sls remove
</code></pre><h2 id="aws-lambda-opens-possibilities">AWS Lambda Opens Possibilities</h2>
<p>AWS Lambda is powering a lot of enterprises around the world. From running cloud platforms to extending legacy applications. In this article, we only cover the top of the iceberg, but there are still a lot of features, integrations, and services that can be used with it. I encourage you to explore and read more about what you can do with AWS Lambda and how can you build awesome and scalable web applications.</p>
]]></content:encoded></item><item><title><![CDATA[How to Soft Delete with MongoDB and Go]]></title><description><![CDATA[If you have to implement an API with CRUD operations on MongoDB with Go, but with the caveat that the documents on a collection had to be deleted using the  soft delete pattern, then continue reading to find out how. 

You can find the full source co...]]></description><link>https://arielorozco.com/how-to-soft-delete-with-mongodb-and-go</link><guid isPermaLink="true">https://arielorozco.com/how-to-soft-delete-with-mongodb-and-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Mon, 24 May 2021 03:05:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621825462841/tEU4dzumY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have to implement an API with CRUD operations on <strong>MongoDB</strong> with <strong>Go</strong>, but with the caveat that the documents on a collection had to be deleted using the  <a target="_blank" href="https://en.wiktionary.org/wiki/soft_deletion">soft delete</a> pattern, then continue reading to find out how. </p>
<blockquote>
<p>You can find the full source code here:
 <a target="_blank" href="https://github.com/arielcr/soft-delete-mongodb-go">https://github.com/arielcr/soft-delete-mongodb-go</a> </p>
</blockquote>
<p>If you are using a <em>SQL</em> database this is a common and easy task, and probably easier if you do it on any other language with a  <a target="_blank" href="https://laravel.com/">framework</a> . I searched about what was the best way to do this in <strong>MongoDB</strong>, and I found several implementation examples, but none of them were very clear or straightforward, and there were just a few examples in <strong>Go</strong>.</p>
<p>So, after looking at the  <a target="_blank" href="https://github.com/mongodb/mongo-go-driver">official MongoDB driver for Go</a> and the examples on the  <a target="_blank" href="https://docs.mongodb.com/drivers/go/">MongoDB documentation</a>, it all ends up on having a well-defined struct for your document with the right <em>json</em> and <em>bson</em> attributes.</p>
<p>So, let's say you have a <em>User</em> document, with the following struct:</p>
<pre><code><span class="hljs-keyword">type</span> <span class="hljs-keyword">User</span> struct {
    ID        primitive.ObjectID `<span class="hljs-type">json</span>:"id" bson:"_id"`
    <span class="hljs-type">Name</span>      string             `<span class="hljs-type">json</span>:"name" bson:"name"`
    Email     string             `<span class="hljs-type">json</span>:"email" bson:"email"`
}
</code></pre><p>If you want it to support the <em>soft delete</em> pattern, you have to include the <code>deleted_at</code> field:</p>
<pre><code><span class="hljs-keyword">type</span> <span class="hljs-keyword">User</span> struct {
    ID        primitive.ObjectID `<span class="hljs-type">json</span>:"id" bson:"_id"`
    <span class="hljs-type">Name</span>      string             `<span class="hljs-type">json</span>:"name" bson:"name"`
    Email     string             `<span class="hljs-type">json</span>:"email" bson:"email"`
    DeletedAt <span class="hljs-type">time</span>.Time          `<span class="hljs-type">json</span>:"-" bson:"deleted_at,omitempty"`
}
</code></pre><p>Notice how we are excluding this field from the <em>json</em> response with the <code>-</code> attribute because we don't want this to be returned as part of the response data, also take a look at the <code>omitempty</code> <em>bson</em> attribute, so this does not get into the document if it is not specified. </p>
<p>First, we insert our <em>User</em> (we don't have to include the <code>deleted_at</code> field):</p>
<pre><code><span class="hljs-keyword">user</span> := entities.<span class="hljs-keyword">User</span>{
        <span class="hljs-type">Name</span>:  "John Doe",
        Email: "john@doe.com",
    }

_, err := r.collection().InsertOne(ctx, <span class="hljs-keyword">user</span>)
</code></pre><p>We want to get only the documents that do not have the <code>deleted_at</code> field in them. We do this by defining the right filter when we get the data:</p>
<pre><code><span class="hljs-keyword">filter</span> := bson.M{
        "_id": userID,
        "deleted_at": bson.M{
            "$exists": <span class="hljs-keyword">false</span>,
        },
    }

err := r.collection().FindOne(ctx, <span class="hljs-keyword">filter</span>).Decode(&amp;<span class="hljs-keyword">user</span>)
</code></pre><p>The key here is to add the <code>"$exists": false</code> condition to the filter, so we only get the records where this field does not exist.</p>
<p>So, to delete a document we just create the <code>deleted_at</code> field:</p>
<pre><code><span class="hljs-keyword">filter</span> := bson.M{
        "_id": userID,
        "deleted_at": bson.M{
            "$exists": <span class="hljs-keyword">false</span>,
        },
    }
    updater := bson.D{
        primitive.E{
            Key: "$set",
            <span class="hljs-keyword">Value</span>: bson.D{
                primitive.E{
                    Key:   "deleted_at",
                    <span class="hljs-keyword">Value</span>: <span class="hljs-type">time</span>.Now(),
                },
            },
        },
    }

result, err := r.collection().UpdateOne(ctx, <span class="hljs-keyword">filter</span>, updater)
</code></pre><p>So, that's it, not too hard, but it was kind of difficult to find a suitable approach for Go.</p>
<p>Hope you find this useful!</p>
<p>There's a fully functional example for this here:  <a target="_blank" href="https://github.com/arielcr/soft-delete-mongodb-go">https://github.com/arielcr/soft-delete-mongodb-go</a> </p>
]]></content:encoded></item><item><title><![CDATA[Factory Method Design Pattern in Go]]></title><description><![CDATA[So, what is it about?
The Factory Method design pattern solves the problem of creating objects without specifying their concrete classes. It provides an interface to create them in a parent class but allows child classes to change the type of objects...]]></description><link>https://arielorozco.com/factory-method-design-pattern-in-go</link><guid isPermaLink="true">https://arielorozco.com/factory-method-design-pattern-in-go</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Go Language]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Sat, 08 May 2021 20:10:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620336576272/U4fVEfM7T.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="so-what-is-it-about">So, what is it about?</h3>
<p>The <strong>Factory Method</strong> design pattern solves the problem of creating objects without specifying their concrete classes. It provides an interface to create them in a parent class but allows child classes to change the type of objects that will be created.</p>
<h3 id="interesting-how-does-it-work">Interesting... How does it work?</h3>
<p><strong>Factory Method</strong> defines a <em>method</em> that should be used instead of the <em>new</em> operator. Child classes can override this method to change the class of the objects that will be created. </p>
<p>Here's a diagram to better understand it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620348972277/9TBMp1WCM.png" alt="DBClientFactory-Page-2.png" /></p>
<h3 id="amazing-but-how-do-i-do-that-in-go">Amazing! But how do I do that in Go?</h3>
<p>So, as you can see it is almost impossible to implement the classic <em>Factory Method</em> pattern in Go, mostly because we don't have some basic OOP features, like classes and inheritance. But, we can still implement a basic version of the pattern, called the <em>Simple Factory</em>. To do this we can make use of <em>composition</em> in Go since the end goal of it is the same as that of <em>inheritance</em>, so instead of inheriting features from a parent class, larger objects are composed of other objects and thereby use their functionality. </p>
<p>Here's how it looks like in Go:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620503118401/6IV-B0FJW.png" alt="DBClientFactory-Factory Method (Go).png" /></p>
<h3 id="show-me-some-code">Show me some code!</h3>
<p>So we're not going to deep dive into a "real world" example right now, since the idea here is to better understand the concept behind the pattern, so what we're going to do is to translate the diagram above into real code, so you can get a grasp on how it would look like (I'll give you some tips below on when it'll be a good idea to use the <em>Factory Method</em> design pattern).</p>
<p><strong>product_interface.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> factory

<span class="hljs-keyword">type</span> ProductInterface <span class="hljs-keyword">interface</span> {
    MakeSomething(<span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span>
}
</code></pre><p><strong>product.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> factory

<span class="hljs-keyword">type</span> Product <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">(p *Product)</span> <span class="hljs-title">MakeSomething</span><span class="hljs-params">(feature <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-keyword">return</span> feature + <span class="hljs-string">" "</span> + p.name
}
</code></pre><p><strong>producta.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> factory

<span class="hljs-keyword">type</span> ProductA <span class="hljs-keyword">struct</span> {
    Product
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewProductA</span><span class="hljs-params">()</span> <span class="hljs-title">ProductInterface</span></span> {
    <span class="hljs-keyword">return</span> &amp;ProductA{
        Product: Product{
            name: <span class="hljs-string">"Product A"</span>,
        },
    }
}
</code></pre><p><strong>productb.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> factory

<span class="hljs-keyword">type</span> ProductB <span class="hljs-keyword">struct</span> {
    Product
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewProductB</span><span class="hljs-params">()</span> <span class="hljs-title">ProductInterface</span></span> {
    <span class="hljs-keyword">return</span> &amp;ProductB{
        Product: Product{
            name: <span class="hljs-string">"Product B"</span>,
        },
    }
}
</code></pre><p><strong>creator.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> factory

<span class="hljs-keyword">type</span> ProductType <span class="hljs-keyword">int</span>

<span class="hljs-keyword">const</span> (
    ProductAType ProductType = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-literal">iota</span>
    ProductBType
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewProduct</span><span class="hljs-params">(t ProductType)</span> <span class="hljs-title">ProductInterface</span></span> {
    <span class="hljs-keyword">switch</span> t {
    <span class="hljs-keyword">case</span> ProductAType:
        <span class="hljs-keyword">return</span> NewProductA()
    <span class="hljs-keyword">case</span> ProductBType:
        <span class="hljs-keyword">return</span> NewProductB()
    <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">return</span> NewProductA()
    }
}
</code></pre><p><strong>main.go</strong></p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"github.com/arielcr/factory-method-go/factory"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    productA := factory.NewProduct(factory.ProductAType)
    fmt.Println(productA.MakeSomething(<span class="hljs-string">"Awesome"</span>))

    productB := factory.NewProduct(factory.ProductBType)
    fmt.Println(productB.MakeSomething(<span class="hljs-string">"Nice"</span>))

}
</code></pre><p>Here is the complete  <a target="_blank" href="https://github.com/arielcr/factory-method-go">code repo</a>.</p>
<h3 id="when-to-use-it">When to use it?</h3>
<ul>
<li><p><strong>When you don't know the exact types of objects your code should work with</strong>: since there is a separation from the code that creates the product from the one that actually uses it, it's easier to extend the construction code from the rest of the code. So if you want to add a new product type you just need to create the appropriate implementation.</p>
</li>
<li><p><strong>When you want to provide a way to extend your code when it's used by other users</strong>: it's easier for other developers to add additional functionality to your code since all that is needed is to add new classes (<em>structs</em>).</p>
</li>
</ul>
<h3 id="final-thoughts">Final Thoughts</h3>
<ul>
<li>By using the <strong>Factory Method Design Pattern</strong> you avoid tight coupling between the creator and the products</li>
<li>You are complying with the <strong>Single Responsibility Principle</strong> since you can move the product creation code into one place, making the code easier to support.</li>
<li>You are complying with the <strong>Open/Closed Principle</strong> because you can add new types of products into the program without breaking existing code.</li>
<li>One <em>"bad"</em> thing that I can think of is that your code becomes more complicated since you need to introduce new files and code to implement the pattern.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Trust In Your Commits]]></title><description><![CDATA[Recently I've been working on a new Go project, it must be shared across the team, and I wanted to be sure that all of the tests passed and have a goimports and golint run every time before a commit, just to have that pretty code and follow some stan...]]></description><link>https://arielorozco.com/trust-in-your-commits</link><guid isPermaLink="true">https://arielorozco.com/trust-in-your-commits</guid><category><![CDATA[Git]]></category><category><![CDATA[repository]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Wed, 22 Jul 2020 11:17:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620505834254/LSOHgziKG.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently I've been working on a new <em>Go</em> project, it must be shared across the team, and I wanted to be sure that all of the tests passed and have a <code>goimports</code> and <code>golint</code> run every time before a commit, just to have that pretty code and follow some standards.</p>
<p>I know this can be done with <a target="_blank" href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">git hooks</a>, but since the content of these need to be inside of the <code>.git</code> folder, it'll be hard to share across the repository and the team, and later if you want to make some changes on the hooks, it gets even harder!</p>
<p>I came across <a target="_blank" href="https://pre-commit.com/">pre-commit</a>, an awesome framework that helps you manage and maintain multi-language pre-commit hooks. It is fairly easy to install, works with <em>Go</em> out of the box, and once you have your configuration set in your <code>.pre-commit-config.yaml</code>, you just have to add it to your repo and just tell your team to <a target="_blank" href="https://pre-commit.com/#install">install pre-commit</a> and run <code>pre-commit install</code> on their project. That's it! Every time they <code>commit</code> to the repo the hooks that are set on the configuration file will be run.</p>
<p>The good thing about this framework is that it gets the hooks from remote repositories, you don't have to install anything or whatnot, so at the end, the <code>.pre-commit-config.yaml</code> acts pretty much like a <em>mod</em> file.</p>
<p>You can find multiple repositories that contain pretty good hooks for <em>Go</em> ready for <code>pre-commit</code>. My favorites are:</p>
<ul>
<li><a target="_blank" href="https://github.com/dnephin/pre-commit-golang">https://github.com/dnephin/pre-commit-golang</a></li>
<li><a target="_blank" href="https://github.com/Bahjat/pre-commit-golang">https://github.com/Bahjat/pre-commit-golang</a></li>
<li><a target="_blank" href="https://github.com/TekWizely/pre-commit-golang#go-fmt">https://github.com/TekWizely/pre-commit-golang#go-fmt</a></li>
</ul>
<p>You can decide which hooks to run from which repository, it's up to you. For example, I run hooks from two different because the one for unit tests does a better job on <em>Bahjat</em> repository.</p>
<p>This is the <code>.pre-commit-config.yaml</code> that I'm currently using:</p>
<pre><code><span class="hljs-attribute">repos</span>:
  - <span class="hljs-attribute">repo</span>: <span class="hljs-attribute">git</span>:<span class="hljs-comment">//github.com/dnephin/pre-commit-golang</span>
    <span class="hljs-attribute">rev</span>: master
    <span class="hljs-attribute">hooks</span>:
      - <span class="hljs-attribute">id</span>: go-imports
  - <span class="hljs-attribute">repo</span>: <span class="hljs-attribute">git</span>:<span class="hljs-comment">//github.com/Bahjat/pre-commit-golang</span>
    <span class="hljs-attribute">rev</span>: master
    <span class="hljs-attribute">hooks</span>:
      - <span class="hljs-attribute">id</span>: go-lint
      - <span class="hljs-attribute">id</span>: go-unit-tests
</code></pre><p>Feel free to grab it use it in your own projects, it works pretty fine for me!</p>
]]></content:encoded></item><item><title><![CDATA[The Adapter Design Pattern]]></title><description><![CDATA[We all use adapters in our daily life, when we want to connect a DVI monitor to a VGA port we need an adapter to do that, or when we want to use a microSD in a SD memory card. So guess what, we can do kind of the same thing using this design pattern....]]></description><link>https://arielorozco.com/the-adapter-design-pattern</link><guid isPermaLink="true">https://arielorozco.com/the-adapter-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Thu, 23 Nov 2017 19:49:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620506121946/l-g9D_HJR.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all use adapters in our daily life, when we want to connect a DVI monitor to a VGA port we need an adapter to do that, or when we want to use a microSD in a SD memory card. So guess what, we can do kind of the same thing using this design pattern.</p>
<p>An <strong>adapter</strong> allows you to translate one interface for use with another. Adapters basically allow objects to work together in a situation where they couldn't because of their different and incompatible interfaces. The adapter translates the calls to its interface into calls that the original interface understands. </p>
<p>To explain it a little bit better there's nothing like seeing it in action with an example. We're going to use PHP, but the same principles apply to any other language.</p>
<p>So imagine that someone gives you an old school Walkman, but you're a teenager that only knows how to use an iPod and <em>touch</em> buttons on the screen, so we're going to create an adapter for you, so you don't have to worry about how it works, you just <em>touch</em> on our <em>Walkman Adapter</em> and it does the job.</p>
<ol>
<li>First let's define our <strong>Walkman</strong> <em>Class</em> and <em>Interface</em>, so to keep it simple it just implements the <code>pressPlay()</code> function to start listening to music:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">WalkmanInterface</span> </span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">pressPlay</span>(<span class="hljs-params"></span>)</span>;

}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Walkman</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WalkmanInterface</span></span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">pressPlay</span>(<span class="hljs-params"></span>)</span>{

        <span class="hljs-keyword">echo</span> <span class="hljs-string">"Playing some music on the Walkman..."</span>;

    }

}
</code></pre>
<ol>
<li>Next we're going to take care of the <strong>iPod</strong> <em>Class</em> and <em>Interface</em> which implements the <code>touchPlay()</code> function to start listening music on the iPod:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">iPodInterface</span> </span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">touchPlay</span>(<span class="hljs-params"></span>)</span>;

}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">iPod</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">iPodInterface</span></span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">touchPlay</span>(<span class="hljs-params"></span>)</span>{

        <span class="hljs-keyword">echo</span> <span class="hljs-string">"Playing some music on the iPod..."</span>;

    }

}
</code></pre>
<ol>
<li>Now lets define our <strong>WalkmanAdapter</strong> <em>Class</em>. It must implement the <em>Interface</em> that we're currently using, in our case the <em>iPodInterface</em> and it must accept an <em>instance</em> of our <em>Walkman Class</em> on it's <em>constructor</em>. Remember we've to <a target="_blank" href="https://www.codeproject.com/Articles/702246/Program-to-Interface-not-Implementation-Beginners">program to an interface, not an implementation</a>. Watch how the <code>touchPlay()</code> function is <em>translated</em> into a <code>pressPlay()</code> Walkman function:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WalkmanAdapter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">iPodInterface</span> </span>{

    <span class="hljs-keyword">private</span> $walkman;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">WalkmanInterface $walkman</span>)</span>{

        <span class="hljs-keyword">$this</span>-&gt;walkman = $walkman;

    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">touchPlay</span>(<span class="hljs-params"></span>)</span>{

        <span class="hljs-keyword">$this</span>-&gt;walkman-&gt;pressPlay();

    }

}
</code></pre>
<ol>
<li>Finally let's just create a sample <strong>Person</strong> <em>Class</em> that will just <em>listen</em> to music on a specific device:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listen</span>(<span class="hljs-params">iPodInterface $ipod</span>)</span>{

        $ipod-&gt;touchPlay();

    }

}
</code></pre>
<ol>
<li>Now to test it out let's just tell our person to listen to music on the Walkman using the <em>Walkman Adapter</em> by creating a new instance of <em>WalkmanAdapter</em> and passing out an instance of <em>Walkman</em>, so the adapter will take care of <em>translating</em> the <em>touch</em> action into a <em>press</em> action:</li>
</ol>
<pre><code class="lang-php">$person = <span class="hljs-keyword">new</span> Person;

$person-&gt;listen(<span class="hljs-keyword">new</span> WalkmanAdapter(<span class="hljs-keyword">new</span> Walkman));
</code></pre>
<p>And the output will be:</p>
<pre><code><span class="hljs-attribute">Playing</span> some music <span class="hljs-literal">on</span> the Walkman...
</code></pre><p>You can run and view the full code here: <a target="_blank" href="http://codepad.org/vduny4f4">codepad.org/vduny4f4</a></p>
<p>And that's all! Painless code right?</p>
]]></content:encoded></item><item><title><![CDATA[The Decorator Design Pattern]]></title><description><![CDATA[The Decorator Pattern is a structural design pattern that has the ability to add behavior to an existing class dynamically.
We can use it to add additional features to objects without the need to heavily modify the underlying code using them.
This pa...]]></description><link>https://arielorozco.com/the-decorator-design-pattern</link><guid isPermaLink="true">https://arielorozco.com/the-decorator-design-pattern</guid><category><![CDATA[software architecture]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Sat, 18 Nov 2017 18:20:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620506460775/82-d1W53_.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Decorator Pattern is a <a target="_blank" href="https://www.javatpoint.com/structural-design-patterns">structural design pattern</a> that has the ability to add behavior to an existing class dynamically.</p>
<p>We can use it to add additional features to objects without the need to heavily modify the underlying code using them.</p>
<p>This pattern avoids using inheritance to add functionality that is not required. It prevents us to break the <a target="_blank" href="http://deviq.com/open-closed-principle/">Open-Closed</a> <a target="_blank" href="http://deviq.com/solid/">SOLID Principle</a>: <em>"An object or component should be open for extension but closed from modification"</em>. So, if we inherit from a class that we need to modify it several times to add functionality, then we're breaking this principle. When we use decorator, we extend that functionality to other classes.</p>
<p>So, ask yourself: <em>If I inherit from that class do I really need to pull in the entirety of that functionality, or do I simply need to adjust the behavior of one or two methods?</em> If that is the case then maybe you can refer to the <strong>Decorator Pattern</strong>.</p>
<p>So here's the pattern explained on PHP. We're going to use a <em>Coffee Service</em> implementation example, where you can order a single coffee and you also have the option to add milk, cinnamon, or both, then we can get the final cost and description. The idea is that we can understand this pattern by using the analogy of <em>decorating</em> the coffee.</p>
<ol>
<li>First we need an <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/concepts/interface.html">interface</a>, this is important because every Decorator Class needs to implement the same interface as the core class:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CoffeeService</span> </span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCost</span>(<span class="hljs-params"></span>)</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getDescription</span>(<span class="hljs-params"></span>)</span>;

}
</code></pre>
<ol>
<li>We create the basic class, in our case is the <code>SingleCoffee Class</code>:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SingleCoffee</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CoffeeService</span></span>{

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCost</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">15</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getDescription</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Single Coffee'</span>;
    }

}
</code></pre>
<ol>
<li>Then we create our first Decorator, it must implement the same interface as the SingleCoffee Class, and the constructor must accept an instance or implementation of the same contract:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Milk</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CoffeeService</span> </span>{

    <span class="hljs-keyword">protected</span> $coffeeService;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">CoffeeService $coffeeService</span>)</span>{
        <span class="hljs-keyword">$this</span>-&gt;coffeeService = $coffeeService;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCost</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">5</span> + <span class="hljs-keyword">$this</span>-&gt;coffeeService-&gt;getCost();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getDescription</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;coffeeService-&gt;getDescription() . <span class="hljs-string">', with milk'</span>;
    }

}
</code></pre>
<ol>
<li>We create our final decorator class:</li>
</ol>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cinnamon</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CoffeeService</span> </span>{

    <span class="hljs-keyword">protected</span> $coffeeService;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">CoffeeService $carService</span>)</span>{
        <span class="hljs-keyword">$this</span>-&gt;coffeeService = $coffeeService;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCost</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> + <span class="hljs-keyword">$this</span>-&gt;coffeeService-&gt;getCost();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getDescription</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;coffeeService-&gt;getDescription() . <span class="hljs-string">', with cinammon'</span>;
    }

}
</code></pre>
<p>Finally, to run our code, create an instance of our basic class and wrap it with the decorators that we want:</p>
<pre><code class="lang-php">$coffeeService = <span class="hljs-keyword">new</span> Cinnamon(<span class="hljs-keyword">new</span> Milk(<span class="hljs-keyword">new</span> SingleCoffee));

<span class="hljs-keyword">echo</span> $coffeeService-&gt;getCost();

<span class="hljs-keyword">echo</span> $coffeeService-&gt;getDescription();
</code></pre>
<p>The output of this would be:</p>
<pre><code><span class="hljs-number">22</span> Single Coffee, <span class="hljs-keyword">with</span> milk, <span class="hljs-keyword">with</span> cinnamon
</code></pre><p>You can run and view the full code here: <a target="_blank" href="http://codepad.org/at37vpqW">codepad.org/at37vpqW</a></p>
<p>And that's all! Painless code right?</p>
]]></content:encoded></item><item><title><![CDATA[What is a Design Pattern?]]></title><description><![CDATA[A design pattern is a reusable solution that can be applied to commonly occurring problems in software development, think of them as templates for solving problems.
They're proven solutions that can be easily reused and provide solid approaches to so...]]></description><link>https://arielorozco.com/what-is-a-design-pattern</link><guid isPermaLink="true">https://arielorozco.com/what-is-a-design-pattern</guid><category><![CDATA[software architecture]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Ariel Orozco]]></dc:creator><pubDate>Sat, 18 Nov 2017 11:06:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620506739359/UhPQH7lT9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A design pattern is a reusable solution that can be applied to commonly occurring problems in software development, think of them as templates for solving problems.</p>
<p>They're proven solutions that can be easily reused and provide solid approaches to solve issues in software development, they usually are an out-of-the-box solution that can be adapted to suit our own needs.</p>
<p>It's important to remember that they're <strong>not an exact solution</strong>, their function is to provide us with a <strong>solution scheme</strong>.</p>
<p>Design Patterns can be divided into several categories, we're going to dig into some of them and look at the most commonly used ones. For the examples, I'm going to use <a target="_blank" href="http://php.net">PHP</a>, but the logic can be applied to any existing <a target="_blank" href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> language.</p>
<ul>
<li><p><strong>Creational Design Patterns</strong></p>
<ul>
<li><p>Constructor</p>
</li>
<li><p>Factory</p>
</li>
<li><p>Abstract</p>
</li>
<li><p>Prototype</p>
</li>
<li><p>Singleton</p>
</li>
<li><p>Builder</p>
</li>
</ul>
</li>
<li><p><strong>Structural Design Patterns</strong></p>
<ul>
<li><p>Decorator</p>
</li>
<li><p>Facade</p>
</li>
<li><p>Flyweight</p>
</li>
<li><p>Adapter</p>
</li>
<li><p>Proxy</p>
</li>
</ul>
</li>
<li><p><strong>Behavioral Design Patterns</strong></p>
<ul>
<li><p>Iterator</p>
</li>
<li><p>Mediator</p>
</li>
<li><p>Observer</p>
</li>
<li><p>Visitor</p>
</li>
</ul>
</li>
</ul>
]]></content:encoded></item></channel></rss>