<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Epps on Medium]]></title>
        <description><![CDATA[Stories by Michael Epps on Medium]]></description>
        <link>https://medium.com/@michael_epps?source=rss-7d78e79e1464------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*azA__hZS6kQbXde_TLv4rw.jpeg</url>
            <title>Stories by Michael Epps on Medium</title>
            <link>https://medium.com/@michael_epps?source=rss-7d78e79e1464------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michael_epps/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Avoiding Java-isms: The Checker Class]]></title>
            <link>https://medium.com/@michael_epps/avoiding-java-isms-the-checker-class-93dee002ac09?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/93dee002ac09</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 22:25:19 GMT</pubDate>
            <atom:updated>2023-04-05T22:25:19.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*UVFIuyptsAS4tArGS-tv4Q.jpeg" /></figure><p>Often times in our code we need to validate a set of conditions around an object that must be true before the code continues. This can be validation rules, configuration rules, invariants, or whatever flavor of checks that need to be performed in your app. Mysteriously, or maybe not so depending on your adherence to “Clean code”, these checks do not take the form of simple boolean statements or even functions. Instead they take the form of a Java-ism called <strong>The Checker Class.</strong></p><p>The Checker class can come in many names: Checker, Validator, Rule, etc. In general though, it will take form in an innocent looking interface which for our purposes will be called ConditionChecker</p><pre>public interface ConditionChecker {<br>    boolean check(MyObject obj)<br>}</pre><p>ConditionChecker and things like it are a class that does one thing and one thing only — check a condition, usually the state of some object being passed in.</p><p>Let’s make this a bit more concrete.</p><h4>A Java Hotel</h4><p>Say you are working on a hotel room booking system. When a prospective customer visits the hotel’s website they wish to be given a list of rooms to choose from that match their stay duration and room preferences. To generate this list of possible rooms, your system must apply a few rules based on the customer’s input:</p><ol><li>The room must not be already booked by another customer during the days the customer wishes to book the room.</li><li>The hotel must be open during the days the customer wishes to book the room.</li><li>The room must be at least one of customer preferred types (queen, king, suite)</li><li>The room must be within a price range set by the customer</li></ol><p>When the customer clicks the “Show me possible rooms” button a request is sent to the server. Then inside the server code you have RoomListingService that’s responsible for taking these rules and filtering out the possible list of rooms</p><pre>public final class RoomListingServiceImpl implements RoomListingService {<br>    <br>    private final RoomRepository roomRepository;<br><br>    // constructors and other methods left out for brevity<br><br>    @Override<br>    public List&lt;Room&gt; listRooms(final CustomerPreferences customerPreferences) {<br>        // For simplicity sake, getRooms just returns an immutable list<br>        // of all rooms the hotel has.<br>        final var possibleRooms = roomRepository.getRooms();<br>                <br>        // Filter out possible rooms<br>        final var filteredRooms = ...What Do we do here?<br><br>        return filteredRooms;<br>    }<br>}</pre><p>This is the point at which this Java-ism takes place. Most engineers have some desire to make this extensible and easy to real — “Clean Code” enthusiasts doubly so. Between DRY, Single Responsibility Principal, and an innate desire to make small, simple methods we reach for an abstraction to “take all the messy rules” and stuff them somewhere else. This is where <strong>The Checker Class</strong> is born.</p><p>Let’s take a look at a possible checker class for this system:</p><pre>public interface RoomFilter {<br>    boolean isRoomAvailable(Room room, CustomerPreferences customerPreferences);<br>}</pre><p>As said before, this type of class can take many forms. In this example, it has taken the form of a filter.</p><p>Let’s write an implementation of this class for one of our rules.</p><pre>public class PriceRangeRoomFilter implements RoomFilter {<br>    <br>    @Override<br>    public boolean isRoomAvailable(<br>        final Room room, <br>        final CustomerPreferences customerPreferences<br>    ) {<br>        return room.getCurrentPrice() &gt;= customerPreferences.getMinPrice()<br>            &amp;&amp; room.getCurrentPrice() &lt;= customerPreferences.getMaxPrice();<br>    }<br>}</pre><p>Now let’s change our service impl to utilize these filters.</p><pre>public final class RoomListingServiceImpl implements RoomListingService {<br>    <br>    private final RoomRepository roomRepository;<br>    private final List&lt;RoomFilter&gt; roomFilters;<br><br>    // constructors and other methods left out for brevity<br><br>    @Override<br>    public List&lt;Room&gt; listRooms(final CustomerPreferences customerPreferences) {<br>        // For simplicity sake, getRooms just returns an immutable list<br>        // of all rooms the hotel has.<br>        final var possibleRooms = roomRepository.getRooms();<br>                <br>        // Filter out possible rooms<br>        final var filteredRooms = possibleRooms.stream()<br>                     .filter(room -&gt; roomFilters.stream().anyMatch(filter -&gt; filter.isRoomAvailable(room, customerPreferences))<br>                     .toList();<br>        return filteredRooms;<br>    }<br>}</pre><p>We register the filters in whichever dependency injection framework and presto! We now have rooms being filtered by a selection of filters, everything has a single responsibility, we can add more filters easily, and we have some nice functional code. Job well done.</p><p>What’s the problem then?</p><h4>Be Clear, not Clever</h4><p>The answer to that question is clarity. If we want to know what exactly this class is doing how many different places do we have to check? Obviously the class it self is filtering rooms based on some filters. We need to know what filters so we go check wherever we register our dependency injection. Now we have a list of filters, and we can go check each one to determine what they are doing.</p><p>In total, to understand this simple system, we would need to check a minimum of 6 different classes at once.</p><p>This number only gets worse as rule list grows. A spiderweb of complexity is created that I and others I have talked to struggle to hold all in our minds at once.</p><p>Thankfully, the most I’ve personally seen is 9 of these rules at once.</p><h3>What to do instead?</h3><p>If we take a look at what we are actually trying to say with this set of RoomFilter classes we can gleam hidden knowledge of our system.</p><p>Let’s take a look at our price filter class again:</p><pre>public class PriceRangeRoomFilter implements RoomFilter {<br>    <br>    @Override<br>    public boolean isRoomAvailable(<br>        final Room room, <br>        final CustomerPreferences customerPreferences<br>    ) {<br>        return room.getCurrentPrice() &gt;= customerPreferences.getMinPrice()<br>            &amp;&amp; room.getCurrentPrice() &lt;= customerPreferences.getMaxPrice();<br>    }<br>}</pre><p>All this class is is a function wrapped inside an OOP trenchcoat.</p><p>Let’s rewrite these classes as static functions inside a RoomFilters class for now.</p><pre>public static class RoomFilters {<br>    <br>    public static boolean isRoomWithinPriceRange(<br>        final Room room,<br>        final CustomerPreferences customerPreferences<br>    ) {<br>        return room.getCurrentPrice() &gt;= customerPreferences.getMinPrice()<br>            &amp;&amp; room.getCurrentPrice() &lt;= customerPreferences.getMaxPrice();<br>    }    // The other filter functions<br>}</pre><p>Then let’s rewrite our service impl one more time.</p><pre>public final class RoomListingServiceImpl implements RoomListingService {<br>    <br>    private final RoomRepository roomRepository;<br><br>   // constructors and other methods left out for brevity<br><br>    @Override<br>    public List&lt;Room&gt; listRooms(final CustomerPreferences customerPreferences) {<br>        // For simplicity sake, getRooms just returns an immutable list<br>        // of all rooms the hotel has.<br>        final var possibleRooms = roomRepository.getRooms();<br>                <br>        // Filter out possible rooms<br>        final var filteredRooms = possibleRooms.stream()<br>                     .filter(room -&gt; RoomFilters.IsRoomWithinPriceRange(room,customerPreferences)<br>                     .filter(room -&gt; RoomFilters.IsRoomAvailableDuringDateRange(room, customerPreferences)<br>                     // Other filters left out for brevity<br>                     .toList();<br>        return filteredRooms;<br>    }<br>}</pre><p>We don’t have to stop here though. Look at all at filters — in each one we are asking the room to give us data that we then use to make a decision. What if we instead encode these rules onto the room type itself, then we can just call the methods on room object to act as filters!</p><p>As an extra step, lets decompose the customerPreferences object into the values the methods need. This allows the Room object to not be dependent on the CustomerPreferences — testing will be much easier this way.</p><pre>public class Room {<br>    public boolean isWithinPriceRange(final int minPrice, final int maxPrice) {<br>        return this.currentPrice &gt;= minPrice &amp;&amp; this.currentPrice &lt;= maxPrice;<br>    }<br>    // Other methods excluded for brevity<br>}</pre><p>Now everywhere in our system we can access these questions about a Room as long as we have a Room object. The rules — the domain language — is baked into the Room object.</p><p>Once again, let’s rewrite our service impl.</p><pre>public final class RoomListingServiceImpl implements RoomListingService {<br>    <br>    private final RoomRepository roomRepository;<br><br>   // constructors and other methods left out for brevity<br><br>    @Override<br>    public List&lt;Room&gt; listRooms(final CustomerPreferences customerPreferences) {<br>        // For simplicity sake, getRooms just returns an immutable list<br>        // of all rooms the hotel has.<br>        final var possibleRooms = roomRepository.getRooms();<br>                <br>        // Filter out possible rooms<br>        final var filteredRooms = possibleRooms.stream()<br>                     .filter(room -&gt; room.isWithinPriceRange(customerPreferences.getMinPrice(), customerPreferences.getMaxPrice())<br>                     .filter(room -&gt; room.isAvailableDuringDateRange(customerPreferences.getDateRangeStart(), customerPreferences.getDataRangeEnd())<br>                     // Other filters left out for brevity<br>                     .toList();<br>        return filteredRooms;<br>    }<br>}</pre><p>This code is now incredibly clear. We can see from reading the service impl exactly our filter rules. As a bonus, we can reuse these rules elsewhere in the system easily.</p><p>When we think about how many classes we have to check to understand this filtering it has been reduced down to exactly two — The service impl and the Room class.</p><p>This is the cost of <strong>The Checker Class</strong>. The rules around your objects get scattered about in disparate classes instead of encoded into the objects they belong to, you lose the ability to know what exactly is going on in the code at a glance, and it becomes a spiderweb of classes you have to check to understand a supposedly “clean” part of your system.</p><p>For the record, this system is still DRY and adhering to Single Responsibility Principal. I’d call that a win.</p><h4>Where Should We Use A Checker Class?</h4><p>As with all good ideas, there’s usually a caveat or two. I do think that there are a couple cases where <strong>The Checker Class</strong> makes sense. These are large rule based systems that are configurable. In these types of systems its not entirely possible to encode these rules on types and maintain the configurability. If you work on one of these systems, then more power to you.</p><p><em>If you enjoyed this article, please follow my page for more on software design!</em></p><p><a href="https://medium.com/@michael_epps">https://medium.com/@michael_epps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93dee002ac09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context-less Go — Writing HTTP Services Easily]]></title>
            <link>https://medium.com/better-programming/context-less-go-854db3e5510?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/854db3e5510</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 22:08:24 GMT</pubDate>
            <atom:updated>2022-12-22T08:37:45.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop using context as an IoC and start writing HTTP services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPgNYNZfXsRCkyW-noZ7CQ.png" /></figure><p>One of the things that many Go developers, especially new ones, find non-obvious is: how the heck to pass all the things I need into my handlers?</p><p>We don’t have fancy Inversion of Control systems like in Java or C#. http.Handlers are static signatures so I can&#39;t just pass in what I really want. It seems we only have 3 options:</p><ul><li>use globals</li><li>wrap handlers in a function</li><li>or pass things down in context.Context!</li></ul><p>Let&#39;s look at all three of these options.</p><h3><strong>A Little Context</strong></h3><p>— <em>Pun Definitely Intended</em></p><p>The handler we are writing is something you would see at your everyday, normal e-commerce shop.</p><p>Our task is to write an endpoint that given some category ID, returns a list of items in that category.</p><p>This endpoint will need to access our items.Serviceto do the actual lookup, logging.Service in case things go wrong, and metrics.Service to get them sweet marketing metrics!</p><h3><strong>Globals</strong></h3><p><em>— Call Me Mr. Worldwide</em></p><p>Our first attempt at getting things into our handlers is with globals. This is a fairly natural way of doing this that many beginners tend to do.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f4000a46f6184b6438118cc113970c1/href">https://medium.com/media/1f4000a46f6184b6438118cc113970c1/href</a></iframe><p>We all have written code like this at one point or another. Then we all quickly learned that globals are bad since they make inflexible, untestable code.</p><p>This naturally leads to a rabbit hole of books, articles, videos, and more that tells you “inject your dependencies!”. This code just won&#39;t do, let&#39;s try a bit of injection.</p><h3><strong>Dependency Injection</strong></h3><p><em>— Getting your Booster</em></p><p>Well, we don’t want to use globals, but http.Handler has a fixed signature. So how do we do this? We wrap it of course!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f644fd9efa67a3aa33d1148a80b7d119/href">https://medium.com/media/f644fd9efa67a3aa33d1148a80b7d119/href</a></iframe><p>This is <em>better </em>since we are no longer relying on the global state, but it still leaves a lot to be desired. Mainly, it makes every handler into a big, long, annoying mess to write. It&#39;s easy to imagine this signature getting 2–3 times longer if we add another few services.</p><p>So we read around and find out our *http.Request has a context.Context inside it! We can create a middleware, and inject all of our dependencies, then the handler can just pull what it needs! This surely will solve all of our problems!</p><h3><strong><em>Context</em></strong></h3><p>— <em>Now in Color!</em></p><p>First, let&#39;s make that middleware we were talking about. We are just going to do this inline after we set up all our dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54bfb5f6836aea7de9df857978323eef/href">https://medium.com/media/54bfb5f6836aea7de9df857978323eef/href</a></iframe><p>Now that we have all that added we can redo our handler once again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a775aecf5de28d67e419587447793a3a/href">https://medium.com/media/a775aecf5de28d67e419587447793a3a/href</a></iframe><p>Nice and easy! Nothing can go wrong here. Well, except when 3 months down the line someone moves a line of code elsewhere in the app and one of these services no longer exists in the context.</p><p>“Well Mr. Smart Medium Writer I’ll just check to make sure!” you may say.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867b8f4d0098ba9da229395b5557d192/href">https://medium.com/media/867b8f4d0098ba9da229395b5557d192/href</a></iframe><p>As you can see even in small, simple, contrived examples it becomes a bit mess to do this in a safe manner.</p><p>One of the reasons we use Go is to avoid all these types of checking messes! By using context as some sort of grab bag for our dependencies we effectively give up on type safety. In addition, we don’t know if things exist until runtime. To fix that we end up with long strings of error checking everywhere.</p><p>This is no good. All three of our options suck in their own way. It seems we can’t escape the verbosity hell if we want to inject our dependencies. Sure you can hack around these problems and create fancy functions that wrap a lot of this, but it&#39;s not actually solving the problem.</p><p>Unless there is a fourth way ….?</p><h3><strong>Structs</strong></h3><p>— <em>Adding structure to your handlers…</em></p><p>Some of you may have been screaming at me to get to this already but having taught this subject a good few times it really helps to see the other solutions first.</p><p>The “fourth way” we did not consider is actually quite simple.</p><ol><li>We create a struct that holds the dependencies we need.</li><li>We add our handlers as methods on that struct</li></ol><p>Let&#39;s take a look at an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e130d6da5b4732a82781d4f79e7bcd2/href">https://medium.com/media/5e130d6da5b4732a82781d4f79e7bcd2/href</a></iframe><p>This solution has a few great benefits:</p><ol><li>Everything we depend on is known at build time and is type-safe (unlike contexts)</li><li>We have minimal extra boilerplate (unlike wrapper functions)</li><li>Maintains testability (unlike globals)</li><li>Allows us to “group” related handlers into units</li></ol><p>4 is one we haven’t touched on yet, but now that we have this struct we can create groupings of handlers that share common dependencies or just go together logically.</p><p>For instance, we may add a handler to add a new category on here. We may create a MetricsHandler to group all of the endpoints related to metrics together. You can be as granular or broad with this as you wish (<em>granular, is probably, better in most cases</em>).</p><h3><strong>Conclusion</strong></h3><p><em>Who even reads this far?</em></p><p>We finally have our goal. Our boss at the totally-contrived e-commerce shop will be happy that the endpoint is ready (baring some testing). We can move on to the next task.</p><p>This is not a new or even novel idea. If you look at classic go example posts such as things such as <a href="https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html">https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html</a> and <a href="https://github.com/benbjohnson/wtf/">https://github.com/benbjohnson/wtf/</a> you will see these ideas in action.</p><p>It is a great and, I think, non-obvious solution though.</p><p>Of course, we can use interfaces and the like to make this even more testable, but that’s another article!</p><p>Thanks for reading!</p><pre><strong>Want to Connect?</strong></pre><pre>Come join the Go Discord server at <a href="https://discord.gg/golang">https://discord.gg/golang</a>!</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=854db3e5510" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/context-less-go-854db3e5510">Context-less Go — Writing HTTP Services Easily</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Generics In 5 Minutes Or Less]]></title>
            <link>https://medium.com/@michael_epps/go-generics-in-5-minutes-or-less-6942ac7713b7?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/6942ac7713b7</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 12:30:05 GMT</pubDate>
            <atom:updated>2022-03-22T13:43:16.818Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick primer on Go generics in Go 1.18+</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mBRgLntgcEWN8HJLry3AA.png" /><figcaption>No Money Back Guarantees!</figcaption></figure><p><strong>Introduction</strong></p><p>Starting in Go 1.18, generic types have been introduced.</p><p>These are compile time type parameters for your types, methods, and functions. They exceptionally useful for reducing code duplication and providing stronger typing.</p><p>If you don’t know what that means, don’t worry we will get there!</p><p><strong>A Function</strong></p><p>Given the function</p><pre>func Foo(t any) { }</pre><p>we can make it generic by adding [T any] to the signature like so</p><pre>func Foo[T any](t T) {}</pre><p>We then can call the function with the concrete type we want</p><p>F[string](“hello, generics!”) // t is a string at compile time</p><p><strong>A Struct</strong></p><p>Given a type</p><pre>type Bar struct {<br>    t any<br>}</pre><p>we can make it generic like so</p><pre>type Bar[T any] struct {<br>    t T<br>}</pre><p>and then create an instance with the concrete type we want</p><pre>b := Bar[string] {</pre><pre>t: &quot;hello, generics&quot; // b.t is a string type<br>}</pre><p>b.t is a string at runtime in this example</p><p><strong>A Method</strong></p><p>Unfortunately, methods cannot have generics. They only can utilize generics introduced on the type they are on. Following our example above, we can define a generic method like so</p><pre>func (b Bar[T]) Foo() { }</pre><p><strong>An Interface</strong></p><p>Interfaces work the exact same as structs.</p><p>Given an interface</p><pre>type Fooer interface {<br>    Bar(any)</pre><pre>}</pre><p>we can make this generic like so</p><pre>type Fooer[T any] interface {<br>    Foo(T)</pre><pre>}</pre><p>and then create an instance and call the method</p><pre>// StringFooer is a struct with the method Foo(string)<br>var f Fooer[string] := StringFooer{}<br>f.Foo(&quot;hello, generics&quot;)</pre><p><strong>Constraints</strong></p><p>The [T any] we have been using constrains T to the type of any .</p><p>We can constrain T to other types also</p><pre>[T any] // T can be any type<br>[T int] // T can only be an int<br>[T ~int] // T can only be an int OR any type with an underlying type of int, e.g. type I int<br>T[T int | string] // T can only be an int OR string<br>T[T io.Reader] // T can be any type that implements io.Reader</pre><p>Sometimes you want to define a constraint for many types, or just want to define it once.</p><p>We can use the interface syntax for that</p><pre>type Float interface {<br>	~float32 | ~float64<br>}</pre><p><em>Important to note here: This is a constraint, </em><strong><em>NOT</em></strong><em> an interface. You can use an interface as a constraint but you cannot use a constraint as an interface!</em></p><p>which we can then use as</p><pre>[T Float] // Reader challenge: what types are accepted here?</pre><p><strong>Predefined Constraints</strong></p><p>The stdlib provides some predefined contraints such as comparable .</p><p>Additional ones can be found at <a href="https://pkg.go.dev/golang.org/x/exp/constraints">https://pkg.go.dev/golang.org/x/exp/constraints</a> until these are merged into the stdlib (1.19+).</p><p><strong>Conclusion</strong></p><p>That is basically all you need to know about generics in Go to get started.</p><p>If you have anything that you feel should be included, please leave a comment.</p><p>If you found this information useful and want to discuss more about Go, join me and others on the Go Discord Server at <a href="https://discord.gg/golang">discord.gg/golang</a></p><p>Be sure to leave a 👏 and follow for more Go content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6942ac7713b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Module, Single Workspace]]></title>
            <link>https://medium.com/@michael_epps/multi-module-single-workspace-3493528555ad?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/3493528555ad</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 09:29:40 GMT</pubDate>
            <atom:updated>2022-03-20T09:29:40.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Utilizing go.work to simplify working with multiple go modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehaChlvaWexkTd16o-7cbA.png" /></figure><p>Working with multiple modules in go can be a real chore. Especially when you have one module that depends on another, and you need to edit both of them at the same time!</p><p>You edit the parent module, but then you need to push it to the repo. Then run update in the dependent module to download the new version. Then finally be able to use the 2 line fix you needed. A real pain to say the least.</p><p>Prior to Go 1.18, the recommended way to deal with this using a <a href="https://thewebivore.com/using-replace-in-go-mod-to-point-to-your-local-module/">replace directive</a> in the dependent module.</p><p>This worked, but has its own problems such as needing to edit your go.mod manually, making sure you don’t commit the replace, and more.</p><p>Finally, starting in Go 1.18 a new way to work with multiple modules at once was introduced which has eliminated these problems: go.work</p><p><strong>What the heck is a go.work?</strong></p><p>Like your go.mod file, a go.work file is a special file for the Go tool chain. It allows you to specify a local “workspace” of modules.</p><p>In other-words, it allows you to say “I am working on these sets of modules together, locally”</p><p><strong>Defining the workspace</strong></p><p>Let’s pretend we have two modules we want to work on: one a library and one a server.</p><pre><br>├── library<br>│   └── go.mod<br>└── server<br>    └── go.mod</pre><p>server is dependent on library for the purposes of this example.</p><p>In the parent directory of these two modules we can run go work init ./library ./server .</p><p><em>You technically can use any directory here, but just to make things simple we are using the parent directory for these projects.</em></p><p>This will create a new go.work file with the following contents:</p><pre>go 1.18</pre><pre>use (</pre><pre>    ./library/</pre><pre>    ./server/</pre><pre>)</pre><p>We have now defined a workspace of library and server!</p><p><strong>Free To Change</strong></p><p>Without changing anything about library and server&#39;s go.mod definitions we can now edit both modules freely. Changed code in library will instantly be available in server as we had with the replace directive.</p><p>For more information and commands see the docs on go work at <a href="https://go.dev/ref/mod#go-work-init">https://go.dev/ref/mod#go-work-init</a>.</p><p>If you found this information useful and want to discuss more about Go, join me and others on the Go Discord Server at <a href="https://discord.gg/golang">discord.gg/golang</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3493528555ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye interface{}, Hello any]]></title>
            <link>https://medium.com/@michael_epps/goodbye-interface-hello-any-8b414b33bce5?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b414b33bce5</guid>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 06:56:12 GMT</pubDate>
            <atom:updated>2022-03-22T11:45:43.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Moving from interface{} to any in Go 1.18+</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOMsEXwQM3uXr8xMi3nWyA.png" /></figure><p><strong>A New Era</strong></p><p>Since Go 1.18, there exists an <a href="https://pkg.go.dev/builtin#any">alias</a> for interface{} called any</p><pre>type any = interface{}</pre><p>With this the Go stdlib has <a href="https://github.com/golang/go/issues/49884">replaced all references</a> to interface{} with any. This is now the standard way to use this type.</p><p><strong>Updating Your Code</strong></p><p>Updating your code can be done with one simple command:</p><p>gofmt -r &#39;interface{} -&gt; any&#39; -w *.go</p><p>Simply run this within your Go project to rewrite all interface{} to any.</p><p><em>To do a dry run replace </em><em>-w with </em><em>-l</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*PnymOOBRMBmp-XYF.gif" /></figure><p>If you found this information useful and want to discuss more about Go, join me and others on the Go Discord Server at <a href="https://discord.gg/golang">discord.gg/golang</a></p><p>If you enjoyed this story, you may enjoy this one on using go.work in Go 1.18 <a href="https://medium.com/p/3493528555ad">https://medium.com/p/3493528555ad</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b414b33bce5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Interface Or Two Will Do: Go’s Most Powerful Feature]]></title>
            <link>https://medium.com/@michael_epps/an-interface-or-two-will-do-gos-most-powerful-feature-6e3b3ac08f9d?source=rss-7d78e79e1464------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e3b3ac08f9d</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michael Epps]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 18:01:43 GMT</pubDate>
            <atom:updated>2021-09-22T18:01:43.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wX0iKpQ9UDB1vMb4UNhOQ.png" /></figure><p>Everyone knows interfaces by now right? You know, those fancy things that you see being used all the time.</p><p>People tell you to use them to “decouple your code”, or maybe to “make it easier to test”. So many reasons given on why to use interfaces, but no one ever seems to explain how to use them!</p><p>If this sounds like where you are on your Go journey then lets dive into both the why and HOW of Go’s most powerful feature.</p><h3>The Interface And You</h3><p>An interface in Go is a way of describing what an object can do (its methods). I think this is the most important point to understand, and bears repeating.</p><blockquote>An interface in Go is a way of describing what an object can do</blockquote><p>An interface says “hey any object that implements me can do these things”. If we look at the io.Reader interface it is simply:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2fd3a2b083a27755329f7cbb876340b/href">https://medium.com/media/f2fd3a2b083a27755329f7cbb876340b/href</a></iframe><p>What is this actually <em>saying </em>though? It’s fairly straight forward. io.Reader is saying “anything that implements me can be read”</p><p>This is one of the largest ideas behind interfaces in Go. Structs describe both what an object can do and how it does it. Interfaces describe <strong>purely </strong>what an object can do.</p><p>By only describing what an object can do, not how it does it, interfaces decouple the use of a method from how its actually works. That is where the power of interfaces comes from.</p><p>Now, with an understanding of what interfaces are, we can dive deeper into how and why we use them.</p><h3>What do I care about?</h3><p>We now understand what interfaces are saying. Now it is critical that we understand how to use them.</p><p>Lets look at a basic function that copies the contents of one *os.File into another *os.File</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f44472bd0033e165449a268cddeff7/href">https://medium.com/media/e8f44472bd0033e165449a268cddeff7/href</a></iframe><p>Code like this is everywhere in our codebases. There is nothing necessarily wrong about this code, but if we tried testing this code like everyone says we should it would be a huge pain. We would have to create some temporary files on disk, do whole bunch of fancy stuff to ensure they are deleted, somehow check if the copy was actually done correctly, and is all around a huge P.I.T.A.</p><p>From all the advice we have heard before, we know that somehow interfaces are supposed to make this better. How though? Where do you use them here?</p><p>This is where the magic trick I’ve developed comes into play. It is a simple question you can ask of any piece of code that takes in an object. It so good that I’m even going to quote it just to make emphasize it.</p><blockquote>What functionality of my inputs does this actually care about?</blockquote><p>“this” being the function, method, struct, etc. in question.</p><p>In my humble opinion, this question strikes right at the heart of why we use interfaces discussed previously. We care about <em>what </em>an object can do <em>not how </em>it does it.</p><p>So lets look at this code and ask that question: What functionality of the inputs does this function care about?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f44472bd0033e165449a268cddeff7/href">https://medium.com/media/e8f44472bd0033e165449a268cddeff7/href</a></iframe><p>Well, for from we care that we can Read it, and for to we care that we can Write it. That’s all. We do not care how Read or Write actually are implemented. That is the key here. When we only care what an object can do, not how it does it we can utilize interfaces.</p><p>Luckily for us the stdlib provides two interfaces for exactly these two use cases: io.Reader and io.Writer. Let’s replace the two *os.File with these interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5553d392d051864ea1dd35aea9376917/href">https://medium.com/media/5553d392d051864ea1dd35aea9376917/href</a></iframe><p>This is actually testable. Just make two buffers in memory, add data to one, copy, check the contents of the other. Simple, elegant, clean. That is the power of interfaces.</p><p>I don’t want to get too far into this in this article, but the question we posed also gives us clear insight into when <strong>not </strong>to use interfaces. This is when we do care about specific implementations or fields of a struct. You can abstract some of that away, but sometimes you really just gotta take in a struct.</p><h3>Conclusion</h3><p>This article has already covered a lot. First we learned that interfaces say what an object can do. They do not say how. This distinction allows us to decouple the use of a method from how its actually works.</p><p>We also learned how we can examine our code to make use of interfaces. By asking “What functionality of my inputs does this actually care about?” with the inputs in mind we can easily determine where we care that an object can do something vs how an object does something.</p><p>There is still much more to cover with interfaces in Go. The next article will be covering the cases in which we do not have premade interfaces and have to make our own. Be on the lookout for that coming soon.</p><p>I hope this article helps your understanding of interfaces in Go. If you need more help or want to ask me a question, come visit the Go Discord server at <a href="https://discord.gg/jVQ9R4fT">https://discord.gg/golang</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e3b3ac08f9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>