<?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 William Jackson on Medium]]></title>
        <description><![CDATA[Stories by William Jackson on Medium]]></description>
        <link>https://medium.com/@william746a?source=rss-a3d7985086c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mq8cG3mYvvBa65cQdZP48A.png</url>
            <title>Stories by William Jackson on Medium</title>
            <link>https://medium.com/@william746a?source=rss-a3d7985086c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:38:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@william746a/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[When Inheritance is a Good Thing]]></title>
            <link>https://medium.com/@william746a/when-inheritance-is-a-good-thing-2d29a596a00f?source=rss-a3d7985086c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d29a596a00f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[William Jackson]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 23:59:29 GMT</pubDate>
            <atom:updated>2025-03-16T23:59:29.269Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes, inheritance can be a valuable tool! It can also be a costly hurdle. Let’s talk about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4CzfdRC0Ij14Iwq" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I read an article by <a href="https://medium.com/u/9516b977c6cd">Aleena</a> that elaborated on some of the problems with using inheritance in programming:</p><p><a href="https://levelup.gitconnected.com/whats-the-problem-with-inheritance-in-programming-e1533f4b4b35">What’s the Problem with Inheritance in Programming</a></p><p>It’s a great article, and I would recommend giving them a follow like I have. Most of the article cautions the reader to consider alternative methods for achieving their desired functionality that don’t rely on inheritance. I’m not going to elaborate on all of the potential issues discussed (although we’ll mention a few of them here), as I’d rather you just read the article then come back, but there are a lot of great points made.</p><p>If you follow <a href="https://www.youtube.com/@ThePrimeTimeagen">ThePrimeTime</a> on YouTube, you also know that he usually cautions his listeners against the use of inheritance in their daily coding practices. For the most part, my experience interacting with code written for web apps (looking at you MVC) would incline me to agree with these programmers and others like them (see <a href="https://softwareengineering.stackexchange.com/questions/12439/code-smell-inheritance-abuse">this</a> StackExchange thread for all the inheritance hate, some even calling it a code smell in any case). Inheritance has gotten a deservedly bad rap because of developers’ proclivity to utilize it as a simple code reuse mechanism, and I must take this opportunity to say this to all the developers reading this article — please stay away from that practice.</p><p>I can’t blame you for having this idea initially, though, as even the <a href="https://docs.oracle.com/en/java/javase/17/language/sealed-classes-and-interfaces.html">Oracle Java SE docs</a> have the potential to lead you astray:</p><blockquote>One of the primary purposes of inheritance is code reuse: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug) them yourself.</blockquote><p>I will state this outright: inheritance is an extremely poor way to <em>just</em> reuse code. Its entire design semantics center around the concept of an is-a relationship between the superclass and subclass, a key aspect of its design which plain code reuse completely ignores and destroys. This is where MVC frameworks and other libraries have enforced bad practice by utilizing convenience classes designed to be extended by client applications simply for code reuse, making it very easy to assume that this “feature” of their framework correlates to good ways to engineer code. What eventually happens when the programmer embraces this idea is instead a maintenance nightmare reminiscent of the spaghetti monster, where classes are coupled together for no good reason and one change breaks a million unit tests.</p><p>Now, I’m going to start by using an example from the article referenced above, and likely a common one online, but please know that I’m not trying to prove anyone wrong about inheritance. The point of that article wasn’t to not use inheritance, it was to use it judiciously. I’m merely going to attempt to illustrate what judicious use is. The example is, given the following pseudo implementation of a list:</p><pre>class MyList&lt;T&gt; {<br><br>  void add(T item) { .. }<br><br>  void addAll(T... items) {<br>    for (T each : items)<br>      add(each);<br>  }<br>}</pre><p>Suppose you want to update it to keep tabs on the number of items that are added, some sort of statistic. You might think that plain inheritance is a good way to do that. You would be wrong. This is what that might look like:</p><pre>class MyListWithCounter&lt;T&gt; extends MyList&lt;T&gt; {<br>        int timesAdded = 0;<br><br>        @Override<br>        void add(T item) {<br>            timesAdded++;<br>            super.add(item);<br>        }<br><br>        @Override<br>        void addAll(T... items) {<br>            timesAdded += items.length;<br>            super.addAll(items);<br>        }<br>    }</pre><p>If you run this code like such:</p><pre>public static void main(final String[] args) {<br>    var list = new MyListWithCounter&lt;Integer&gt;();<br>    list.addAll(1, 2, 3, 4);<br>    System.out.format(&quot;Times added: %d\n&quot;, list.getTimesAdded());<br>}</pre><p>Then timesAdded comes out to 8 instead of 4, like we’d expect. Why is that? Because the superclass’s addAll calls its add method which is overridden by the subclass’s add. This means each element is counted twice. In order to avoid this, we’d have to have known about specific implementation details of the superclass, coupling the two together rigidly. To many opponents of inheritance, this is the case in point, but I say not so fast. First, I’m going to help their case further by showing how composition can fix our little problem:</p><pre>public static void main(final String[] args) {<br>    var list = new MyListV2ImplWithCounter&lt;Integer&gt;();<br>    list.addAll(1, 2, 3, 4);<br>    System.out.format(&quot;Times added: %d\n&quot;, list.getTimesAdded());<br>}<br><br>interface MyListV2&lt;T&gt; {<br>    void add(T t);<br>    void addAll(T... items);<br>}<br><br>static class MyListV2Impl&lt;T&gt; implements MyListV2&lt;T&gt; {<br>    public void add(T item) {<br>        // add<br>    }<br><br>    public void addAll(T... items) {<br>        for (T each : items)<br>            add(each);<br>    }<br>}<br><br>static class MyListV2ImplWithCounter&lt;T&gt; implements MyListV2&lt;T&gt; {<br>    MyListV2&lt;T&gt; list = new MyListV2Impl&lt;&gt;();<br>    int timesAdded = 0;<br><br>    @Override<br>    public void add(T item) {<br>        timesAdded++;<br>        list.add(item);<br>    }<br><br>    @Override<br>    public void addAll(T... items) {<br>        timesAdded += items.length;<br>        list.addAll(items);<br>    }<br>}</pre><p>We define a common interface then a basic implementation and a wrapper class that composes the implementation and adds the counting functionality. This gives us the correct result, and the superclass’s addAll behavior hasn’t changed a bit. Composition broke the coupling. Granted, we’re still using inheritance to implement the interface, but it’s not the egregious usage in the first example. Basically, what we’ve done here is start to implement the <a href="https://en.wikipedia.org/wiki/Decorator_pattern">decorator design pattern</a>, but to flesh it out we’ll need to do something like the following:</p><pre>interface MyListV3&lt;T&gt; {<br>    void add(T t);<br>    void addAll(T... items);<br>}<br><br>class MyListV3Impl&lt;T&gt; implements MyListV3&lt;T&gt; {<br>    public void add(T item) {<br>        // add<br>    }<br><br>    public void addAll(T... items) {<br>        for (T each : items)<br>            add(each);<br>    }<br>}<br><br>// This exists just to compose the concrete list implementation<br>// and call its methods below the covers.  It acts as a delegator <br>// that allows the composed class&#39;s functionality to be decorated.<br>abstract class MyListDecorator&lt;T&gt; implements MyListV3&lt;T&gt; {<br>    MyListV3&lt;T&gt; list;<br>    MyListDecorator(MyListV3&lt;T&gt; list) {<br>        this.list = list;<br>    }<br><br>    @Override<br>    public void add(T item) {<br>        list.add(item);<br>    }<br><br>    @Override<br>    public void addAll(T... items) {<br>        list.addAll(items);<br>    }<br>}<br><br>class CounterDecorator&lt;T&gt; extends MyListDecorator&lt;T&gt; {<br>    private Integer timesAdded = 0;<br><br>    CounterDecorator(MyListV3&lt;T&gt; list) {<br>        super(list);<br>    }<br><br>    public Integer getTimesAdded() {<br>        return timesAdded;<br>    }<br><br>    @Override<br>    public void add(T item) {<br>        timesAdded++;<br>        super.add(item);<br>    }<br><br>    @Override<br>    public void addAll(T... items) {<br>        timesAdded += items.length;<br>        super.addAll(items);<br>    }<br>}<br><br>class LoggingDecorator&lt;T&gt; extends MyListDecorator&lt;T&gt; {<br>    private static final Logger LOGGER = Logger.getLogger(LoggingDecorator.class.getName());<br><br>    LoggingDecorator(MyListV3&lt;T&gt; list) {<br>        super(list);<br>    }<br><br>    @Override<br>    public void add(T item) {<br>        LOGGER.info(&quot;Adding item &quot; + item.toString());<br>        super.add(item);<br>    }<br><br>    @Override<br>    public void addAll(T... items) {<br>        String itemsLog = items.stream().map(Objects::toString).collect(Collectors.joining(&quot;,&quot;));<br>        LOGGER.info(&quot;Adding items &quot; + itemsLog);<br>        super.addAll(items);<br>    }<br>}</pre><p>Then use these classes like so:</p><pre>public static void main(final String[] args) {<br>    var list = new CounterDecorator&lt;Integer&gt;(<br>            new LoggingDecorator&lt;&gt;(<br>                    new MyListV3Impl&lt;&gt;()));<br>    list.addAll(1, 2, 3, 4);<br>    System.out.format(&quot;Times added: %d\n&quot;, list.getTimesAdded());<br>}</pre><p>That’s definitely more inheritance, but now we get counting statistics and logging and any other fancy functionality we want to augment our list implementation with. I know we took off kind of quickly here, and there are quite a few things to take note of. Let’s try to unpack them.</p><p>First, I would point out that this makes my case pretty well — inheritance was indeed a valuable tool that enabled us to create a near perfect solution to our problem, one that didn’t require us to take sides between inheritance and composition like we’re in a pointless flame war but instead allowed us to combine the two in harmony. You’ll find that a lot of design patterns work this way and that there was never any need to vilify inheritance or deify composition or anything else of the sort.</p><p>Second, the key to this whole design pattern is that our decorator classes implement the same interface that our composed, concrete list implementation does. This enables us to both compose the core functionality of the list implementation while extending the functionality of the classes that decorate it. Only a couple of design patterns work this way, but this is the only one I’m aware of that allows us to recursively compose an unlimited number of objects with complimentary, but differing, functionality.</p><p>Third, even though we use inheritance to extend the decorators, because we’re able to add functionality at runtime through what I like to call “dynamic composition,” our functionality isn’t statically coupled together. This is one of the biggest shortfalls of using strictly inheritance to implement this type of solution. This is mentioned in the article above as well, and it’s clearly illustrated here. If we added a few more classes of decorators and then iterated through all the runtime combinations of dynamically composed objects, coding the equivalent in static inheritance hierarchies would result in an obscene number of classes, and it would be rigid, inflexible, and a maintenance nightmare.</p><p>Now, that’s the decorator pattern, one of dozens of design patterns, so surely there are others that illustrate my point just as eloquently? Indeed. Let’s talk about the <a href="https://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a>. This one is most commonly touted for its ability to add functionality to a class without having to touch the original class, provided it implements a method enabling you to do so. It’s also, however, one that achieves its functionality using only inheritance. No composition here.</p><p>If you read my last article:</p><p><a href="https://medium.com/@william746a/sum-types-in-java-c20f34c19921">Sum Types in Java?</a></p><p>Then you remember that we looked a lot at switch statements/expressions and pattern matching. We looked at how sum types can be reasoned about with those mechanisms and how polymorphism lets us do essentially the same thing in more elegant fashion. Now, we’re going to look at the visitor pattern in light of each of these.</p><p>Let’s go back to the following class hierarchy from the last article:</p><pre>interface PaymentMethod {<br>  String type();<br>}<br><br>record Cash() implements PaymentMethod {<br>  String type() {<br>    return &quot;Cash&quot;;<br>  }<br>}<br><br>record PayPal(String email) implements PaymentMethod {<br>  String type() {<br>    return &quot;PayPal (&quot; + email + &quot;)&quot;;<br>  }<br>}<br><br>record CreditCard(String cardNumber) implements PaymentMethod {<br>  String type() {<br>    return &quot;Credit (&quot; + cardNumber + &quot;)&quot;;<br>  }<br>}</pre><p>Then we used it like so:</p><pre>String describePaymentMethod(PaymentMethod method) {<br>  return method.type();<br>}</pre><p>This is all well and good as long as the methods defined in the common interface are all we need (the type method in this example). What if we need to use methods specific to one of the particular implementation types, methods that the interface doesn’t define? Or what if we need to do different processing steps or send data to different systems depending on the type? This, typically, is where the functional programming (FP) crowd will be shouting, “Pattern matching!” from the rooftops. And indeed, if we augment our types to add implementation-specific methods with different return types:</p><pre>record Cash() implements PaymentMethod {<br>  String type() {<br>    return &quot;Cash&quot;;<br>  }<br><br>  DepositBatch depositBatch() {<br>    // return deposit batch payment is in<br>  }<br>}<br><br>record PayPal(String email) implements PaymentMethod {<br>  String type() {<br>    return &quot;PayPal (&quot; + email + &quot;)&quot;;<br>  }<br><br>  PayPalAccount accountInfo() {<br>    // return account info<br>  }<br>}<br><br>record CreditCard(String cardNumber) implements PaymentMethod {<br>  String type() {<br>    return &quot;Credit (&quot; + cardNumber + &quot;)&quot;;<br>  }<br><br>  Bank bankInfo() {<br>    // return bank info<br>  }<br>}</pre><p>Then pattern matching will seem to really shine when you need to use those type-specific methods to process the payment:</p><pre>public void processPayment(PaymentMethod method) {<br>    switch (method) {<br>        case Cash cash -&gt; {<br>            logCashSale(cash.depositBatch());<br>            finalizeCashSale(cash);<br>        }<br>        case PayPal payPal -&gt; {<br>            logPayPalSale(payPal.accountInfo());<br>            finalizePayPalSale(payPal);<br>        }<br>        case CreditCard creditCard -&gt; {<br>            logCreditCardSale(creditCard.bankInfo());<br>            finalizeCreditCardSale(creditCard);<br>        }<br>    }<br>}</pre><p>Long time Java programmers might wonder where the default case and instanceof operators are. If we seal the interface, the compiler can ensure that all of the cases are covered in the switch, removing the need for a default case. Additionally, now that switches support pattern matching, they take care of all the instanceof checking and type casting under the hood. Looks kind of like a functional language now, huh? What it also looks like is that we’re able to process different implementations in different ways without having to concern ourselves with shoehorning functionality into a superclass like we would typically try to do with an inheritance-based solution. That doesn’t mean that inheritance can’t help us create something more elegant and flexible, however. This pattern matching solution could easily snowball into a maintenance bottleneck and make it harder to add or amend functionality when (not if) the time comes. The visitor pattern can save us. First, we’ll define an interface that our processing methods can implement:</p><pre>interface PaymentProcessor {<br>    void doThings(Cash paymentMethod);<br>    void doThings(PayPal paymentMethod);<br>    void doThings(CreditCard paymentMethod);<br>}</pre><p>Then, we’ll make sure our original PaymentMethod interface exposes a method that allows us to use PaymentProcessor:</p><pre>interface PaymentMethod {<br>    String type();<br>    void process(PaymentProcessor paymentProcessor);<br>}</pre><p>We’re assuming the return types are void for brevity. Next, we implement the new method in the PaymentMethod subclasses like so:</p><pre>record Cash() implements PaymentMethod {<br>    @Override<br>    public String type() {<br>        return &quot;Cash&quot;;<br>    }<br><br>    @Override<br>    public void process(PaymentProcessor paymentProcessor) {<br>        paymentProcessor.doThings(this);<br>    }<br>}<br><br>record PayPal(String email) implements PaymentMethod {<br>    @Override<br>    public String type() {<br>        return &quot;PayPal(&quot; + email + &quot;)&quot;;<br>    }<br><br>    @Override<br>    public void process(PaymentProcessor paymentProcessor) {<br>        paymentProcessor.doThings(this);<br>    }<br>}<br><br>record CreditCard(String cardNumber) implements PaymentMethod {<br>    @Override<br>    public String type() {<br>        return &quot;CreditCard(&quot; + cardNumber + &quot;)&quot;;<br>    }<br><br>    @Override<br>    public void process(PaymentProcessor paymentProcessor) {<br>        paymentProcessor.doThings(this);<br>    }<br>}</pre><p>Now, you may be wondering what good it does for the implementation to only call paymentProcessor.doThings(this) and why the implementation is exactly the same for each payment method. We’ll get to that in a second. Lastly, we need PaymentProcessor implementations where our actual business logic will go:</p><pre>class LogPayment implements PaymentProcessor {<br>    private static final Logger LOGGER = Logger.getLogger(LoggingPaymentProcessor.class.getName());<br><br>    @Override<br>    public void doThings(Cash paymentMethod) {<br>        LOGGER.info(&quot;Processing Cash payment method.&quot;);<br>    }<br><br>    @Override<br>    public void doThings(PayPal paymentMethod) {<br>        LOGGER.info(&quot;Processing PayPal payment method with email: &quot; + paymentMethod.email());<br>    }<br><br>    @Override<br>    public void doThings(CreditCard paymentMethod) {<br>        LOGGER.info(&quot;Processing CreditCard payment method with card number: &quot; + paymentMethod.cardNumber());<br>    }<br>}<br><br>class FinalizePayment implements PaymentProcessor {<br><br>    @Override<br>    public void doThings(Cash paymentMethod) {<br>        // Cash things<br>    }<br><br>    @Override<br>    public void doThings(PayPal paymentMethod) {<br>        // PayPal things<br>    }<br><br>    @Override<br>    public void doThings(CreditCard paymentMethod) {<br>        // CreditCard things<br>    }<br>}</pre><p>Let’s return to our original consumer method — processPayment — and see how we can transform our pattern matching to something more elegant:</p><pre>public void processPayment(PaymentMethod method) {<br>    method.process(new LogPayment());<br>    method.process(new FinalizePayment());<br>}</pre><p>Would you believe that those two lines achieve everything that the switch statement did? Obviously our solution required a few steps, but consuming our classes and dispatching the correct type-safe business logic is as simple as that. In the process, we gained the extensibility we need to add or amend functionality without breaking our entire workflow or ending up with a fifty-line-long case statement. PaymentMethod#process is what we call our visitor method, and PaymentProcessor is our visitor. You may be thinking that the process implementations with the single paymentProcessor.process(this) are the most boring parts of this whole pattern, and you’d be right. However, they’re also the most important parts because they determine exactly which instances of both the visitor method and the visitor class’s methods get dispatched at runtime. It essentially replaces the branching logic of the switch with built-in polymorphic method dispatch that branches our logic for us based on the concrete runtime types. We could decouple it even more by injecting the payment processors through the constructor of the class containing processPayment. There’s also a lot of flexibility here in regards to the visitor API. We could add new visitors that return different types depending on the stage of processing that the payment is in (such as a result type that allows us to process specific business validation errors), we could create a new aggregator class using the <a href="https://en.wikipedia.org/wiki/Composite_pattern">composite pattern</a> that would allow us to interact with a collection of payment methods using the same API as a singular payment method (meaning our client code in processPayment would gain new capabilities without changing at all), or we could even create decorators from visitor implementations to make our client code even more expressive and powerful (adding circuit-breakers for fault tolerance or publishing events to a queue, to name just two of dozens of examples). The possibilities are endless, thanks in large part to the proper use of inheritance and polymorphism.</p><p>FP fans like to tout their favorite language’s more declarative programming style over the typically more imperative approach of languages like Java, and I can appreciate that. However, of these two examples, doesn’t the glorified if-else of pattern matching cases look a lot more imperative than the visitor method calls? You decide for yourself. Now this doesn’t mean that I never feel the need to use pattern matching or appreciate its utility. I used it for a problem the other day, in fact. This also doesn’t mean that I have anything against FP as a paradigm. Even some of the most basic concepts of OOP borrow something from FP — objects and classes are actually just fancy ways to create closures around lexically-scoped variables, for example. They’re brothers, really.</p><p>What it does mean is that there’s a use for every tool. When you’re practicing carpentry, you don’t become a hammer purist and use that tool in every situation, do you? Imagine if we tried to saw a board with it! Why do we think differently when we’re writing code? It’s so easy, almost trendy sometimes, to become a purist in some manner or another then try to shoehorn all the code we touch into whatever paradigm seems most honorable to us. I think I’ve shown clearly why inheritance is both a valuable tool and something that you shouldn’t get carried away with, but so is composition and pattern matching and plain old for loops. My advice is to embrace every tool and learn to use them appropriately to create well-engineered applications.</p><p>Be well, programmers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d29a596a00f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sum Types in Java?]]></title>
            <link>https://medium.com/@william746a/sum-types-in-java-c20f34c19921?source=rss-a3d7985086c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c20f34c19921</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[type-theory]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[William Jackson]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 02:10:45 GMT</pubDate>
            <atom:updated>2025-02-25T13:26:54.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>User-Defined Sum Types in Java?</h3><p>Ah, this old question! Yes, it has them, and you probably use them every day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uo5vWB0k6vy3SL1e" /><figcaption>Photo by <a href="https://unsplash.com/@angelekamp?utm_source=medium&amp;utm_medium=referral">Angèle Kamp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s recap. A sum type is essentially an either/or value. In the classic example of a Boolean, a value is either “true” or “false.” There are many other examples, however. An integer is either -2,147,483,648, or -2,147,483,647, or…, all the way up to 2,147,483,647, so it is a sum type as well. There are many other examples, all adhering to the either/or paradigm. The question we face today comes from articles such as <a href="https://www.schoolofhaskell.com/user/Gabriel439/sum-types">this</a> one (which is an extremely interesting article and worth a read, by the way), which claim that Java, among other OOP and imperative languages, lacks support for user-defined sum types. This is simply <em>false </em>(at least in Java’s case), even without pattern matching switches and sealed interfaces added to support it in recent JDK versions. Allow me to explain.</p><p>There are several different styles of <a href="https://en.wikipedia.org/wiki/Tagged_union">sum types</a>, but generally the definition includes the concept of a union between the possible values that can be used to discriminate among them. With Booleans, True and False have their union in the fact that they are both instances of the type Boolean. This means that, in <em>very </em>simplistic type theory terms (please don’t come after me with pitchforks), they can be used in the same position in a code expression interchangeably. For example, given the expression if &lt;Boolean&gt; then &lt;true-exp&gt; else &lt;false-exp&gt;, true-exp is evaluated if Boolean is True, and false-exp if Boolean is False. In Java’s case, as well as most other imperative-natured languages, this requires built-in support for “if” conditionals that can discriminate between Boolean values and branch the logic accordingly. Since current computer architecture is still binary, this might be the most basic construct in all of programming. I digress.</p><p>Either way, we see a sum type used to control branching logic, with the concrete instance of the sum type not changing the semantics of the expression. With Booleans, if does the trick because you don’t need to use the value of the Boolean in the resultant branch. It’s assumed. With other sum types, pattern matching is the ticket because you usually do need to use the value in the branch. Pattern matching is likely just boolean evaluation of some sort of instanceof operator under the hood anyway. Now, what if I told you there’s a way that does it more elegantly in Java, a way that will make Java’s, and many other class-based language’s, support for sum types seem lightyears ahead of anything you’ve been led to believe? We’ll get back to that.</p><p>In languages like TypeScript, union types are implemented with a literal tag field, which lets the transpiler guarantee type safety within the branches of conditional logic. An example of this can be found in articles such as <a href="https://mariusschulz.com/blog/tagged-union-types-in-typescript">this </a>one, but the premise is the same in many idiomatically functional languages. Here’s the code from that article:</p><pre>interface Cash {<br>  kind: &quot;cash&quot;;<br>}<br><br>interface PayPal {<br>  kind: &quot;paypal&quot;;<br>  email: string;<br>}<br><br>interface CreditCard {<br>  kind: &quot;credit&quot;;<br>  cardNumber: string;<br>  securityCode: string;<br>}<br><br>type PaymentMethod = Cash | PayPal | CreditCard;<br><br>function describePaymentMethod(method: PaymentMethod) {<br>  switch (method.kind) {<br>    case &quot;cash&quot;:<br>      // Here, method has type Cash<br>      return &quot;Cash&quot;;<br><br>    case &quot;paypal&quot;:<br>      // Here, method has type PayPal<br>      return `PayPal (${method.email})`;<br><br>    case &quot;credit&quot;:<br>      // Here, method has type CreditCard<br>      return `Credit card (${method.cardNumber})`;<br>  }<br>}</pre><p>The kind field acts as our tag. The function parameter is our element of interest in this discussion, however, as the consuming logic depends on the concrete type of method. As you can see, this logic is implemented with a switch statement where the parameter is checked against each possible concrete type, allowing type-safe execution within the specified case branches. Most functional compilers also check to make sure that all the cases are handled, a feature that was also added to Java recently with sealed interfaces.</p><p>Now, let’s look at user-defined sum types in Java so that we can prove the doubters wrong. If we continue with the premise that an instance of a sum type can replace any other instance of that same sum type in a statement or expression and retain type safety, then we can use a rather familiar OOP term to describe our strategy here — polymorphism. Let’s see some code, using equivalent types to the TypeScript above:</p><pre>interface PaymentMethod {<br>  String type();<br>}<br><br>record Cash() implements PaymentMethod {<br>  String type() {<br>    return &quot;Cash&quot;;<br>  }<br>}<br><br>record PayPal(String email) implements PaymentMethod {<br>  String type() {<br>    return &quot;PayPal (&quot; + email + &quot;)&quot;;<br>  }<br>}<br><br>record CreditCard(String cardNumber) implements PaymentMethod {<br>  String type() {<br>    return &quot;Credit (&quot; + cardNumber + &quot;)&quot;;<br>  }<br>}</pre><p>I’m assuming you can see where we’re going at this point?</p><pre>String describePaymentMethod(PaymentMethod method) {<br>  return method.type();<br>}</pre><p>It’s as simple as that. No magic, no syntactic sugar, no pattern matching, just plain polymorphic Java. Sum types are right there, and polymorphism makes consuming them so utterly elegant. Notice that rather than have their concrete type asserted in the branches of conditionals or cases, we simply have an expression of a specific type (in this case a method with the signature PaymentMethod -&gt; String), in which our PaymentMethod sum type plays a part. All the conditional logic is contained in the concrete class that implements the interface, with the interface itself being our union “tag” and the JVM doing the dispatching.</p><p>Be well, programmers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c20f34c19921" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>