<?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 FinTechDev on Medium]]></title>
        <description><![CDATA[Stories by FinTechDev on Medium]]></description>
        <link>https://medium.com/@fintechdevlondon?source=rss-cfd4a6c02058------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GJXkaR0OY9JAmxumJgEa1g.jpeg</url>
            <title>Stories by FinTechDev on Medium</title>
            <link>https://medium.com/@fintechdevlondon?source=rss-cfd4a6c02058------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:37:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fintechdevlondon/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[How to setup a Jupyter lab server — don’t mix virtual environments!]]></title>
            <link>https://medium.com/@fintechdevlondon/how-to-setup-a-jupyter-lab-server-dont-mix-virtual-environments-d9f6fd0a5e0e?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f6fd0a5e0e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[jupyterlab]]></category>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 20:51:14 GMT</pubDate>
            <atom:updated>2026-07-27T21:28:40.179Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a quick guide on how to install Jupyter Lab (the proper way — no mixing of venvs!)</p><p>Fundamental problem: The root of the problem comes from the mixing of multiple concerns within the same virtual environment. Most install guides give some variation of “install a venv, and then pip install jupyterlab” — with no word on what that venv is and <strong><em>is not </em></strong>for.</p><p>I would guess one of the first things most users do following the typical install instructions is to activate the same virtual environment used to install Jupyter, and then install a whole collection of different python packages — numpy, pandas, scipy, perhaps some GUI widget toolkits…? (etc)</p><p>This is the wrong thing to do because it mixes multiple concerns into the same virtual environment. The venv into which jupyter lab is installed should be reserved for just that one purpose — installing and running Jupyter.</p><p>Fine — so what’s the fix?</p><p>Actually it’s quite straightforward. I will provide a full step by step process showing how to install and setup everything from end to end later in this article. To fix this specific nuance, the solution is pretty much the following:</p><pre># the server — install once, never pollute it<br>python3 -m venv ~/venvs/jupyter<br>~/venvs/jupyter/bin/pip install jupyterlab<br><br># a project env — its own dependencies<br>python3 -m venv ~/work/analysis-project/.venv<br>~/work/analysis-project/.venv/bin/pip install ipykernel<br>~/work/analysis-project/.venv/bin/python -m ipykernel install --user \<br>    --name analysis-project --display-name analysis-project</pre><p>As you can see, a separate .venv has been created in the root of the project itself, rather than each project simply piggybacking off the original Jupyter virtual environment. Obviously — this has the additional advantage that one can now have one virtual environment per project, rather than bundling everything together into a single virtual environment. This is much less likely to cause package install conflicts.</p><h3>Full end-to-end guide (for Ubuntu Server 26.04 — probably works for other Linux variants)</h3><p>Firstly, install the core components.</p><pre>sudo apt update &amp;&amp; sudo apt install python3-venv<br>python3 -m venv ~/venvs/jupyter<br>~/venvs/jupyter/bin/pip install --upgrade pip<br>~/venvs/jupyter/bin/pip install jupyterlab</pre><p>Now, you need a home for your projects. Set “jupyter home”.</p><p><strong>Caution: Common error — do not run</strong> !pip install xyz <strong>from within Jupyter.</strong> This doesn’t do what you think it does. The correct command would have been %pip install xyz , which runs sys.executable -m pip , which picks up the kernel’s own interpreter. On the other hand, !pip is wrong, because this escapes to the shell — and that will pick up pip from the shell’s PATH . This is inherited from whatever ran jupyter lab in the first place, and therefore pip points to the virtual environment used to manage Jupyter itself rather than a project specific one.</p><p>If managed by systemd, then the service inherits systemd’s default PATH with no virtual environment on it, so !pip finds a system pip or nothing at all.</p><p>Hint: You can check it with this: import sys; print(sys.executable)</p><p>To set the Jupyter home and other configuration variables, run</p><pre>jupyter lab --generate-config</pre><p>This creates the file</p><pre>~/.jupyter/jupyter_lab_config.py</pre><p>Now run</p><pre>jupyter lab password</pre><p>This creates the file</p><pre>~/.jupyter/jupyter_server_config.json</pre><p>while simultaneously allowing the password to be configured. If you need a high level of security, for example if Jupyter will be exposed to the rest of the world, consider generating something secure with openssl.</p><pre>openssl rand -base64 32</pre><p>Now edit the config file. ~/.jupyter/jupyter_lab_config.py</p><p>Some parameters worth modifying:</p><pre>c.ServerApp.root_dir = &#39;/home/&lt;user&gt;/Jupyter-Home&#39;<br>c.ServerApp.ip = &#39;localhost&#39;<br>c.ServerApp.port = 8888<br>c.ServerApp.open_browser = False    # For headless servers</pre><p>Of course, this requires creating ~/Jupyter-Home/ . Change the IP address from localhost to some other IP, or possibly 0.0.0.0 if you want the server to bind to all IPs. Be aware of the security implications of this.</p><p>If you want the command jupyter to be on your PATH, the way to set that up is</p><pre>ln -s ~/venvs/jupyter/bin/jupyter ~/.local/bin/jupyter</pre><p>If you want your Jupyter environment to start when your system boots, then you might want to register it with systemd. Create the file</p><p>~/.config/systemd/user/jupyterlab.service</p><pre>[Unit]<br>Description=JupyterLab<br>After=network-online.target<br>Wants=network-online.target<br><br>[Service]<br>Type=simple<br>WorkingDirectory=/home/&lt;user&gt;/Jupyter-Home<br>ExecStart=/home/&lt;user&gt;/venvs/jupyter/bin/jupyter lab<br>Restart=always<br>RestartSec=5<br><br>[Install]<br>WantedBy=default.target</pre><p>Then run</p><pre>systemctl --user daemon-reload<br>systemctl --user enable --now jupyterlab<br>sudo loginctl enable-linger &lt;user&gt;<br><br># check with<br>systemctl --user status jupyterlab --no-pager<br>systemctl --user is-enabled jupyterlab         # expect: enabled<br>systemctl --user is-active  jupyterlab         # expect: active<br>loginctl show-user &lt;user&gt; --property=Linger    # expect: Linger=yes</pre><p>Notice that the service is registered under the users .config rather than in the /etc/systemd directory. Since the Jupyter environment is configured entirely within a single userspace (in other words, it is configured for a single-user to use) this is the most straightforward solution.</p><p>If you wish to setup a Jupyter server for a multi-user environment, then it would make more sense to register the service under “system-wide systemd” (in other words under /etc/systemd) and have it run as some new user such as jupyterlabadmin . Then create a group jupyterlabusers and add jupyterlabadmin and any other relevant users to that group. The service should run as the user jupyterlabadmin . Obviously other variations on this are possible — choose whatever is most relevant for your organization.</p><p>Now, if you reboot the server, Jupyter lab should start shortly after the system boots <strong><em>even if you don’t login (via ssh etc).</em></strong></p><p>To setup a project do the following:</p><pre>mkdir ~/Jupyter-Home/my-project<br>cd ~/Jupyter-Home/my-project<br>python3 -m venv .venv<br>./.venv/bin/pip install -q --upgrade pip ipykernel<br>./.venv/bin/python -m ipykernel install --user\<br>    --name my-project --display-name &quot;Python (my-project)&quot;<br>systemctl --user restart jupyterlab</pre><p>This creates a new project directory under Jupyter-Home . Note that this project has its own virtual environment — the separation of concerns is achieved. The fussy reader might argue that this is a bit more work than just bundling every dependency into the same virtual environment. For such a reader, one might suggest copying and pasting the above block of code into a markdown document and saving it under Jupyter-Home for easy reference, or possibly create a bash function to do this if you really can’t be bothered to copy and paste this every time you need to spin up a new project.</p><p>Note that the final line causes Jupyter to pick up the new kernelspec.</p><p>From within Jupyter, you should now have a choice of kernels, each one referencing a different virtual environment.</p><p>If you want to list registered kernels, run</p><pre>jupyter kernelspec list # what&#39;s registered, where?</pre><p>To remove a kernelspec, run</p><pre>jupyter kernelspec remove &lt;name&gt;</pre><p>This is something that must be run if the corresponding project directory is deleted, otherwise the kernel will fail to launch if selected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f6fd0a5e0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Controversial Guide to 4 Programming Languages]]></title>
            <link>https://medium.com/@fintechdevlondon/the-controversial-guide-to-4-programming-languages-cbd7e47e5f26?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd7e47e5f26</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 00:15:02 GMT</pubDate>
            <atom:updated>2024-11-05T00:15:02.539Z</atom:updated>
            <content:encoded><![CDATA[<p>Laying down the lay of the land for 4 of the most popular programming languages</p><p>Sometimes it’s good to have a bit of fun. I hope this article won’t offend too many people.</p><p>Most people have a favorite programming language. Some peoples’ favorite language changes with time. Some people just stick to one thing, and learn it really well. They use it, because they know how to use it, so they learn it better, and then because they know it the best, they continue to use it.</p><p>This is a vicious cycle. A positive feedback loop. I used to be one of these people. In my particular case, I was stuck in a C++ loop.</p><p>My view on programming languages is somewhat different to most people. At least, I am yet to encounter someone with the same opinion.</p><p><em>My opinion is, they all, well, kind of suck? That is to say, there is no such thing as a really good programming language. Whichever one you choose, they all have at least some significant problems.</em></p><p>Let’s explore this idea together.</p><h3>C++</h3><p>You may be surprised to hear this, but since using Rust and Python, I have come to appreciate C++ more than I used to. I have been using it for a really long time. Since before C++ 11 was a thing.</p><h4>Good things</h4><p>No borrow checker. It might seem a bit weird to start off with this one, but honestly compare C++ to Rust and this is my favorite C++ feature. No borrow checker. I appreciate the borrow checker for what it is as an academic piece of research, but I don’t appreciate it for preventing me from writing code which I know is legal, and would have compiled in C++.</p><p>The reality is the borrow checker isn’t really necessary. There is an alternative. The alternative is <em>learn and understand in detail what the compiler does with your code</em>. Basically what I am saying is, the alternative to the borrow checker is just to be competent.</p><p>If you can’t be bothered, or don’t have the time to invest to do this, then use instead Julia, I guess. If there’s any difference in performance between the two you’re not going to notice it.</p><h4>More good things</h4><p>Speed. Yeah it’s fast, and relatively easy to write fast code without too much thought.</p><p>The standard library is pretty good. Some things have weird names though.</p><h4>Bad things</h4><p>It’s complicated. Seriously complicated. There are a lot of rules to remember, and a lot of exceptions to rules.</p><p>There are 5 different types of value types. They are lvalue, rvalue, glvalue, xvalue and prvalue. At one time, there were just lvalue and rvalues. But rvalues aren’t even considered to be one of the 3 primary categories anymore. Is it necessary to have so many? You can find the documentation at the link below. Can you decipher it? Probably not. It would probably be more helpful to have a detailed explanation of how the compiler works. But unfortunately we don’t get that.</p><p><a href="https://en.cppreference.com/w/cpp/language/value_category">https://en.cppreference.com/w/cpp/language/value_category</a></p><h4>More bad things</h4><p>It seems to take a really, really long time to accomplish anything. This could be due to a number of factors.</p><p>There isn’t a good, universal package manager. Python’s pip, Rust’s Cargo and Julia’s pkg far exceed anything C++ has to offer.</p><p>If you want to take advantage of the C++ ecosystem, that usually means searching the internet for libraries to try and find something suitable, hopefully which is also still maintained. Then you have to figure out how to download the source and compile it, or download some compiled library code. Either way you then have to integrate that with your build system. That might mean learning make, cmake or some of Microsoft’s tools. Yuck.</p><p>It also just takes a long time to type C++ code. It feels very verbose compared with other languages. All those extra keystrokes take a surprisingly long time to type into VS Code. Weird, but true.</p><h3>Julia</h3><p>Ok — let’s do Julia next. Weirdly, although it’s intended as a replacement to Python and the two-language-problem, it feels more like a juiced up version of C. Which is odd, because it’s a dynamic language, like Python.</p><p>In some ways the equivalent of templates in Julia also make it feel a bit like C++. But it has a package manager. Odd.</p><h4>Good things</h4><p>Package manager, sane (ish) metaprogramming, and really good type system which make templates trivial to write, JIT compiled which means your code can in theory be really fast and highly specialized depending on context. Variables work like Python which means it’s really simple to use. It’s really fast. Comparable to C or C++.</p><p>It’s functional, which I guess it an advantage? There’s no OOP, which initially sounds like a disadvantage until you realize that OOP is single dispatch, and Julia has <em>multiple dispatch </em>—<em> </em>which is like mega-wow rather than traditional dynamic dispatch which is just a-little-bit-wow.</p><p>Actually, having multiple dispatch essentially makes OOP obsolete, or at least unnecessary. When you have multiple dispatch, you sort of look back at OOP and the entire domain of design patterns which sprung up just to solve problems OOP created, and think <em>“well, that was stupid”</em>.</p><p>Think about it though, we have entire research domains structured around solving problems which only exist in an OOP world. We have entire textbooks dedicated to trying to explain how to solve complex problems in an OOP paradigm, and people, like me, have spent years thinking about OOP and trying to design systems in a framework which fundamentally makes everything excessively complicated.</p><h4>Bad things</h4><p>Nobody uses it. Ah yeah, this one’s gonna be a problem.</p><p>Well, ok that’s not quite true. There are people who use Julia, but they’re mostly confined to academia. It’s true, there are large scale science research projects who make use of Julia. It is marketed with an emphasis on scientific compute. Computational Biology, Astrophysics and High Energy (Particle) Physics appear to be significant players in this space.</p><p>But in industry? Not so many players here. There are some people using it, but the applications are confined.</p><p>One of the reasons for this is the ecosystem. Sure, if you want tools to solve math problems, Julia probably has you covered. Want good database support? Postgres and Maria are your options. Redis is supported, but for anything else? Forget it. No Kafka. Many of your favorite Python packages are missing. Some exist, but only because Julia calls into Python. If so, they’re not native, so you’re stuck at Python performance.</p><p>The other reason? It feels like a single player game. It is difficult for teams to use Julia, in a way that it isn’t difficult for teams to collaborate in other languages. I’m not actually sure why this is. It might be because the REPL is the primary interface. Python has a REPL, sure, but it’s easier to deploy and collaborate within a Python application team than a Julia application team.</p><p>Honestly, I can’t quite say why at the moment. I felt the same way, when I first started working with Python, and still do.</p><p>It might be due to the less mature documentation. Documentation is more important in dynamic languages because you don’t get the hints from types in return values. Figuring out what a function returns in Julia can be a bit, well, obscure. Python seems to compensate with it’s mature documentation.</p><h3>Python</h3><p>Well, might as well talk about Python next, I guess? At the moment I use it everyday. Probably more often than any of the others here.</p><h4>Good</h4><p>I have a lot of good things to say about Python. The package manager pip is pretty good. Some people complain about it, but honestly I can’t say I’ve experienced any major issues with it.</p><p>The ecosystem is vast. Like a huge warehouse of sweets. Almost anything you want, you can find. Database connectors, Kafka connectors, scientific libraries, GPU libraries, ML, AI, if it exists in Computer Science, it probably exists as a Python implementation.</p><p>It’s fast (to write). But not to run…</p><h4>Bad</h4><p>This one’s kind of obvious. The performance. It’s just utterly shocking how slow Python is. Normally you don’t notice it, because modern computers compensate by being really fast. If you always use a vectorized implementation, such as the many libraries for scientific and mathematical operations, then again, you may never see the Python performance penalty, because all your logic is basically executing in code which was compiled from C.</p><p>But, if you can’t use a prebuilt C library with a Python wrapper, because you are implementing some logic which is somewhat niche or specialized (specific?) and therefore you do not have the benefit of a generalized library such as scipy or numpy, this is where you pay. I sure hope you have a large compute budget, because you are going to need to to pay for all those (really, really expensive) cloud compute machines to scale out horizontally.</p><p>If you dig into the CPython implementation and try and find all the steps the language has to go through just to add two integer fields in two classes, then you will understand why it is so slow. It’s a lot of stuff.</p><p>There’s a second aspect. The two language (three language?) problem. This is related to the above. You write some logic in Python. It is slow. You want to convert your logic into a C library to speed it up, and call that from Python. Great idea, but now you need to know Python and C. Actually, it’s worse than that. You need to learn CPython, which is essentially a DSL (Domain Specific Language) written in C — a whole language by itself, with it’s own rules any syntax.</p><h3>Rust</h3><p>Can Rust save us, then? Spoiler alert — no it can’t. Sorry.</p><h4>Good</h4><pre>#[derive(Copy, Clone, Display, Debug, yadda yadda)</pre><p>Need I say more? It’s <em>genius</em>. And it saves <em>so much time</em>. (FYI if you didn’t know, this macro automatically derives a bunch of functions and behaviors for our types. You won’t believe how much time this saves. It’s really the future.)</p><p>The package manager, Cargo, is by far the best of any I’ve seen. I doubt anyone would disagree here.</p><p>It’s fast like C++. Well that’s good.</p><p>The ecosystem is mega. Not quite as mature as Python, but it’s really picking up these days. There’s a lot of stuff available, for interfacing with all kinds of different technology.</p><p>Enums, and algebraic data types. They juts make code so fast to write. It’s really surprising how much difference this makes. Combined with #derive, this makes Rust almost feel like a superpower.</p><p>No exceptions! (As in, exceptions do not exist.) Honestly working with Result and Option types is just so much better. You think you’re going to miss exceptions, but then you just don’t. I find myself missing the Result’s and Option’s in other languages now. Exceptions, by contrast, feel like dynamic return data types. Harder to reason about. More difficult to know if the code is correct, and you’ve accounted for all the possible things which can come back from a function call.</p><p>The type system. It can make a lot of guarantees about the correctness of your code just from the fact that it compiles successfully. This seems to be a combination of some of the above points. Most notably, handling errors as part of an enumeration of the return type.</p><h4>Bad</h4><p>You know what? It’s just that damn borrow checker. Constantly blocking me and telling me what I can’t do. It’s a total pain.</p><p>Some people say if the borrow checker doesn’t let you compile your code, then you must be doing something wrong. But this isn’t true, and anyone who is reasonably proficient with C++ knows it’s true.</p><p>Ah yes, and you have to annotate your references with lifetimes for anything which is slightly more than trivial. This really is painful, and requires a lot of thinking. In C++ this isn’t really a problem, because you just design your code so that it uses references in a sensible way. You don’t get undefined behavior if you don’t use references incorrectly. It’s simple enough, make sure the data to which they refer always exists.</p><p>If you are every unsure, then either be sure, or find another solution. (Unique ptr maybe?)</p><p>The point is, there’s a lot of things about Rust that make it really fast to write solutions to problems with. But the borrow checker is the reverse of that. Eventually you will be writing some code, and you will want to pass some data around. But because your data structures are large, you don’t want to pass them by value, but by reference. (Or maybe you can’t even pass them by value, or the code becomes obtuse if you do or otherwise just doesn’t suit this.) Suddenly, requirements for explicit lifetimes appear everywhere, and development speed slows down, or possibly even grinds to a halt. It just doesn’t feel very natural to have to specify exactly how long each reference lives. What is important is that they do live long enough.</p><p>Which brings us back to C++, I guess.</p><p>Just kidding. I would never go back to C++.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd7e47e5f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Containers are not Not Persistent]]></title>
            <link>https://medium.com/@fintechdevlondon/docker-containers-are-not-not-persistent-8d2969655832?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d2969655832</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 20:06:46 GMT</pubDate>
            <atom:updated>2024-04-13T20:08:22.882Z</atom:updated>
            <content:encoded><![CDATA[<p>Just a quick note on Docker Containers and the Persistency of data within them</p><p>I wish to present a point of view that Docker Container data storage <em>is persistent</em>. This goes against what is written in almost every textbook and article written about Docker.</p><p>My objection to this is more to do with the wording used to describe how Docker behaves rather than anything else.</p><p>This might receive a negative reaction, but I hope it won’t. Let me explain…</p><p>I have always been a bit confused by the statement <em>“Docker container storage is not persistent”</em>.</p><p>This is repeated, literally, everywhere — from books to articles.</p><p>This statement is actually quite misleading. Consider the following example.</p><p>Let’s say we pull an image. (The most basic ubuntu image will do as an example.) Imagine we start a container, run apt install vim, and then shut it down.</p><p>Now we start it back up again. vim is still there. It didn’t evaporate. It didn’t uninstall.</p><p>From my point of view, the opposite of <em>persistent storage</em> must be <em>volatile storage.</em> RAM is volatile, SSDs, Hard Drives and Tape are not (supposed to be).</p><p>Perhaps this makes it clear why I think it is misleading to state that Docker Containers are not persistent, or that volumes are required to maintain persistent data storage. <em>Neither of these things are really true, and these statements are confusing to the reader who is unfamiliar with Docker</em>.</p><p>Another source explains the situation quite clearly</p><blockquote>Data inside Docker containers is not persistent by default. This means that when the container is destroyed, so is the data. There may be situations where you want to maintain data beyond the lifecycle of a container, and this can be achieved using persistent data storage.</blockquote><p>I don’t really like the first sentence, for the reasons I already explained I don’t think it is truly accurate to say <em>Data inside Docker containers is not persistent by default</em>.</p><p>Actually, Docker Containers <em>are persistent</em>. Just as persistent as any other native OS or VM would be. If you stop a container and start it again, it doesn’t lose data. <em>The data is not volatile</em>.</p><p>A more accurate statement would be, <em>data created inside a Docker Container during its lifetime is not saved inside the Docker Image it was created from. If a Docker Container is deleted, then so is any data that was generated on top of the base image from which it was created. Docker Volumes provide a way to persist data even after a Container is destroyed.</em></p><p>I would have thought it was sort of obvious that if you create data inside a Container and then delete the Container, then that data is gone. In just the same way, any data create inside a Docker Volume is also gone if the Volume is deleted.</p><p>Images are supposed to be considered as immutable templates for stamping out containers. Perhaps the above isn’t so obvious if you didn’t know this, just as it wasn’t obvious to me what the statement about Docker Containers not being persistent really meant.</p><p>In addition, images are created as a sequence of filesystem layers, further hinting at their implementation.</p><p>The point of Volumes is to separate the lifetime of a container from additional data which is created within it while it is running.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d2969655832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka listeners and advertised.listeners — how do I configure a Kafka Broker?]]></title>
            <link>https://medium.com/@fintechdevlondon/kafka-listeners-and-advertised-listeners-how-do-i-configure-a-kafka-broker-b062de171ce8?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/b062de171ce8</guid>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 15:52:02 GMT</pubDate>
            <atom:updated>2024-02-03T15:52:23.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka listeners and advertised.listeners — how do I configure a Kafka Broker?</h3><h3>Following on from my previous post I explain the steps required to configure the networking settings for a set of Kafka Brokers.</h3><p>In this guide, I will explain step-by-step how to configure the Kafka parameters for network connectivity, including listeners and advertised.listeners.</p><p>Note that this guide applies specifically to the more up-to-date method of using Kafka with Kraft rather than Zookeeper. If you are still using Zookeeper, this guide will still be helpful, but you will need to configure some additional parameters for Zookeeper.</p><h3>Step 1: Find your Kafka configuration file</h3><p>Installing Kafka is a relatively trivial affair. Assuming you installed a Java Runtime Environment (JRE) and then installed Kafka in the usual way by downloading it and then extracting the tarball, you probably have a known directory which contains Kafka.</p><p>In my case that directory is /opt/kafka and the config file can be found at</p><pre>/opt/kafka/config/kraft/server.properties</pre><h3>Step 2: Decide how many sets of address types will be required to connect to Kafka</h3><p>This requires a bit of thought. The question to answer is the following:</p><ul><li>From the point of view of a client, from wherever this client is running, what address(es) should be used to connect to the Kafka cluster?</li></ul><p>In addition, depending on the above, the following question must also be answered:</p><ul><li>Can (maybe more accurately “should”) each individual Kafka Broker in the cluster use the same address(es) to communicate with each other?</li></ul><p>To make it clear let’s consider an example. This is perhaps the most common use case.</p><ul><li>A Kafka client application runs “somewhere”.</li><li>It isn’t on the same network as the Kafka Broker(s) / Kafka cluster.</li><li>It must contact the Kafka cluster via the internet.</li><li>What address should be used?</li></ul><p>Perhaps the answer is the following.</p><pre>kafka1.prod.mycompany.com:9092</pre><p>Here, kafka1.prod.mycompany.com is the address of an external facing NAT router or firewall for our organization. Port 9092 is forwarded to one of the Kafka broker hosts.</p><p>Maybe that Kafka broker host has the address 192.168.0.1, and Kafka perhaps runs on this host at port 9092.</p><ul><li>So, we expect clients to be able to talk to Kafka using the address kafka1.prod.mycompany.com:9092.</li><li>What about inter-broker communication?</li></ul><p>If we have a second machine</p><pre>kafka2.prod.mycompany.com:9092</pre><p>then is it sensible for that machine to use the same address for inter-broker traffic? It will <em>probably</em> work (due to NAT reflection) but it perhaps isn’t very sensible.</p><p>A better option would be for the brokers to communicate directly via the local private network. (Addresses 192.168.0.X.)</p><p>Perhaps better still a separate local private network. This way traffic can be segregated for internal and external traffic. (Addresses 192.168.100.X,maybe.)</p><p>What we conclude from this is that we need two different types of communication.</p><ul><li>Communication from external sources, typically this will be for traffic from clients to brokers</li><li>Communication from internal sources, typically this will be for inter-broker traffic and perhaps also some internal clients which do things such as monitoring, data migration, …</li></ul><p>Great, we now know we need <em>two types of listeners</em>. Let’s call them INTERNAL and EXTERNAL.</p><h3>Step 3: Configure the listeners parameter with a port number</h3><p>We just concluded that we want two listeners, named INTERNAL and EXTERNAL. Actually, the names are arbitrary. Call them TOM and JERRY if you want.</p><p>Each listener needs a port number and network interface to bind to. The network interface is determined by an ip address.</p><p>If we have a broker with the address 192.168.0.1, then this broker needs to listen on that ip with two different port numbers, one for each listener.</p><p>As mentioned above, it might be a better decision to segregate network traffic. In which case we might use the same port number but different ip addresses for each listener.</p><p>Assuming the simpler setup with a single internal private network, the configuration is defined like so:</p><pre>listeners=INTERNAL://192.168.0.1:9092,EXTERNAL://192.168.0.1:9093</pre><p>The port numbers specified here will essentially be used as a “key” for all other parameter mappings.</p><p>In other words:</p><ul><li>9092 maps to the name INTERNAL</li><li>9093 maps to the name EXTERNAL</li></ul><p>When you read listener think “network connection for this broker” or “address and port for listening socket”. You are trying to answer the question:</p><ul><li>what network interface should I (a Kafka Broker) open a listening socket to?</li></ul><h3>Step 4: Configure the inter-broker listener name</h3><p>Because we have two listeners, one which is intended for use for internal inter-broker communication, and one which is intdended for use for external traffic, we must set the inter.broker.listener.name parameter.</p><pre>inter.broker.listener.name=INTERNAL</pre><h3>Step 5: Configure the corresponding advertised listeners</h3><p>In the case of the advertised.listeners parameter, we are trying to answer a different question:</p><ul><li>what address should clients use to contact me?</li></ul><p>If the same address as specified in listeners can be used, we don’t need to specify this parameter.</p><p>We already stated (in Step 2) that we will need two types of listener. Both listen to the same address 192.168.0.1, but the port numbers differ. (9092, 9093)</p><p>If somebody connects to us via either port, we need to specify what address should be used in the future to continue communication. (See my other recent article to understand exactly why.)</p><p>We already said that port 9092 should be used for inter-broker communication, so the address 192.168.0.1:9092 is sufficient.</p><p>We also said that port 9093 should be used for traffic coming from external clients. In this case, we can’t re-use the address 192.168.0.1:9093. If we send that address back to a client, and the client is on some external network, there is unlikely to be anything listening on 192.168.0.1:9093, and it certainly isn’t our desired Kafka broker.</p><ul><li>Key point: advertised.listeners contains address which are sent back to clients when they first connect to a cluster, which tells the clients how to continue communicating with the brokers.</li><li>The addresses for all advertised.listeners for all brokers in a cluster are aggregated together before sending them back to the client.</li><li>We expect there to be more addresses returned from this aggregation process than were originally contained in the bootstrap.servers string, which exists on the client side.</li><li>This explains a point of confusion:</li><li>If a client already has the address kafka1.prod.mycompany.com:9092 as the address of a Kafka broker, what is the point of advertised.listeners?</li><li>Why would we want to <em>change</em> the address the client uses to connect? It already knows the address. It was specified in the bootstrap.servers. Without this being specified, the client would have no way to know how to reach the Kafka cluster in the first place.</li><li>The answer is that we don’t want to change the address — only potentially add additional addresses which the client might not yet know about.</li><li>In the case of a single broker setup, it does indeed appear to be pointless. There are no additional brokers with new addresses to return when the client connects, and the address of the single broker that exists in the cluster must be already specified in the client bootstrap.servers string, otherwise the client wouldn’t have been able to connect.</li></ul><p>So, what does the config look like?</p><pre>advertised.listeners:EXTERNAL://kafka1.prod.mycompany.com:9093</pre><p>We don’t need to specify a mapping for the listener with the nameINTERNAL. It will simply use the value from listeners. This works because all brokers for this cluster are on the same internal private network.</p><p>A more realistic example might contain many addresses.</p><pre># host: kafka1<br>advertised.listeners:EXTERNAL://kafka1.prod.mycompany.com:9093<br><br># host: kafka2<br>advertised.listeners:EXTERNAL://kafka2.prod.mycompany.com:29093<br><br># host: kafka3<br>advertised.listeners:EXTERNAL://kafka3.prod.mycompany.com:39093<br><br># host: kafka4<br>advertised.listeners:EXTERNAL://kafka4.prod.mycompany.com:49093<br><br># host: kafka_dynamic_0<br>advertised.listeners:EXTERNAL://kafka_dynamic_0.prod.mycompany.com:50000<br><br># host: kafka_dynamic_1<br>advertised.listeners:EXTERNAL://kafka_dynamic_1.prod.mycompany.com:50001</pre><p>I have added two additional hosts here called kafka_dynamic_0 and kafka_dynamic_1.</p><p>The idea being that a clients’ bootstrap.server might contain the addresses for kafka1, kafka2, kafka3, kafka4, but not the “dynamic” servers which we assume were added at a later date.</p><h3>Step 6: Configure the controller listener names</h3><p>This step is required because we are running Kafka in Kraft mode.</p><pre>controller.listener.names=CONTROLLER</pre><p>We obviously didn’t define the name controller yet, so let’s add it. The Kraft communication layer needs a new listening socket.</p><pre># update this<br>listeners=INTERNAL://192.168.0.1:9092,EXTERNAL://192.168.0.1:9093,CONTROLLER://192.168.0.1:9091</pre><h3>Step 7: Configure the security protocol map</h3><p>Finally, we configure the security protocol map, using all of the previously defined names. Since this is not a tutorial about Kafka security and authentication, I will skip over the exact details as to what each of these are.</p><p>So far the “names” have been arbitrary. When configuring Security Protocol Map, each entry is a KEY:VALUE pair.</p><ul><li>The KEY must be one of our “names”.</li><li>The VALUE must be a recognized security protocol option. Possible options include:</li><li>PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL</li></ul><p>We will just use the PLAINTEXT security protocol option here.</p><pre>listener.security.protocol.map=CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT</pre><p>Obviously EXTERNAL:PLAINTEXT is not a good idea since traffic from external clients will be sent over the internet in plaintext… Which is not secure.</p><h3>Summary</h3><p>There are a few key take-away points.</p><ul><li>The “names” of listeners are arbitrary. They are used to define a key which is used as part of several maps defined by listeners, advertised.listeners, and listener.security.protocol.map.</li><li>listeners tells the Kafka process which network interfaces and ports to open listening connections on.</li><li>The combination of addresses and ports chosen in the listeners map defines how the map lookup works. The address and port is mapped to a listener “name”, that “name” then appears in the other maps and elsewhere in the configuration. (It is certainly helpful to this about the config in this way even if that isn’t exactly how Kafka’s internal configuration data-structure works.)</li><li>advertised.listeners defines the addresses clients should use to continue communication. Some of these will be duplicates of what a client already has in it’s bootstrap.servers, but some addresses may be new alternative addresses, and some broker addresses may not be in the initial bootstrap.servers string.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b062de171ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka `listeners` and `advertised.listeners` — What are they and what do they do?]]></title>
            <link>https://medium.com/@fintechdevlondon/kafka-listeners-and-advertised-listeners-what-are-they-and-what-do-they-do-9b004e2eb93d?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b004e2eb93d</guid>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 13:18:54 GMT</pubDate>
            <atom:updated>2024-02-03T13:21:03.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka listeners and advertised.listeners — What are they and what do they do?</h3><h4>Providing clarity to the Kafka configuration parameters listeners and advertised.listeners and demistifying their purpose</h4><h4>Kafka has a large number of configuration parameters. Most of them are relatively easy to understand when one has a conceptual understanding of Kafka’s architecture. Two parameters which have confused me for a long time are listeners and advertised.listeners.</h4><h4>I wish there was a straightforward explanation as to what these parameters are and what they do. Hopefully this article will provide that.</h4><h3>The design architecture of Kafka, as it relates to networking</h3><p>Kafka is designed to be a highly available, highly redundant system. Topics have multiple partitions, which facilitates horizontal scalability. Topic partitions are replicated, which provides redundancy.</p><p>The design of Kafka’s networking architecture follows the same principles. Every broker (server) can be connected to multiple physical networks via multiple network interfaces. Most modern servers provide somewhere between 2 and 4 physical network interfaces, and Kafka can make use of those either for redundancy or scalability.</p><p>For example, if one network goes down, another physical network might be available for Kafka traffic to use, thereby increasing redundancy.</p><p>Alternatively, one physical network might be used for inter-broker traffic, and another use for communication with clients, thereby distributing the total amount of network traffic across more than one network, increasing scalability.</p><p>Most databases use a single connection string (URI) to describe how clients should connect to them. Here’s an example from Postgres:</p><pre>postgresql://user@localhost:5432/my_database</pre><p>In the world of Kafka, the closest analogy is the concept of bootstrap.servers. This string is an array of possible network addresses where a client might find a Kafka broker to talk to. We will talk more about the possible types of address which might be used here later.</p><p>Because Kafka is designed to allow brokers to go offline and then catch up with the rest of the cluster state at a later time, the bootstrap.servers string would typically contain the addresses for several “core” brokers which should usually be online and available.</p><p>Kafka is also designed to allow cluster scaling. As a cluster has to deal with larger volumes of data, it is possible to scale the cluster up by adding more brokers. The addresses of these brokers might not be known at the time when a client application is written, because they are to be added in the future as and when necessary.</p><p>As an aside, this is why it is sometimes advisable to initialize topics with the maximum expected number of partitions that may be required (at some future date) rather than limiting the number of partitions to the number of brokers. For example, in a cluster of 3 brokers, a Kafka topic might be initialized with a total of 14 partitions, assuming that 14 is the anticipated maximum number of required partitions for future scalability.</p><p>This configuration is seemingly nonsensical. With 3 brokers, we will be limited to roughly 3x throughput (at a maximum) — and will not obtain the full 14x throughput with 14 partitions. (Since each broker has to manage multiple partitions, we may even see a performance reduction.)</p><p>However, it is far easier to migrate a partition from one existing broker to a new one than to add more partitions to a topic. (This cannot be done, except by creating a new topic with more partitions and streaming the existing data from the existing topic to the new topic.)</p><p>To summarize this section, bootstrap.servers will contain an initial set of broker addresses which are always expected to exist, and the full set of brokers currently connected together in a cluster will be returned to a client when it asks for them when first connecting to one of those brokers from the choice given in the bootstrap.servers string. The additional brokers which are not part of this string might be in some sense “dynamic”.</p><h3>listeners and advertised.listeners</h3><p>Great, now we know a little about the design considerations of Kafka, and anticipate that a Kafka broker might be expected to run on a host with multiple network interfaces, we can more easily understand the configuration options listeners and advertised.listeners.</p><p>They are actually relatively straightforward -</p><p>listeners:</p><ul><li>listeners tells the Kafka process what physical network interface it should open a listening socket to.</li><li>We don’t usually talk about physical network interfaces in terms of their hardware names ( eg eth0). This is the wrong level of abstraction. We don’t care what physical network our traffic is sent to. Rather, we care about the virtual network described by ip networking addresses. Therefore, we speak in terms of ip addresses. A physical network adapter should have 1 or more ip addresses assigned to it.</li><li>So listeners just tells the Kafka process which network adapter and port number to use to initialize a listening socket.</li><li>This is exactly the same as a regular SQL database. Usually a single listening socket is opened with a particular port number.</li><li>As mentioned earlier, there could be multiple network interfaces for a host on which Kafka is running. This is particularly likely in a datacenter where “proper” server hardware is in use. (I run a Kafka cluster at home in a janky setup composed of random consumer PCs. They each have a single network adapter, and my home network consists of a single network, not multiple. So I don’t usually “see” this important distinction — you may be in the same boat if you are setting up Kafka in a similar manner, or using Docker.)</li></ul><p>advertised.listeners:</p><ul><li>This is the address clients should use to connect to the Kafka broker.</li><li>Each broker specifies one or more such addresses which can be used to talk to the broker.</li><li>Addresses could be some combination of ip addresses or dns addresses.</li><li>Examples: 192.168.0.1:9092, kafka1.prod.examplecompany.com:9092.</li><li>Each broker specifies addresses for itself, and none of the others. All of these addresses will be aggregated together and sent back to a client when a client first connects.</li><li>The advertised.listeners parameter becomes confusing because some of these addresses are redundant (ie pointless). At least 1 of them <strong>must</strong> be specified in the client application in the bootstrap.servers string. Otherwise the client doesn’t know how to connect to <strong>any</strong> of the Kafka brokers. <strong>It must know about at least one broker in advance, however typically several broker addresses would be provided for redundancy.</strong></li><li>It is key to realize that the bootstrap.servers address should contain a list of static broker addresses. These are for brokers which should always be online.</li><li>Over time, a Kafka cluster might expand and new brokers might be added. The client application will not know the addresses of these brokers (unless the client application is updated) therefore any remaining broker addresses are returned to the client when the client first connects.</li><li>The addresses of “dynamic” brokers (ones which were added at a later date) <strong>will have addresses which are not contained in the</strong> bootstrap.servers <strong>string.</strong></li></ul><p>There is one further point to recognize -</p><ul><li>If advertised.listeners is not specified, then listeners will be used in its place. This will (might) work if listeners is an address like 192.168.0.1:9092, but not if it is set to localhost:9092.</li></ul><p>Great, so we now understand that listeners is used to configure a running Kafka process to open listening network sockets on particular network address and port numbers, and advertised.listeners is just a declaration of the address other clients should use to talk to us (the broker). All of these addresses will be grouped together and returned to a client when the client first connects. The addresses may match the bootstrap.servers configuration string which is present on the client side, or there may be additional broker addresses which are not included in the client side bootstrap.servers string.</p><h3>Example configuration with a single machine, localhost</h3><p>Let us now explore some example configurations, and see what we might set both configuration parameters to.</p><p>The simplest cluster setup is a single Kafka broker running on a machine, localhost, with a client application running on the same host.</p><ul><li>We configure listenersto be localhost:9093, and we leave advertised.listeners to be unspecified. It defaults to localhost:9093 using the value from listeners.</li><li>The Kafka process knows the address and port number to bind to and listen on.</li><li>The bootstrap.servers string should be set to localhost:9093on the client side.</li><li>The client is able to successfully connect to the broker. The broker returns the entire set of possible addresses to the client, which in this case is just a single address localhost:9093, and the client continues to use this for future communication.</li></ul><p>What happens if we run multiple Kafka brokers on the same machine, as part of a cluster?</p><ul><li>In this case, each instance of Kafka will require a different port number. We might use localhost:9093, localhost:19093, localhost:29093.</li><li>Three instances of Kafka start up, listening to these addresses.</li><li>The bootstrap.servers string on the client must be set to one of these addresses. It doesn’t matter which one. If we want to simulate redundancy, more then one address should be provided.</li><li>For example, we might set bootstrap.servers to be localhost:9093,localhost:19093.</li><li>The client can connect to both brokers. The broker returns the entire set of possible addresses to the client, which in this case is a set of three addresses localhost:9093, localhost:19093, localhost:29093, and the client continues to use these for future communication.</li><li>If we shut down the broker with address localhost:9093, future clients can still contact localhost:19093, and from this obtain the address of the remaining running broker.</li></ul><p>So running clients and brokers on the same host is essentially trivial.</p><h3><strong>Multiple hosts on the same local network</strong></h3><p>Let’s see what configuration is needed to run a Kafka cluster on a local (private) network. Here’s some detail about out network topology:</p><ul><li>A set of 3 Kafka brokers are running on 3 hosts connected to the local network. Their ip addresses are 192.168.0.1, 192.168.0.2, 192.168.0.3. In each case, the port number is 9093.</li><li>A client is running on the same network, with address 192.168.0.100.</li></ul><p>In this case, listeners set to localhost:9093 isn’t going to cut it. If we (the broker) declare localhost to be the address clients should use to contact us, then the client running on the host with address 192.168.0.100 will try to connect to itself on port number 9093. There is no instance of Kafka running on 192.168.0.100, so that will fail.</p><p>There are two options which will work here.</p><ul><li>Set listeners to the host ip address eg 192.168.0.1:9093. This will now work because advertised.listeners will use it as the default.</li><li>Leave listeners set to localhost:9093 and set advertised.listeners to 192.168.0.1:9093.</li><li>(Additionally this will also work:) Set both to be the same 192.168.0.1:9093. But it is redundant.</li></ul><h3>Clients connecting from the internet (external network)</h3><p>This is the more common situation, unless you are hosting your own Kafka cluster at home as part of a private network. This option applies to any situation where the Kafka brokers are running behind a NAT network. That includes running Kafka inside a Docker container, and also possibly virtual machines.</p><p>Again, let’s summarize the network topology:</p><ul><li>A set of 3 Kafka brokers are running on 3 hosts inside a private network. Let’s assume the same private IP addresses as before.</li><li>This time, the client runs on an external network. It must connect via the internet. The client address doesn’t really matter that much, just know it is on some totally separate network.</li><li>The private network, like most private networks, sits behind a router performing NAT. The routers external facing address might be something like 8.8.8.8.</li><li>Let’s assume port forwarding is enabled, and that</li><li>8.8.8.8:9093 is forwarded to 192.168.0.1:9093</li><li>8.8.8.8:19093 is forwarded to 192.168.0.2:9093</li><li>8.8.8.8:29093 is forwarded to 192.168.0.3:9093</li></ul><p>You can probably anticipate the result. This time neither localhost nor one of the internal 192.168.0.X addresses will be contactable from the client.</p><p>We have to set the advertised.listeners to 8.8.8.8:9093, 8.8.8.8:19093, 8.8.8.8:29093.</p><p>The clientbootstrap.servers string must contain at least one of these addresses, likely more than one. When the client first contacts one of the brokers using the addresses it knows in advance, it will pick up any remaining addresses which it does not yet have.</p><p>However, in the case of the broker listeners parameter, this must now be set independently to the advertised.listeners value. 8.8.8.8 wouldn’t make any sense, because the brokers are presumably not the same host as the device performing NAT routing, and so none of the brokers know about the external facing address 8.8.8.8. They must be set to either localhost or one of the internal192.168.0.X addresses assigned to one of the network interfaces as before.</p><h3>Docker</h3><p>The configuration for Kafka brokers running inside a docker container is essentially the same as above. If you are running Docker on a host which is inside a private network, and clients wish to connect to the Docker containers over the internet, then there is one additional hop in the chain.</p><p>Clients should connect to 8.8.8.8:PORT as before, since they need to contact the NAT router which will then forward the address to the host on which the Docker containers are running. That means advertised.listeners is unchanged.</p><p>The NAT router should forward traffic destined for ports 9093, 19093 and 29093 to addresses 192.168.0.1:9093, 192.168.0.1:19093, 192.168.0.1:29093, assuming that the Docker container host is the machine with the address 192.168.0.1.</p><p>Finally, Docker needs to be configured to forward traffic from the ports 9093, 19093, 29093 on the host to the ports used by Kafka running inside each Docker container. Let’s assume in all 3 cases port 9093 is used.</p><p>For example, the full chain might look like:</p><pre>8.8.8.8:9093 -&gt; 192.168.0.1:9093 -&gt; kafka1docker:9093<br>8.8.8.8:9094 -&gt; 192.168.0.1:9093 -&gt; kafka2docker:9093<br>8.8.8.8:9095 -&gt; 192.168.0.1:9093 -&gt; kafka3docker:9093</pre><p>We could of course have multiple hosts running different Docker containers. In which case, we simply substitute out the address 192.168.0.1 for the address of the host running the Docker container instance we wish to talk to.</p><h3>Summary</h3><p>If you take one thing away from this guide, let it be this:</p><p>In all cases, there are two simple questions to answer:</p><ul><li>what network interface should I (a Kafka Broker) open a listening socket to?</li><li>what address should clients use to contact me?</li></ul><p>The first question dictates which ip address should be used by any particular Broker for the listeners parameter. It must be an ip address assigned to one of the network interfaces belonging to the Broker.</p><p>The second question dictates the ip address of fully qualified domain name which should be used for the advertised.listeners parameter. If the Kafka host is behind a NAT router, behind a NAT VM network, or running inside a Docker container host, this address must be “visible” (contactable) from wherever the client application is intended to run.</p><p>Finally, the bootstrap.servers parameter will usually be a subset of all the advertised.listeners addresses for the whole Kafka cluster, but it doesn’t have to be. It must at a minimum contain 1 contactable address, and at most it can contain the whole lot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b004e2eb93d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom C++ STL Compliant Iterators — an a guide to implementation]]></title>
            <link>https://medium.com/@fintechdevlondon/custom-c-stl-compliant-iterators-an-a-guide-to-implementation-64f7359e580f?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f7359e580f</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[standard-template-library]]></category>
            <category><![CDATA[iterator-design-pattern]]></category>
            <category><![CDATA[iterator-pattern]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 12:18:16 GMT</pubDate>
            <atom:updated>2023-03-30T12:18:16.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom C++ STL Compliant Iterators — an a guide to implementation</h3><p>This is a post about implementing Standard Template Library compliant iterators with C++.</p><p>STL compliant iterators are relatively easy to implement. Many software engineers avoid writing them because they <em>seem</em> like they might be difficult, and because their implementation involves a lot of excess boilerplate code.</p><p>This article is about writing an iterator implementation for an existing MFC container. There is plenty of useful STL engineering information here, but with more emphasis on how the implementation developed over time. It explains different possible implementations in more detail.</p><p>If you want a complete code example containing nothing but hardcore engineering information, see my other recent article on the same subject.</p><p><em>Some backstory… you can skip over this if you’re not interested…</em></p><p>Before moving to Fintech I used to work at BAE Systems. I didn’t stay very long at the company before moving. (A bit less than a year.) One of my most notable achievements while I was there was an implementation of STL compliant iterators for a container which was written well before the times of modern C++, and certainly didn’t support iterators.</p><p>As an aside, this actually sounds kind of negative. <em>Your highest achievement was writing an iterator?</em> It’s not particularly impressive. There’s a bit of a backstory to that too…</p><p>If I remember correctly, my code didn’t pass code review. The reason given, by my direct manager, was because custom iterator implementations were considered “too difficult” for the average engineer to understand. This particular person, although impressed with the code, was concerned that if it were to be merged, future engineers would struggle to learn about these “complicated” iterators in order to understand the code.</p><p>… Do I need further explanation as to why I left?</p><p>The code that I had written was quite elegant, and provided a modern interface to a legacy class for iteration. It’s a shame it never made it into production, especially as the slightly less experienced engineer who I was working with at the time was really impressed with the implementation and excited by what had been done.</p><p>He was a bright young guy, I hope he’s doing well.</p><p>The Microsoft Foundation Classes (MFC) framework includes a template object called CArray . It takes two template types, the type used to index the elements, and the type of the elements.</p><p>The API provides a few things which we are interested in.</p><ul><li>operator[](index) Return the element at the specified index . (No bounds checking.)</li><li>GetCount() Return the total number of elements in the container.</li></ul><p>There are several advantages to using iterators rather than indexes to iterate through a container. Firstly, iterators provide safety from accessing an out of bounds index, something that CArray::operator[] does not provide.</p><p>More importantly, iterators enable the use of algorithms via the STL &lt;algorithm&gt; library. If I recall correctly, we wanted to sort the elements, and the idea was to use an std::vector to do that.</p><pre>CArray&lt;int, int&gt; carray;<br>std::vector sortableContainer(begin(carray), end(carray));</pre><p>In order to populate the vector with the data from carray we needed read-only forward iterators. We need something that will be returned by two new functions begin and end which we will add to our codebase.</p><p>A simple implementation would look like this.</p><pre>template&lt;typename T, typename U&gt;<br>auto begin(const CArray&lt;T, U&gt; &amp;array&gt;)<br>{<br>    return &amp;array[0];<br>}<br><br>// This only works for containers where higher index elements<br>// are guaranteed to be at higher value memory addresses.<br>template&lt;typename T, typename U&gt;<br>auto end(const CArray&lt;T, U&gt; &amp;array&gt;)<br>{<br>    if(array.GetCount() &gt; 0)<br>    {<br>        // The last element is at `index = array.GetCount() - 1`<br>        // Therefore `&amp;array[array.GetCount() - 1]` is a valid<br>        // pointer to an element which exists.<br>        // We add 1 to this pointer to get something resembling<br>        // the concept of an `end` iterator.<br>        return (&amp;array[array.GetCount() - 1]) + 1;<br>    }<br>    else<br>    {<br>        // Can&#39;t do `array[GetCount() - 1]` when size is 0<br>        return &amp;(array[0]) + 1;<br>    }<br>}</pre><p>While this works, it isn’t very nice. The use of raw pointers here is a bit suspicious. Since the elements of our container are all of a fixed size, it is legal to +1 to a pointer which points to the last element. It works because the elements allocated by a carray are all in a continuous block of memory.</p><p>But still, in order to have an end iterator, we resorted to creating a pointer which is invalid. We wouldn’t normally expect to be able to dereference an end iterator. Regardless, the solution is a bit of a hack.</p><p>In addition, there is an exceptional case for when the size of the container is 0. It’s doubly horrible as we now have two invalid pointers in use. Looking back at this today I am not totally convinced the implementation is correct. The behaviour of end changes when the size is zero, and returns a pointer which is next to the pointer returned by begin . That isn’t correct because in a for loop, like the one below, the logic will execute once before the loop exit.</p><pre>for(auto it = begin(carray); it != end(carray); ++ it)<br>{<br>    // still happens once when length of carray is zero<br>}</pre><p>Overall this gives an impression of bad code which is hard to reason about. The fact that nobody else who looked at this code recognized the bug suggests that the code is difficult to understand, hence nobody spotted it.</p><p>We need a better solution, using things which are designed to be used with the API provided by CArray .</p><p>In our toolbox we have:</p><ul><li>operator[](index)</li><li>GetCount()</li></ul><p>This suggests our solution should be built using an index, rather than memory addresses. Indexes are a higher level of abstraction than memory addresses, and the API is written in terms of them.</p><p>To build an iterator class, we need several things.</p><ul><li>Initialize it in a valid state referencing an element of the associated container, or in some other valid state which corresponds to the “end” state</li><li>Advance the iterator reference by 1</li><li>Dereference the iterator (or throw an exception if the iterator is at the end)</li><li>begin and end functions</li></ul><p>We sketch something out along the following lines.</p><pre>template&lt;typename T, typename U&gt;<br>class CArrayIterator<br>{<br><br>private:<br><br>    CArray&lt;T, U&gt; &amp;m_array_ref; // Hold a reference to the container<br>    U m_index;<br>};</pre><p>The implementation details are relatively straight forward. The constructor should maintain a reference to the underlying container object. It must be initialized with an index, which we should check is valid.</p><pre>CArrayIterator::CArrayIterator(CArray&lt;T, U&gt; &amp;array_ref, const U index)<br>    : m_array_ref{array_ref}<br>    , m_index{index}<br>{<br>    // Note that index = GetCount() is valid, because this is the<br>    // &quot;end&quot; iterator state.<br>    if(index &lt; 0 || index &gt; array_ref.GetCount())<br>    {<br>        throw std::out_of_range();<br>    }<br>}</pre><p>We need a way to increment the iterator.</p><pre>CArrayIterator&amp; CArrayIterator::operator++()<br>{<br>    ++ m_index;<br>    return *this;<br>}<br><br>CArrayIterator CArrayIterator::operator++(int)<br>{<br>    CForwardArrayIt tmp(*this);<br>    ++(*this);<br>}</pre><p>We need to be able to compare two iterators. To implement this, we first check if two iterators reference the same container, and if so we compare their indexes.</p><pre>friend bool operator==(const CArrayIterator&amp; lhs, const CArrayIterator&amp; rhs)<br>{<br>    if(&amp;(lhs.m_array_ref) == &amp;(rhs.m_array_ref))<br>    {<br>        return lhs.m_index == rhs.m_index;<br>    }<br>    return false;<br>}<br><br>friend bool operator!=(const CArrayIterator&amp; lhs, const CArrayIterator&amp; rhs)<br>{<br>    return !(lhs == rhs);<br>}</pre><p>Finally, we need to be able to dereference an iterator.</p><pre>T&amp; operator*() const<br>{<br>     if(m_index &gt;= 0 &amp;&amp; m_index &lt; m_array_ref.GetCount())<br>     {<br>         return m_array_ref[m_index];<br>     }<br>     else<br>     {<br>         throw std::out_of_range();<br>     }<br>}</pre><p>The whole implementation is done using the API provided to us by the underlying container type.</p><p>To make our iterator implementation compatible with standard library algorithms, including range based for, we require begin and end helper functions.</p><pre>// Range based for<br>for(const auto&amp; element: container) // ...<br><br>// Same as<br>for(const auto it = begin(container); it != end(container); ++ it) // ...</pre><p>These are simply instantiations of an iterator object with the index set correctly.</p><pre>template&lt;typename T, typename U&gt;<br>auto begin(CArray&lt;T, U&gt; &amp;array)<br>{<br>    return CArrayForwardIt&lt;T, U&gt;(array, 0);<br>}<br><br><br>template&lt;typename T, typename U&gt;<br>auto end(CArray&lt;T, U&gt; &amp;array)<br>{<br>    return CArrayForwardIt&lt;T, U&gt;(array, array.GetCount());<br>}</pre><p>No where in our code does any variable or pointer contain invalid state. The value of m_index is always valid, and compared to the pointer implementation our code is easy to comprehend.</p><p>Finally, we can use our iterator as intended.</p><pre>CArray&lt;int, int&gt; array;<br><br>// construct vector from elements of array in one line<br>std::vector&lt;int&gt; vector(begin(array), end(array));</pre><p>For a full code example, see my other article about implementing an iterator for a custom memory allocator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f7359e580f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Review: Design Patterns (GoF)]]></title>
            <link>https://medium.com/@fintechdevlondon/book-review-design-patterns-gof-3bc011e12b33?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bc011e12b33</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 17:02:47 GMT</pubDate>
            <atom:updated>2022-12-21T17:03:26.188Z</atom:updated>
            <content:encoded><![CDATA[<p>The original Gang of Four (GoF) text from 1995. Is it still useful in 2022?</p><h4>Design Patterns by Gamma, Helm, Johnson and Vlissides</h4><p>This is the original Design Patterns bible. It is referenced by numerous questions on Stack Overflow, and it is generally considered to be one of the most important texts for any Software Engineer working with Object Oriented languages.</p><p>I believe this text was originally printed around 1995. My copy has a copyright with this year stamped next to it. As such, this book is dated. It particularly shows its age in that some of the examples are provided in Smalltalk. I have heard of Smalltalk, but never used it. As far as I am aware it is a language which fell out of common use at least 20 years ago.</p><p>Some examples are provided in C++. Despite the fact that this book was printed considerably before the release of the C++ 03 standard, the C++ examples are easily readable to any C++ developer in 2022, due to the fact that core concepts such as inheritance haven’t changed in the language since the early days.</p><p>So let’s cut to the chase. Is it still useful? Should a graduate student seeking to develop his engineering abilities invest in this text? I would argue yes — and for two reasons.</p><h4>Reason 1</h4><p>The obvious reason for buying the GoF book is because the information contained within is still of relevance today. The design patterns presented are still in use today, and the information is still useful and practical.</p><p>The Smalltalk examples are obviously less approachable, but it is not too much of a hinderance since the text provides diagrams and explanation detail. The examples are nice to have, but somewhat redundant.</p><h4>Reason 2</h4><p>The second reason relates to the history, and consequences, of the publication of this text.</p><p>The GoF book has had a significant impact on the software engineering world when it comes to nomenclature. The whole purpose of studying this somewhat academic and occasionally esoteric field is to be able to identify, name and categorize frequently used patterns of code. That is what this book is all about, and the categorizations and names used by the authors have proliferated throughout the industry.</p><p>Reading this text will give you a good understand of exactly what is meant by an “Abstract Factory” or “Template Method”. (The definitions are not exactly intuitive in all cases. For example, the Template Method has nothing to do with templates and the type system.)</p><p>It will also give you some idea of the state of the field in the mid 1990’s. This was a period of time where the industry was trying to figure out how to scale software systems. In the 1980’s, software engineers didn’t have to deal with complex Operating Systems, multi user environments and multi-process environments, but by the 1990’s Windows was here, and engineers had to deal with megabytes of memory not just kilobytes.</p><p>I won’t dwell on this point, but it was a period of time where computers scaled to such an extent that while in the 80’s a single engineer could produce a commercially successful game with a couple of weeks of engineering, in the 90’s game studios spawned and whole teams of engineers were working on projects for years at a time. The example applies to other software products of course, not just games.</p><h4>This book is not the most approachable</h4><p>Smalltalk aside, this book is not the easiest read. While some patterns are relatively easy to understand conceptually, others are abstract and difficult to conceptualize. I came from a background of having a solid understanding of the C++ language, and while I could understand literally how the compiler would interpret the examples presented in the book I didn’t always understand exactly what the purpose was.</p><p>It seems that real world experience of some of the problems addressed by the patterns is necessary to fully understand them. Now with a couple of years of industry experience, I have seen some of the patterns in real world applications as well as being able to address problems previously seen in my own personal projects. Consequently, the text is much easier to understand with this experience.</p><p>I want to make the following point. Imagine you wanted to learn a new programming language. For example, consider the jump between learning Python and C++. Some aspects of C++, particularly things like pointers, manual memory management, and multiple inheritance, would be difficult to understand for a Python programmer on first reading, because they are unfamiliar concepts. However, re-reading the relevant sections a couple of times and trying to compile some example code is likely to clarify the details.</p><p>Not so with this text. If you want to understand the Abstract Factory in detail, then you really need to have prior experience with a real world example problem, which this pattern can solve.</p><p>The examples provided in the book are sometimes helpful, and sometimes just as difficult to understand as the pattern itself. This is the nature of design patterns. Some situations arise rarely and it is difficult to think of a good example problem, which contains all the necessary detail without being overly complex. Some patterns address one specific case and don’t have a more general application.</p><p>Something useful to be aware of is that there is a book about this book. <em>Design Patterns Explained</em> by Shalloway and Trott. This book explains some of the Design Patterns from GoF in more detail, with more context for real world use cases. I highly advise reading this book as well, as it makes the GoF book much more approachable. Shalloway and Trott don’t explain everything covered by GoF however, so it isn’t a substitution or replacement.</p><h4>What you’ll get from it</h4><p>Here is an overview of some of the patterns presented, with a brief summary of each.</p><ul><li>Abstract Factory. You have a set of objects which you might want to create. A factory can create those for you depending on some input or parameter. An abstract factory differs slightly in that you define multiple factories with inheritance, and each different implementation returns a different set of the same types of objects. A common use case is in testing, where you want a real and fake implementation of a set of C++ classes.</li><li>Adapter, Façade, Decorator. Modify an existing class or set of classes by adapting its interface to be compatible with something else (Adapter), providing an interface which simplifies access or pretends to be something else (Façade), or adds additional functionality (Decorator). They are all quite simple in concept, objective and implementation.</li><li>Factory Method and Template Method. Use a base class to define the structure of an algorithm for creating objects (Factory Method) or performing some operation (Template Method). Subclasses modify the exact behaviour polymorphically.</li><li>Flyweight. Reduce memory footprint by decomposing large objects with repeated data into smaller objects which reference a single copy of the repeated data. Can be used in the context of rendering text glyphs or images, but there are many other potential uses.</li><li>Interpreter. Define a representation for a language grammar using objects. I haven’t used this one myself in the real world, and there are whole books on the subject of writing interpreters which probably explain the concept more clearly. Don’t buy just for this section, but it is a useful inclusion.</li><li>Iterator. Provide a way to iterate through a collection of objects using an object. I have actually written STL style iterators without the use of this book, but it will likely be useful to someone who hasn’t had this level of exposure.</li><li>Observer. A pattern which allows you to connect events to observers. Think “signals and slots”.</li><li>Singleton. Despite being somewhat disfavoured these days, it is useful to know of its existence. If you want to know why it has fallen out of favour with designers, there is a detailed explanation in Nystrom’s <em>Game Programming Patterns.</em></li><li>Strategy. Define an operation in a object and allow different operations to be used interchangeably.</li><li>Visitor. Define interchangeable operations which “visit” a set of objects.</li></ul><p>This is not an exhaustive list. There are other patterns which I am less familiar with including the Command, Chain of Responsibility, Memento and State, among others.</p><p>Compared to other design patterns texts, this is the most exhaustive.</p><p>In summary then, this should be considered essential reading for the serious OOP software architect. Although comprehensive in the number of patterns which are included it falls short in a few ways. Each pattern could benefit from more detailed and approachable explanation. The book could have easily been twice the length without being overly verbose. The Smalltalk examples are outdated. For many examples it is difficult to understand “what is the point” or “what problem is resolved”. And finally, many patterns seem to be closely related or similar, but there is no mention of this anywhere within the text. This, I think, is the greatest shortcoming.</p><p>Regardless of the above, this is still a worthwhile text to study in 2022, and it will likely remain so for many years because of the wealth of information contained within and because the range of patterns included is so extensive. Essential reading for serious engineers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc011e12b33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Review: Game Programming Patterns by Nystrom]]></title>
            <link>https://medium.com/@fintechdevlondon/software-book-review-game-programming-patterns-by-nystrom-8a7d403fc9e7?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7d403fc9e7</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[optimization-techniques]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Sat, 13 Aug 2022 20:36:14 GMT</pubDate>
            <atom:updated>2022-08-13T20:39:09.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Game Programming Patterns by Nystrom, front cover" src="https://cdn-images-1.medium.com/max/1024/1*5h-IF07VOZmFVEfcAoIxYg.jpeg" /></figure><p><em>Worth its weight in gold, this is a book which has absolutely nothing to do with Games Programming</em></p><p>Books about Design Patterns usually have a reputation for being abstract and difficult to read. Not in this case. Nystrom provides clear examples which clarify the matter at hand quickly. None of the chapters are particularly lengthy, and I didn’t find myself becoming lost in a long, dense, meandering text about highly theoretical aspects of Object Oriented Programming.</p><p>If you have found yourself struggling to get through a chapter of even the more approachable Design Patterns books, I would highly recommend reading this one.</p><p>I first encountered Nystrom as an author when I ordered another of his books <em>Crafting Interpreters.</em> I bought this some months ago when I was interested in learning about how the internal machinery of compilers work. While the book is about writing an interpreter for a language that Nystrom himself developed, it turns out that compilers and interpreters do a lot of the same operations when it comes to parsing text — perhaps unsurprisingly.</p><p>I was initially somewhat sceptical about my purchase, until I read a few pages. Not only did I not realize quite how much overlap there is between the technology behind both compilers and interpreters, but the book was genuinely <em>interesting</em> to read — which kept me hooked.</p><p>… at least until about half way — then I got distracted by an idea for another project and put it down for a while. But I will definitely pick it back up again — soon.</p><p><em>Game Programming Patterns</em> was a similar experience. The title made me initially sceptical. I have no interest in programming games — or at least I thought so before reading it.</p><p>It turns out that the technology behind games programming, at least in terms of program structure, design patterns and optimization is surprisingly interesting. I say <em>surprisingly </em>interesting because for my day job I write business logic code, which is essentially an elaborate interface to a very large and complex database. To most, this is probably the most obscenely boring area of the software engineering industry, however it does pay exceptionally well — which is why I took the job.</p><p>I didn’t consider myself likely to be interested in <em>games programming</em>, because this area of the industry has a reputation for being just as difficult in terms of the actual engineering but with thin pickings when it comes to financial opportunity.</p><p>Perhaps this is an unfair assessment? If you are a games developer, I hope I haven’t offended you, but if a software engineer wants a big salary, he is usually advised to focus his attention towards Finance or FAANG.</p><p><em>Game Programming Patterns</em> is not about <em>games programming</em>. Not really. While it may contain examples oriented towards programming games, the majority of the ideas and information in this book is applicable to a wide variety of high performance software engineering applications.</p><p>What makes this book unique is that the ideas are totally different to any other Designs Patterns book I have encountered before. Here are a few examples:</p><ul><li>Double Buffer. While the example given is related to game engines and graphics double buffering, this pattern has far reaching scope beyond graphics and real-time rendering. In reality, this is a <em>general optimization or synchronization pattern.</em> It is about being able to maintain the current state of a system for reading, while simultaneously writing data about the next state of a system, without those two operations trampling all over each other.</li><li>Event Queue. This is not a new idea, but I have never seen the concept explained quite so clearly. One of my favourite chapters.</li><li>Component and Service Locator. Again these are not especially difficult concepts, although with most books they turn out to be. Nystrom has a unique take on the Component pattern which I have not seen before, where a class composed of subcomponents is reduced just to a collection of IDs. The Service Locator pattern is a better name for what most authors describe as a type of Factory pattern. The Service Locator is a bit more specific in that in Nystroms description the “Factory” has to be set to provide some resource which it then later can be used to obtain a handle to. It is easy to see how this pattern could be adapted to provide a default resource if something closer to the traditional factory was required.</li><li>Optimization Patterns. There are several chapters on optimization including Dirty Flag, Object Pool and Data Locality. Again, Nystrom does an excellent job in making the reader aware how important the layout of data in memory is, and how optimizing data is just as important or possibly more important than optimizing executable code.</li></ul><p>What is important here is that these ideas are extremely valuable, and flexible. They are powerful ideas which have wide range of potential use cases, far beyond that of game engines. They are often related to performance. Games are real-time systems, with rigid restrictions on how much calculation needs to be done within a fixed time window. The majority of the ideas presented by Nystrom are applicable to any high performance software system.</p><p>If you haven’t worked on a software team responsible for implementing a AAA game engine before (I haven’t) then I would highly recommend reading this book. I am quite sure there will be something for a wide range of audiences here, from graduates with a couple of years of industry experience to mid-level and senior developers who haven’t happened to encounter some of these ideas before by fact of working in a different industry.</p><p>Fundamentally, this is a book about Design Patterns, software architecture and optimization — and it’s rare to find a book where such complex subject matters are explained in such a clear and succinct manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7d403fc9e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Visitor Pattern — Design Pattern Experiments with C++ 20]]></title>
            <link>https://medium.com/@fintechdevlondon/the-visitor-pattern-design-pattern-experiments-with-c-20-74853f9d9ddb?source=rss-cfd4a6c02058------2</link>
            <guid isPermaLink="false">https://medium.com/p/74853f9d9ddb</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[cplusplus20]]></category>
            <category><![CDATA[visitor-pattern]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[FinTechDev]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 18:17:23 GMT</pubDate>
            <atom:updated>2022-02-06T18:17:23.216Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Visitor Pattern — Design Pattern Experiments with C++ 20</h3><p>For those with an aspiration to enter the world of FinTech, there are typically three main subjects which I recommend building a firm foundation in. These are Core Language Skills (eg: C++), Software Design Patterns and Data Structures and Algorithms. The Core Language of choice is actually not that important, but given that C++ is used throughout the industry, it is a good language to build a strong understanding of.</p><p>My knowledge of Software Design Patterns is not as strong as my other skills, partly because one can only really obtain a firm understanding of the subject matter through experience with relevant real-world problems. Today I am going to walk though a simple example of the Visitor Pattern. This is one of the more frequently used patterns, and it is therefore a good starting point to break into the subject area. In addition, our example will provide ample opportunity to flex modern C++ 20 features, such as Lambda functions (closure) as well as extensive use of the STL Algorithms.</p><p>As a prerequisite, you should be reasonably familiar with polymorphism. It would also be helpful to understand what a lambda function is, as well as familiarity with some STL algorithms such as for_each , accumulate and transform . The C++ code presented here is not overwhelmingly complicated, but it does touch on some more advanced concepts. As I note elsewhere in the article, I deliberately avoid the use of templates, as this would certainly make the code harder to understand on a first reading.</p><p>The basic idea underpinning the Visitor is that we wish to differentiate between our data types and the operations which can be applied to those data. In this example, we will have a class hierarchy containing three very different classes each containing different types of data. This will be used in combination with a class hierarchy containing three different classes for operations which can be performed on our data types.</p><p>In order to make the examples clearer and easier to follow, I decided to avoid extensive use of template types. However, we will still make use of the template types from the STL. I hope this will not obfuscate the learning process.</p><p>Without further ado, let us jump into some code — just as soon as we have reviewed the design decisions. By the way, the full source code can be obtained from Github. See the link below.</p><p><a href="https://github.com/FinTechDevLondon/Visitor-Pattern">GitHub - FinTechDevLondon/Visitor-Pattern: Visitor Pattern Experiments with C++ 20</a></p><h3>Data Operations</h3><p>I actually thought of the operations that I wanted to use to demonstrate the Visitor before I thought of the data types, so it makes sense to discuss those first.</p><p>The three operations we will use are Addition, Multiplication and XOR. These three operations are easy to understand, and we will be able to verify the results obtained using something like Python or a calculator. They have the advantage of being operations that you (probably) are already familiar with.</p><p>Although these are simple operations you have (probably) already seen before, they become interesting when we use them in conjunction with the Visitor Pattern, after the data types have been defined.</p><p>Actually, there will be two data types for which the XOR operation doesn’t make much sense. However this is advantageous from an education perspective, as it will allow us to demonstrate the use of exceptions to handle those cases at runtime. (Since there is no way to “catch the problem” at compile time.)</p><p><strong>The Abstract Base Class</strong></p><p>The AbstractVisitor base class contains 3 pure virtual functions, one for each data type that the visitor classes will be able to operate on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/080cacaf61e7dfb9e14fc676b5690dd5/href">https://medium.com/media/080cacaf61e7dfb9e14fc676b5690dd5/href</a></iframe><p><strong>A Visitor Implementation</strong></p><p>The below snippet shows the class for just one type of “concrete” Visitor. It is not too complex to understand. The class contains a single member variable to store the result of repeated calculations. The 3 pure virtual functions from the abstract base are now implemented, although we have not yet seen the objects themselves.</p><p>Without knowing anything about the implementation of the data types, it can be seen that the SingleElement type provides a way to access its data through a GetValue method. This data is added to the internal member variable, which simply holds the result of the calculations (the sum).</p><p>The logic for the other two types, ArrayElement and StringElement is slightly more complex. ProcessArrayElement applies the function accumulate from the STL algorithm library to every element of the vector containing the data to be summed. In this context, accumulate simply adds the elements starting from the initial value of 0.0 . accumulate can be used in other ways to apply a binary function to all elements of a container, and this can be seen in the following function.</p><p>The ProcessStringElement also makes use of a accumulate , although this time a lambda function object is used to implement more complex logic. The lambda checks the elements of the string container to see if they are within the range of characters 0 to 9 . If such numerical characters are found, then the character code is converted into a numerical value, and this is added to the sum.</p><p>The code below demonstrates how a Visitor class can be used to apply specialized logic to a set of data types, depending on the type. In this case, the purpose of the Visitor is to compute the “generic sum” of whichever type of data it is applied to.</p><p>We consider the “sum” of a type containing one double to be the trivial sum of the values stored in each element. The “sum” of a type containing an array (vector) of double is the (somewhat) trivial sum of every element in every vector.</p><p>The “sum” of objects containing strings is the sum of the numerical values of each individual numerical digit in the string. All non-numerical characters are ignored. This might seem a bit unusual, but this is useful to demonstrate the very different logic which is applied to each of the three data types.</p><p>We also had the opportunity to combine accumulate with a lambda function, which makes things quite interesting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/334f2b1245e0b22ff71d7b0450955df9/href">https://medium.com/media/334f2b1245e0b22ff71d7b0450955df9/href</a></iframe><p>The remaining Visitor types can be found in the source code. The logic for the remaining two classes is similar, with the exception of the class which is responsible for computing the xor operation. In this case, an exception is thrown when applied to data types for which there is no straightforward xor calculation. This is to aid the readers understanding as much as it demonstrates the use of exceptions to handle cases for which there exists no sensible logic which can be implemented.</p><h3>Data Types</h3><p>The data types I have chosen are somewhat esoteric as they don’t really represent anything which has an analogy in the real world. On the other hand, they are simple to understand.</p><p>There will be one type which contains a single double variable. Another which contains an array (vector) of doubles. And finally another type which simply contains a string.</p><p>But don’t be dismotivated! Although not particularly inspiring, the data types are all quite different and will require different logic to handle each of the cases. The simplicity of each object should help to clarify the Pattern.</p><p>Let us just take a look at one of them. The array data type. As the class is quite simple there isn’t much to note, other than the Accept function, which takes a polymorphic reference to an AbstractVisitor . The function then calls the ProcessArrayElement function with a this pointer, such that the Visitor can execute the logic for the specific type of visitor on the ArrayElement type.</p><p>If you want to know more about this, do a search for “double dispatch”. However, by following the sequence of function calls it should be fairly obvious what is happening. The “special” part is that the choice of ProcessArrayElement function which is executed depends on the type of visitor , because this is a polymorphic type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c12685be7b8eea9c386a25aab5c1e0/href">https://medium.com/media/35c12685be7b8eea9c386a25aab5c1e0/href</a></iframe><p>You probably already noticed that ArrayElement inherits from AbstractElement . You don’t need to know much about the abstract base class, other than it defines a pure virtual function Accept .</p><h3>main Function Code</h3><p>The below code snippet shows a (slightly modified) snippet from the main function. The first few lines initialize some data types for us to use later. There are two lists, one containing SingleElement types and the other containing ArrayElement types. Finally a StringElement is defined. I couldn’t think of a particularly elegant way to initialize the list of ArrayElement types. It can probably be done in a similar way using transform and a vector&lt;vector&gt; to hold the numerical values. I didn’t have time to investigate it in detail.</p><p>There isn’t that much to say about the remainder of the code. There is a try-catch block enclosing each call to for_each , given that the Visitor objects can throw a runtime_error when applied to an incompatible type.</p><p>Again, a lambda function is used in combination with for_each . I originally wrote this using a functor adapter, and there is an example of how to do this in the full source code. The lambda method is more elegant, although using a named lambda could have reduced code duplication in the main function.</p><p>In order to understand why a functor or lambda is required, first realize that for each applies a function object to every element in the defined range. We can’t apply the Visitor types directly, since these do not define an operator() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdde67d131be85dcc7874abe8606b3b3/href">https://medium.com/media/fdde67d131be85dcc7874abe8606b3b3/href</a></iframe><h3>Output</h3><p>Finally, let us take a quick look at the output of the full code. Here is it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7db2d2d1895ee3170a1b74481ad343f/href">https://medium.com/media/f7db2d2d1895ee3170a1b74481ad343f/href</a></iframe><p>First note that two exceptions were thrown during execution. This is because xor cannot be applied to the ArrayElement and SingleElement types. (At least as I have defined the logic here.)</p><p>All three types essentially contain the same data, so they produce the same results for Sum and Product Visitors.</p><p>The string checksum, produced by xor-ing all characters together, produces the output 48 . We can test this output by changing the string from Hello World 123456789 to Hello World 123456789\1 or Hello World 123456789\2 . This just adds a char with the literal numerical value of 1 or 2. The result of which is that the xor operation result changes by an LSB bit flip or second-to-LSB bit flip. (Appending \1 changes the result from 48 to either 49 or 47. Appending \2 changes the result from 48 to 50 or 46.) One has to know a bit about the binary representation of char and \1 and \2 in order to make sense of this.</p><p>I hope this has made the Visitor pattern a bit more accessible to understand. Have a go with the source code. It should be fairly simple to download and compile. There is a build shell script provided for Linux users. (And since you are reading Design Patterns and are writing C++ code, you must presumably also be a Linux user.)</p><p>It is my aim to write more articles like this on other Design Patterns, with examples. I have no particular preference for which one is next, but it will likely be the Flyweight (which doesn’t get the credit it deserves, probably because most most commentators don’t understand the use cases), or if not the Bridge Pattern. (AKA: PIMPL)</p><h3>External Resources</h3><p>There are several external resources with are worthy of note. In particular, the book <em>Design Patterns, Elements of Reusable Object-Oriented Software</em> serves as the primary reference for the writing of this article. If you are not already familiar with the kinds of problems that can arise when using an object-oriented language such as C++, then this book can be difficult to understand, given that many of the examples are abstract in nature.</p><p>Other resources can be found by searching Stack Overflow for <em>Visitor Pattern</em> tagged with [C++].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74853f9d9ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>