<?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 Spyros Argalias on Medium]]></title>
        <description><![CDATA[Stories by Spyros Argalias on Medium]]></description>
        <link>https://medium.com/@sargalias?source=rss-f8ab8bda909b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HLYpVTCwkw28aG-J.</url>
            <title>Stories by Spyros Argalias on Medium</title>
            <link>https://medium.com/@sargalias?source=rss-f8ab8bda909b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:12:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sargalias/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[Nulls and null checks — How to work safely with nulls in any codebase]]></title>
            <link>https://sargalias.medium.com/nulls-and-null-checks-how-to-work-safely-with-nulls-in-any-codebase-de9ddc592efe?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/de9ddc592efe</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[null]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:06:54 GMT</pubDate>
            <atom:updated>2022-01-03T03:11:48.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nulls and null checks — How to work safely with nulls in any codebase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtV8pVtbdlUdbPtb-r2Fww.jpeg" /></figure><p>An important part of <a href="https://programmingduck.com/articles/clean-code">clean code</a> is handling nulls properly.</p><p>Nulls have been a tricky problem in programming for decades.</p><p>Tony Hoare, the inventor of the null even called it a <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">billion-dollar mistake</a>.</p><p>Semantically, nulls are necessary. They represent the absence of a value. For example, a user may fill in a form that has optional fields. They may leave the optional fields blank. That’s one reason for nulls.</p><p>The problem is that nulls can be difficult to work with and track.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOJOYcfDrGh4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOJOYcfDrGh4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOJOYcfDrGh4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68af6ec66fcec25a5579b2e8bbf8c0e/href">https://medium.com/media/c68af6ec66fcec25a5579b2e8bbf8c0e/href</a></iframe><h3>The problem with nulls</h3><p>Nulls are hard to track in a codebase. There are many things which:</p><ul><li>have properties that are null</li><li>can return null</li><li>need to check for null before doing something</li></ul><p>If you miss a single “null check”, you have a bug. Your program might do the wrong thing or even crash.</p><p>For example, here is some code that crashes if you forget to check for null first:</p><pre>// this function crashes if the argument is null<br>function foo(arrayOrNull) {<br>  return arrayOrNull[0];<br>}</pre><p>The code should have been like this instead:</p><pre>function foo(arrayOrNull) {<br>  if (arrayOrNull === null) {<br>    return null;<br>  }<br>  return arrayOrNull[0];<br>}</pre><p>The issue is that being 100% thorough with your null checks is very hard. It’s extremely difficult, if not impossible, to keep track of every null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pDpQfTDjYQJprH4D.jpg" /></figure><h3>Solutions for working with nulls</h3><p>Working with nulls is difficult. To make things easier, here are some possible solutions you could use. Some of them are bad and some of them are good. We’ll go over each one.</p><p>The solutions are to:</p><ul><li>place a null check around everything</li><li>use try / catch instead of null checks</li><li>return a default value instead of null</li><li>use the null object pattern</li><li>remember to check for every null</li><li>use a type system that forces you to check for every null</li><li>use something like the Option type</li></ul><p>Here is each one in more detail:</p><h3>Place a null check around everything</h3><p>One solution for dealing with nulls is to always check for them, even when you shouldn’t need to. Check “just in case”. After all “It’s better to have it and not need it than to need it and not have it.” — George Ellis. Right?</p><p>If this is your only way of ensuring that you don’t miss null checks, then maybe…</p><p>However, it’s not an optimal solution. The problem is that something in your code might be null when it&#39;s not supposed to be. In other words, you have a bug.</p><p>But, if you have null checks where they’re not needed, you’ll silently ignore the bug. It will be swallowed up in a null check.</p><p>For example:</p><pre>// car is never supposed to be null<br>if (car !== null) {<br>  car.getWheels();<br>}</pre><p>In the code above, car may be null when it&#39;s not supposed to be. That&#39;s a bug. However, due to an unnecessary null check, the program won&#39;t crash. The bug will be silently ignored.</p><p>But, if you didn’t have the unnecessary null check, the program would crash.</p><p>For example:</p><pre>// car is null due to a bug<br>// the program crashes<br>car.getWheels();</pre><p>This is a good scenario. As explained in <a href="https://programmingduck.com/articles/error-responses">how to respond to errors</a>, at the very least, you want to know that you have a bug. Crashing makes that clear, but silently ignoring bugs doesn’t.</p><p>In other words, you should probably avoid unnecessary null checks.</p><p>Otherwise, if you want to do <a href="https://programmingduck.com/articles/defensive-programming">defensive programming</a>, you can have the extra null checks. However, put in some code that records the bug if the thing is actually null. That way you can debug the problem later. (For more information please see <a href="https://programmingduck.com/articles/error-recording">record errors to debug later</a>.)</p><h3>Use try / catch instead of null checks</h3><p>Conditionals vs try / catch is a debate that applies to all possibly invalid actions. For this reason, it’s explained more thoroughly in <a href="https://programmingduck.com/articles/control-flow-invalid-actions">control flow for invalid actions</a>.</p><p>That aside, try / catch won’t solve the problem.</p><p>You might forget to add try / catch blocks, just like you might forget null checks. In this case, your program could crash.</p><p>Worse, an exception might be caught, unintentionally, by a different try / catch block. That’s a silent bug. Silent bugs tend to be worse than crashes.</p><h3>Return a default value instead of null</h3><p>Another option is to avoid returning null. Instead, return a default value of the relevant type.</p><p>For example, you might have a function that would normally return a string or a null. Instead of null, return the empty string. Or, you might have a function that would normally return a positive number or null. Instead of null, return 0 or -1 (if 0 isn’t a suitable default).</p><h4>Benefits of default values</h4><p>Default values reduce the number of nulls in your code.</p><p>In some cases, they also reduce the number of conditionals. This happens when you can treat the default value and the “normal” value the same way.</p><p>For example, this code works whether user.name is a normal value or the empty string.</p><pre>function printUserGreeting(user) {<br>  const name = user.name;<br>  const formattedName = name.toUppercase();<br>  const greeting = `Hello ${formattedName}`;<br>  document.body.append(greeting);<br>}</pre><p>But, if user.name was sometimes null, the function would need a null check to work.</p><pre>function printUserGreeting(user) {<br>  const name = user.name;<br>  if (name === null) { // null check<br>    document.body.append(&#39;Hello&#39;);<br>  } else {<br>    const formattedName = name.toUppercase();<br>    const greeting = `Hello ${formattedName}`;<br>    document.body.append(greeting);<br>  }<br>}</pre><p>Returning default values can be good. However, there are downsides.</p><h4>Downsides of default values</h4><p>One downside is that the semantic meaning of null isn&#39;t being honoured. Semantically, null means the absence of a value. It doesn&#39;t mean a legitimate value. In comparison, the empty string or the number 0 could be legitimate values. 0 or -1 could be the result of a math calculation. The empty string may be a delimiter provided to a function. They don&#39;t mean the absence of data.</p><p>Another downside, related to the first, is that you lose information on whether the value represents null or a legitimate value. Sometimes it’s important to differentiate between the two. You won’t always be able to use the default value and a normal value in the same way.</p><p>For example, consider JavaScript’s Array.prototype.indexOf() method. It returns either a natural number (0 or a positive integer), or -1 as a default value (instead of null). But, in most situations, you can never use the value -1. You&#39;ll need a conditional to see if the method returned -1 or a normal value. This defeats the point. From the point of view of your code, it might as well have been null.</p><p>For example:</p><pre>function findUser(userArray, targetUser) {<br>  const index = userArray.indexOf(targetUser);<br>  if (index === -1) {<br>    console.log(&#39;Sorry, the user could not be found&#39;);<br>  } else {<br>    console.log(`The target user is user number ${index + 1}`);<br>  }<br>}</pre><p>Another downside is that you might have many functions. Each might need a different default value. In this case, you’ll have a default value that works for one of them, but not for the others. Then, the other functions will need conditionals to check for the default value. Again, this defeats the point. It actually makes the code harder to work with. Checking for null is easier than checking for &quot;magic values&quot;.</p><p>Just to finish off, some other downsides are that:</p><ul><li>coming up with a default value can be difficult</li><li>tracing the origin of a default value (in code) can be difficult</li></ul><h4>Verdict for default values</h4><p>To summarize: This is a solution which can be helpful to use. However, be careful of the downsides. You’ll need to use your own judgement for when to use this option.</p><p>Personally, I don’t use it too often.</p><p>But, one “default” value that’s often good to use is an empty collection. For example, an empty array, or an empty hashmap. This tends to have all of the benefits without the downsides. That’s because it’s semantically correct to say “yes, this thing <em>has a collection</em>, it just <em>happens to be empty</em>”. Also, most code should be able to work with an empty collection in the same way as a non-empty collection.</p><h3>Use the null object pattern</h3><p>The null object pattern is similar to using default values (mentioned above).</p><p>The difference is that it works with classes and objects, rather than primitive values like strings and numbers and such. It sets defaults for values (attributes) as well as behaviour (methods).</p><p>You use the null object pattern by creating a null / empty / default object with the same interface as a normal object. The attributes and methods of this object would have default values and behaviour.</p><p>For example, here is a normal User class that you might have in your codebase:</p><pre>class User {<br>  constructor(name, id) {<br>    this.name = name;<br>    this.id = id;<br>  }<br><br>  updateName(name) {<br>    this.name = name;<br>  }<br><br>  doSomething() {<br>    // code to do something<br>  }<br>}</pre><p>Here is an example NullUser class that you might have (a null object):</p><pre>class NullUser {<br>  constructor() {<br>    this.name = &#39;Guest&#39;; // default value<br>    this.id = -1; // default value<br>  }<br><br>  updateName() {} // do nothing (default behaviour)<br><br>  doSomething() {<br>    // do nothing, or do some other default behaviour<br>  }<br>}</pre><p>The usage in code would be something like this: You might have some code that would normally return either null or a normal object. Instead of returning null, return the null object. This is analogous to returning a default value.</p><p>For example, the code below sometimes returns null:</p><pre>function findUser(userId) {<br>  const targetUser = users.find(user =&gt; user.id === userId);<br>  if (!targetUser) {<br>    return null;<br>  }<br>  return user;<br>}</pre><p>Instead, you can have this code, which returns a null object instead of null:</p><pre>function findUser(userId) {<br>  const targetUser = users.find(user =&gt; user.id === userId);<br>  if (!targetUser) {<br>    return new NullUser();<br>  }<br>  return user;<br>}</pre><p>Then, whenever you use the null object or the normal object, you don’t need a null check.</p><p>To illustrate the point, here some example code <strong>without</strong> the null object pattern:</p><pre>// class User is shown above<br><br>const users = [new User(&#39;Bob&#39;, 0), new User(&#39;Alice&#39;, 1)];<br><br>function findUser(userId) {<br>  const targetUser = users.find(user =&gt; user.id === userId);<br>  if (!targetUser) {<br>    return null;<br>  }<br>  return user;<br>}<br><br>function printName(user) {<br>  if (user === null) { // null check here<br>    document.body.append(`Hello Guest`);<br>  } else {<br>    document.body.append(`Hello ${user.name}`);<br>  }<br>}<br><br>function main() {<br>  const user = findUser(123);<br>  printName(user);<br>}</pre><p>Here is the same code, except it uses the null object pattern:</p><pre>// classes User and NullUser are shown above<br><br>const users = [new User(&#39;Bob&#39;, 0), new User(&#39;Alice&#39;, 1)];<br><br>function findUser(userId) {<br>  const targetUser = users.find(user =&gt; user.id === userId);<br>  if (!targetUser) {<br>    return new NullUser(); // instead of returning null, return a null object<br>  }<br>  return user;<br>}<br><br>function printName(user) {<br>  // no null check<br>  document.body.append(`Hello ${user.name}`);<br>}<br><br>function main() {<br>  const user = findUser(123);<br>  printName(user);<br>}</pre><p>As for whether to use the null object pattern or not, similar points apply as for default values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gw3iSdZ2BMUNZf0P.jpg" /></figure><h3>Remember to check for every null</h3><p>One way to be thorough with all of your checks is… to be thorough with all of your checks…</p><p>Every time you work on code, be extremely careful with your null checks. You should understand where null can appear and where it shouldn&#39;t appear (where it would be a bug).</p><p>It’s very difficult. Sometimes it might feel impossible. But, that’s what you have to do if you’re not using other solutions.</p><h3>Use a type system that forces null checks</h3><p>Type systems to the rescue. Some programming languages, such as TypeScript with its strictNullChecks option, understand when something could be null. Then, they force you to check.</p><p>Another example is C# with its nullable reference types. These warn you to check (they don’t force you), but that’s still helpful.</p><p>This means that you can never forget to check for null.</p><p>Personally, I think that this is a great option.</p><h3>Use the Option type</h3><p>The final option (no pun intended) is to use something like the Option type (also known as the Maybe type).</p><p>This doesn’t completely eliminate null checks. But, it reduces them a lot. Also, the few remaining null checks are in places where they’re easy to work with. It’s very difficult to forget to put them in.</p><p>With the Option type, you have two null checks instead of a countless number of them.</p><p>The null checks are in:</p><ol><li>the Option type itself</li><li>the first function to return an Option type</li></ol><p>Here’s a (very) simplified implementation of the Option type:</p><pre>class Option {<br>  constructor(nullOrNormalValue) {<br>    this._value = nullOrNormalValue;<br>  }<br><br>  map(fn) {<br>    if (this._value === null) {<br>      return this;<br>    }<br>    const newValue = fn(this._value);<br>    return new Option(newValue);<br>  }<br>}</pre><p>To do something with the Option type, you use the map method and pass in a function. This should be familiar if you&#39;ve ever used a map function for arrays and such.</p><p>The key point here is that the null check is inside the Option type. In other words, every single time you try to use that value, you get a null check for free. This means that, as long as you’re working with the Option type, you can never forget your null checks.</p><p>You also need a null check, or some other conditional, in the place where you’ll return an Option for the first time.</p><p>For example, here’s a normal function that would normally return null or a normal value:</p><pre>function getNextScheduledEvent(user) {<br>  if (user.scheduledEvents.length === 0) {<br>    return null;<br>  }<br>  return user.scheduledEvents[0];<br>}</pre><p>Here is the same function, but now, it returns an Option.</p><pre>function getNextScheduledEvent(user) {<br>  if (user.scheduledEvents.length === 0) {<br>    return new Option(null);<br>  }<br>  return new Option(user.scheduledEvents[0]);<br>}</pre><p>After writing that code, you don’t need any more null checks for the returned value.</p><p>For example, here’s what the code would look like without Option:</p><pre>function getNextScheduledEvent(user) {<br>  if (user.scheduledEvents.length === 0) {<br>    return null;<br>  }<br>  return user.scheduledEvents[0];<br>}<br><br>function foo(nextScheduledEvent) {<br>  if (nextSceduledEvent === null) { // null check<br>    // do nothing<br>  } else {<br>    // stuff<br>  }<br>}<br><br>function bar(nextScheduledEvent) {<br>  if (nextSceduledEvent === null) { // null check<br>    // do nothing<br>  } else {<br>    // stuff<br>  }<br>}<br><br>function baz(nextScheduledEvent) {<br>  if (nextSceduledEvent === null) { // null check<br>    // do nothing<br>  } else {<br>    // stuff<br>  }<br>}<br><br>function main() {<br>  const user = {scheduledEvents: []}<br>  const nextEventOption = getNextScheduledEvent(user);<br>  const a = foo(nextScheduledEvent);<br>  const b = bar(nextScheduledEvent);<br>  const c = baz(nextScheduledEvent);<br>}</pre><p>Notice that every function needs a null check.</p><p>Here is the same code using Option:</p><pre>function getNextScheduledEvent(user) {<br>  if (user.scheduledEvents.length === 0) {<br>    return new Option();<br>  }<br>  return new Option(user.scheduledEvents[0]);<br>}<br><br>function doubleEventPrice(event) {<br>  // no null check<br>  return {<br>    ...event,<br>    price: event * 2,<br>  }<br>}<br><br>function foo(event) {<br>  // stuff, no null check<br>}<br><br>function bar(event) {<br>  // stuff, no null check<br>}<br><br>function main() {<br>  const user = {scheduledEvents: []}<br>  const nextEventOption = getNextScheduledEvent(user);<br>  const a = nextEventOption.map(doubleEventPrice);<br>  const b = nextEventOption.map(foo);<br>  const c = nextEventOption.map(bar);<br>}</pre><p>Notice the lack of null checks.</p><p>Of course, this is a very simplified explanation. There is much more to using the Option type. A real implementation of Option would also be more much more complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TvtjbQVWy2yH10MZ.jpg" /></figure><h3>Which option should you use?</h3><p>We covered a lot of methods for dealing with nulls.</p><p>It’s up to you to choose the appropriate one for your codebase. You need to weigh the pros and cons of each. You also need to consider your preferences.</p><p>Personally, I love the type system enforced null checks. Along with those, I might use default values or the null object pattern sometimes. As of the time of writing, I haven’t used the Option type very much. However, many people are passionate about that one. It seems like a great solution.</p><p>If you want, leave a comment below about which method you recommend and why.</p><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Image credits:</p><ul><li>Single box — Photo by Christopher Bill on Unsplash</li><li>Two boxes — Photo by Karolina Grabowska from Pexels</li><li>Sticky note — Photo by AbsolutVision on Unsplash</li><li>Pointing to laptop — Photo by John Schnobrich on Unsplash</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/nulls"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de9ddc592efe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defensive & offensive programming]]></title>
            <link>https://levelup.gitconnected.com/defensive-offensive-programming-2fcbc2847795?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fcbc2847795</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:05:13 GMT</pubDate>
            <atom:updated>2022-01-17T02:26:31.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMFtVpjqGNMjF9opkjDdEw.jpeg" /></figure><p>Defensive programming is a term that many programmers have heard of. It’s related to <a href="https://programmingduck.com/articles/errors">error handling</a> and having correct programs. For some programs, defensive programming is essential. For others, it may be useful to use here and there. Along with that, there’s also offensive programming.</p><p>In this article, we’ll start by examining “normal programming”. We’ll examine it first because some people mistake it for defensive programming. However, this is something that you should do regardless of whether you do defensive programming or not.</p><p>Then, we’ll examine defensive programming, followed by offensive programming.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FklY408xWUTw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DklY408xWUTw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FklY408xWUTw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c3e1f4dc0ab6117b3d8b17bcdfb8ee/href">https://medium.com/media/c6c3e1f4dc0ab6117b3d8b17bcdfb8ee/href</a></iframe><h3>Normal programming</h3><p>Normal programming means to have all the checks that are necessary in your code. It also means to always handle certain types of errors.</p><h3>Necessary checks in code</h3><p>Some code needs a lot of conditionals. It can feel like you’re being “overly defensive” with the number of conditionals you have.</p><p>One example of this is checking for null (the billion-dollar mistake). <a href="https://programmingduck.com/articles/nulls">Nulls and null checks</a> are very tricky. Many codebases need if statements for them all over the place.</p><p>Another example is validating user input. You need to have many checks to ensure that user input is valid. Your program needs to handle it very harshly. Otherwise, you’ll have security vulnerabilities.</p><p>But that’s not defensive programming.</p><p>Rather, something like forgetting a single null check is a bug. They’re not unnecessary checks that you do “just in case”. They’re necessary checks. The value will be null sometimes and that&#39;s normal. If you forget a single one, you have a bug. No questions asked.</p><h3>Necessary error handling</h3><p><a href="https://programmingduck.com/articles/errors">Error handling</a> is very important in programs. You always need to consider <a href="https://programmingduck.com/articles/error-responses">how your program should respond to errors</a>.</p><p>This also depends on the kind of error.</p><p>Generally, most programs handle “expected errors” which are out of their control. For example:</p><ul><li>failing to send a network request because the network connection dropped.</li><li>failing to find a file because a user deleted it.</li></ul><p>It would be very bad for the user experience for a program to crash on these errors. Also, it’s relatively easy to handle them.</p><p>As a result, most programs handle these, even if they’re not doing defensive programming. So, again, this is considered “normal programming”, not defensive programming.</p><p>A different kind of error is a bug. In most programs, these errors are considered “unrecoverable”. The rule-of-thumb for most programs is to crash on these errors and to not handle them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6479EzEmBjVHe4mJ.jpg" /></figure><h3>Defensive programming</h3><p>In my interpretation, defensive programming is about fault tolerance. It means going above and beyond to ensure that your program continues working. It’s used for certain programs where you need maximum:</p><h3>Example use case of defensive programming</h3><p>One example of defensive programming, as <a href="https://coder.today/tech/2017-11-09_nasa-coding-standards-defensive-programming-and-reliability-a-postmortem-static-analysis./">Adrian Georgescu writes on his post on NASA coding standards</a>, is for code used in space exploration missions.</p><p>That code is developed once and sent to space. If it goes wrong, that’s billions of dollars worth of work lost.</p><p>For that kind of code, you need to take extreme measures. The code must work correctly, without crashing, no matter what.</p><p>This is very different to your average program. With your average program, bugs aren’t generally a big problem. Your program may still be usable even if it’s buggy. In the worst case, a problem can be fixed manually by calling customer service. If the program becomes unusable, you can crash it and restart it. If it’s a back end program, there are probably multiple servers running it. If it’s a client, the user can restart the program themselves. In a really bad case, you can update the server code. You can even go to a physical server manually and restart it.</p><p>But, with certain critical software, you can’t do that. The software has to always work properly.</p><p>The problem is that people aren’t perfect. We create bugs. Not to mention that other errors may occur that are outside of the program’s control (such as operating system errors). This means that the program may fail.</p><p>But, that’s not an option with some software.</p><p>As a result, you need to do everything in your power to prevent failure.</p><h3>How to do defensive programming</h3><p>Defensive programming primarily means doing everything possible to ensure your program is working correctly and will continue to work correctly. This can include:</p><ul><li>having very good software development practices.</li><li>having many checks in code to double and triple check that everything is working at all times.</li><li>optionally, having error recovery mechanisms. That way, if something goes wrong, maybe the program can recover.</li></ul><h4>Good software development practices</h4><p>The first step is to make the code as bug-free and as easy to work with as possible.</p><p>That means that you need things such as:</p><ul><li>very strict QA</li><li>very thorough tests</li><li>very thorough runtime monitoring</li><li>very strict coding and development standards. In fact, you may ban certain patterns or language features altogether, such as recursion.</li><li>good general software quality</li><li>source code that’s easy to understand</li><li>software that behaves in a predictable manner</li></ul><p>Those points are important for all software. However, they’re critical for defensive programming. After all, if your source code isn’t well tested or easy to understand, it could have bugs. This defeats the point of defensive programming.</p><h4>Extra checks</h4><p>Code with defensive programming tends to have many extra checks. The checks are there to catch bugs. They wouldn’t be needed if the code was completely bug-free. Checks that aren’t intended to catch bugs fall under “normal programming”, not “defensive programming”.</p><p>You have conditionals in the code that check whether something, such as some state in the program, is valid. If a check fails, it shows a bug.</p><p>At that point:</p><ul><li>if the program is in development, you can crash it and fix the bug. This is the same principle as using assertions, during development, in offensive programming.</li><li>if the program is in production, you can run error recovery (if you’ve implemented it) so the program can continue working.</li></ul><p>The common case is to crash the program and fix the bug. During development, you hope that the combination of tests and extra checks will catch all of the bugs. Then, when the program is in production, it should work as intended.</p><p>Another benefit for these checks is that they catch errors early. The more checks you have that the intermediate state is correct, the sooner you’ll catch bugs. That makes debugging easier. It also means that you can start error recovery earlier.</p><p>Finally, you may be able to implement some error recovery. Then, if a check fails, you can run your error recovery code.</p><p>You can have as many or as few checks as you need. You’ll have to decide what to check based on risk analysis. Some important checks are probably results involving important calculations and data. Some less important checks are things like checking function arguments or constantly checking state after simple operations.</p><p>Here are some examples of checks you might have:</p><p>Example with checking function arguments</p><p>You can check whether a function is called with valid arguments. The arguments should have the correct type and range.</p><p>Here’s a code example:</p><pre>function foo(nonEmptyString, naturalInteger) {<br>  if (<br>    typeof nonEmptyString !== &#39;string&#39; || // if it&#39;s not a string<br>    nonEmptyString === &#39;&#39; || // if it&#39;s the empty string<br>    !Number.isInteger(naturalInteger) || // if it&#39;s not an integer<br>    naturalInteger &lt; 1 // if it&#39;s not a natural integer (1 or more)<br>  ) {<br>    // crash the program<br>    // or handle the error here<br>    // or throw an exception so some code higher up handles the error<br>    // or do anything else your error recovery implementation requires<br>  }<br>  // code for normal function execution<br>}</pre><p>Example with checking the results of data calculations</p><p>Another example is checking results involving data.</p><p>Normally, you would only check some data when you first receive it. For example, if a user submits some data, you would check it to make sure it’s valid.</p><p>Then, you would work with that data. You might format it or transform it in some way. You would have tests to make sure that these processes work correctly.</p><p>In theory, you shouldn’t need to also check the final result. The initial data is valid. The code you process it with works correctly. Therefore, the end result should be correct.</p><p>But, if you’re doing defensive programming, you might have checks on the final result too.</p><h4>Recovering from unexpected errors</h4><p>The steps mentioned so far try to reduce the number of bugs in your program. However, there might still be bugs. For that reason, you might want to implement error recovery.</p><p>This might require a lot of thinking. It might even need to be part of your feature planning. This would be the case if the program needs to respond to a user while it’s in the process of recovery. The user-facing behaviour will probably be determined in collaboration with a product manager, not just by the programmers.</p><p>Also, error recovery might be a large part of the code. As a made-up example, consider a back end that accepts network requests for product orders. A server might error while processing the order. To handle that scenario, you might do things like:</p><ul><li>have an initial server record the order information so it’s not lost.</li><li>have some recovery mechanism for the faulty server. E.g. some other process may restart it. Or, maybe the server can try to fix its own state internally.</li><li>the order can be given to a different server, or maybe the erroring server can try to process it again after it’s fixed.</li></ul><p>Here are some more examples of possible recovery mechanisms. If something in the code fails:</p><ul><li>maybe you can try to manually fix or reset the state in the program.</li><li>maybe you can try running the operation again. If the problem is a race condition, it may work next time.</li><li>if it’s a subprogram that’s erroring, maybe you can restart it. If the problem is invalid state in the subprogram, then restarting it may work.</li><li>maybe you can have a backup program hosted on a server. If the client is producing incorrect results, then maybe it can call on the server to do the calculation instead.</li><li>maybe you can have a backup program with less features than the main program. If the main program is erroring, maybe run the backup program instead which only provides barebones operation.</li></ul><p>Of course, if a critical part of the program is buggy then maybe you can’t do anything about it in runtime. The only solution may be to fix the code.</p><p>You’ll also need to have risk analysis. That’s where you consider things like:</p><ul><li>what code could have errors?</li><li>how likely it is that it will have errors?</li><li>what impact would the error have?</li><li>what would it cost to prevent the error from ever happening or to implement recovery mechanisms for that error?</li></ul><p>The idea is that recovery will need to be considered as a first class citizen and a requirement during the project.</p><p>Note that these kinds of recovery measures are probably reserved for programs that really need defensive programming. For most normal programs, it’s probably enough to simply restart a server or notify the user that something went wrong.</p><h3>Downsides of defensive programming</h3><p>Defensive programming has significant downsides. For example:</p><ul><li>it requires a lot more code. At the very least, you’ll have many more conditions and checks than a similar program without defensive programming.</li><li>performance can be worse. That’s because the extra checks take time to execute.</li><li>it makes the code harder to work with because there is a lot more code.</li><li>error recovery can take a long time to plan for and implement.</li></ul><h3>When to use defensive programming</h3><p>Whether or not you use defensive programming depends on your program.</p><p>As mentioned earlier, some programs need maximum availability, reliability and security. Those types of programs may require a lot of defensive programming.</p><p>For most other programs, you shouldn’t need defensive programming. “Normal programming” should be enough. Nonetheless, you’re free to use some defensive programming techniques around some key areas of the code. It’s up to you to make the decision.</p><p>Regardless of what you do, remember to be pragmatic. Use risk analysis. Consider:</p><ul><li>what could go wrong?</li><li>how much chance is there of it going wrong?</li><li>what would the impact be?</li><li>how could you prevent it from going wrong?</li><li>what would it cost to implement prevention or recovery?</li></ul><p>Then, use the right amount of defensive programming where necessary. Try to avoid overusing defensive programming if it’s not necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U_XYoldexIR5AUMz.jpg" /></figure><h3>Offensive programming</h3><p>The goal of offensive programming is to catch bugs and crash early. As explained in <a href="https://programmingduck.com/articles/error-responses">how to respond to errors</a>, crashing early is helpful.</p><p>It means that you are notified of bugs immediately. Also, the stack trace from the crash is closer to the source of the problem. This helps with debugging.</p><h3>How to do offensive programming</h3><p>To do offensive programming, you:</p><ul><li>do normal programming</li><li>don’t recover from bugs (avoid defensive programming)</li><li>write code in a way where bugs are obvious and easy to find</li><li>immediately crash the program on bugs</li></ul><p>Just like with normal programming, you still need conditionals for things that aren’t bugs. For example, you need conditionals for null checks.</p><p>Similarly, you should probably handle errors which aren’t bugs. For example when users provide invalid data, or when you’re not able to find a file in the file system. Most of the time, it would be unreasonable to crash on them. In other words, you should probably follow the “normal programming” way of dealing with these.</p><p>Also, you should write code in a way where bugs are easy to find. Here are some techniques for that.</p><h4>Avoid fallback code and default values</h4><p>Things like default state, default arguments and fallback code can hide bugs.</p><p>For example, you might call a function with incorrect arguments. You might have accidentally used null instead of a string for an argument. That&#39;s a bug. However, due to default arguments, the argument will be a string anyway. The bug won&#39;t be caught and the program may do the wrong thing as a result.</p><p>A similar thing applies to fallback code. One example is inheritance and subclassing. You may have forgotten to implement a method in a subclass. Then, you call the method and it executes the parent’s method. That’s unintended behaviour, which is a bug.</p><p>To prevent this, avoid using things like default state, default values and fallback implementations.</p><h4>Avoid checks on code that will crash on errors</h4><p>Sometimes, buggy code will crash on its own. You don’t have to do anything extra. Leave the code as it is and let it crash.</p><p>For example, consider the code below. array should never be null. If it&#39;s null, that&#39;s a bug.</p><p>If you have a defensive check around it, the code won’t crash:</p><pre>function foo(array) {<br>  if (array !== null) { // code doesn&#39;t crash if array is null<br>    return array[0];<br>  }<br>}</pre><p>But if you don’t have a defensive check, the code will crash.</p><pre>function foo(array) {<br>  return array[0]; // code crashes if array is null<br>}</pre><p>You want the code to crash as early as possible. So, in this case, just leave it as it is without a defensive check.</p><h4>Have conditionals or assertions to check for errors</h4><p>Contrary to the point above, some bugs won’t cause the program to crash.</p><p>For example, you might have some incorrect state in your program. Your program may not crash from that.</p><p>As another example, some code may execute that shouldn’t execute under normal circumstances.</p><p>In these cases, you can use manual checks. Then, if you find something wrong, you can manually crash the program.</p><p>For example:</p><pre>function foo(arg) {<br>  switch(arg) {<br>    case &#39;foo&#39;:<br>      // do something<br>      break;<br>    case &#39;bar&#39;:<br>      // do something<br>      break;<br>    default:<br>      // this code should never execute, so crash the program if it does<br>      throw new Error(&#39;Default case should never execute.&#39;);<br>  }<br>}</pre><p>Here’s another example with checking state:</p><pre>function getCurrentPlayerHealth() {<br>  const health = player.health;<br>  if (health &lt; 0 || health &gt; 100) {<br>    // this condition should never evaluate to true, so crash the program if it does<br>    throw new Error(`Player health should be between 0 and 100.`);<br>  }<br>  // continue normal function execution<br>}</pre><p>More traditionally, these kinds of “bug checks” use assertions instead of conditionals.</p><p>Assertions are bug-finding tools. If they fail, they signify a bug. Conditionals are control-flow tools. If a conditional “fails”, it doesn’t signify a bug. It means that a different block of code should execute instead.</p><p>So, instead of using conditionals, you can use assertions. For details on how to do that, please see the documentation for your programming language.</p><p>Here’s a code example in JavaScript:</p><pre>console.assert(player.health &gt;= 0 &amp;&amp; player.health &lt;= 100, player); // logs a stack trace if condition is false, along with the player object</pre><p>In some programming languages, assertions crash the program. However, in others, they don’t crash it. They may only print an error message to the console or something. Both are usable. However, offensive programming recommends hard crashing when possible.</p><p>Also, some programming languages allow you to turn off assertions in production for better performance.</p><h3>Downsides of offensive programming</h3><p>Similar to defensive programming, offensive programming has downsides.</p><p>One downside is having to avoid certain kinds of code like default arguments. Default arguments have valid use cases. They provide “reasonable defaults”. They can make some code much easier to work with.</p><p>Another downside is having to crash the program. As explained in <a href="https://programmingduck.com/articles/error-responses">how to respond to errors</a>, crashing on bugs is usually good. However, it might be something that you’re not prepared to do in your application.</p><p>Another downside is performance. Having assert statements throughout your code can significantly reduce performance.</p><p>As a result, many programming languages don’t crash when assertions fail. Also, they have the option of removing assertions from production code. With this option, you lose the benefits of offensive programming in production. You only gain the benefits during development. However, that alone can be very useful.</p><h3>When to use offensive programming</h3><p>Offensive programming helps you catch bugs. That’s a significant win.</p><p>For this reason, it’s good to use it during development. Generally, you’ll put assert statements here and there to ensure that certain things are correct.</p><p>As for production, it depends. Consider the pros and cons of offensive programming and make your decision.</p><p>It’s alright to only use offensive programming in development. After all, catching more bugs during development is better than nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IKJOMPJ56rcKtEDK.jpg" /></figure><h3>Be pragmatic</h3><p>When choosing your approach to handling errors, you need to be pragmatic.</p><p>“Normal programming” is the minimum that you need to do for most programs.</p><p>For some programs, you might use defensive programming. In particular, for programs that need high:</p><p>But also understand the downsides. Primarily, the downsides are worse performance and longer development time.</p><p>Offensive programming helps you catch bugs. This is useful during development (and even production).</p><p>You can mix and match the approaches based on what you need. You can even use different methodologies in different areas of the code. It’s up to you to decide.</p><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>For the next steps, I recommend looking at the other articles in the <a href="https://programmingduck.com/articles/errors">error handling series</a>.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Image credits:</p><ul><li>Turtle in sea — Photo by Tanguy Sauvin from Pexels</li><li>Turtle in shell — Photo by Hogr Othman on Unsplash</li><li>Tiger — Photo by Samuele Giglio on Unsplash</li><li>Squirrel — Photo by Pixabay from Pexels</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/defensive-programming"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fcbc2847795" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/defensive-offensive-programming-2fcbc2847795">Defensive &amp; offensive programming</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exceptions vs error values]]></title>
            <link>https://sargalias.medium.com/exceptions-vs-error-values-cc7f83f4df63?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7f83f4df63</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:04:14 GMT</pubDate>
            <atom:updated>2021-12-31T05:45:17.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6e6rVIyQdwi_OXJHwicHg.jpeg" /></figure><p>Exceptions vs error values has been a debate in <a href="https://programmingduck.com/articles/errors">error handling</a> for ages. Some people have firm stances on them. For example, in the book <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a>, Uncle Bob recommends exceptions. In his post on <a href="https://www.joelonsoftware.com/2003/10/13/13/">Exceptions</a>, Joel mentions that he prefers error values.</p><p>Programming languages have also taken stances. Popular languages such as C# and Java traditionally use exceptions. Languages like Rust use error values.</p><p>In this article we’ll examine some of their similarities and differences. We’ll also provide suggestions about when to use which.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fwrz409nQ4hc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dwrz409nQ4hc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fwrz409nQ4hc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f892e099b796a63fdb47e822266eab6d/href">https://medium.com/media/f892e099b796a63fdb47e822266eab6d/href</a></iframe><h3>Basic examples of exceptions and error values</h3><p>Just for a quick introduction, here are some examples of exceptions and error values.</p><p>If you’re already familiar with them, then please skip to the next section.</p><p>Here’s an example of throwing and catching an exception in C#:</p><pre>public class Example<br>{<br>    public void Foo()<br>    {<br>        try<br>        {<br>            Bar();<br>        }<br>        catch (IndexOutOfRangeException ex)<br>        {<br>            // handle error<br>        }<br>    }<br><br>    public void Bar()<br>    {<br>        if (true /* some condition to check if something went wrong */)<br>        {<br>            throw new IndexOutOfRangeException(&quot;Some error message&quot;);<br>        }<br>        else<br>        {<br>            // normal program execution<br>        }<br>    }<br>}</pre><p>In the code above, Bar throws an exception. The exception is caught and handled in Foo, in the catch block.</p><p>Here’s the same thing in JavaScript:</p><pre>function foo() {<br>  try {<br>    bar();<br>  } catch (error) {<br>    // handle error<br>  }<br>}<br><br>function bar() {<br>  if (true /* some condition */) {<br>      throw new Error(&quot;Error message&quot;);<br>  } else {<br>      // normal program execution<br>  }<br>}</pre><p>Error values can be implemented in different ways. One way is for a function to return either an error or a normal value.</p><p>For example:</p><pre>function foo() {<br>  const result = bar();<br>  if (result instanceof Error) {<br>    // handle error<br>  } else {<br>    // normal program execution<br>  }<br>}<br><br>function bar() {<br>  if (true /* some condition */) {<br>    return new Error(&#39;Error message&#39;);<br>  } else {<br>    return 42;<br>  }<br>}</pre><p>In the code above, bar can return either an error or a normal value. foo checks the return value. If it was an error, it handles it. Otherwise, it continues normal program execution.</p><p>You can also use error values by returning a single object. The object should have fields for both the error and the normal return value. For example, you could use a tuple, or an object with properties. If there was an error, the value should be empty. For example {error: new Error(&#39;Message&#39;), value: null}. If there wasn&#39;t an error, the error value should be empty. For example {error: null, value: 42}.</p><p>Here’s a code example:</p><pre>function foo() {<br>  const result = bar();<br>  if (result.error !== null) {<br>    // handle error<br>  } else {<br>    // normal program execution<br>  }<br>}<br><br>function bar() {<br>  if (true /* some condition */) {<br>    return {error: new Error(&#39;Error message.&#39;), value: null};<br>  } else {<br>    return {error: null, value: 42};<br>  }<br>}</pre><p>In the code above, bar always returns an object. If something goes wrong, the object will have a value in the error field. Otherwise, the error field will be null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S30L9aV8T1aC7qBJ.jpg" /></figure><h3>Similarities between exceptions and error values</h3><p>Exceptions and error values are fairly similar. In fact, some newer programming languages such as Rust and Swift eliminate most of the differences between them.</p><p>The most important thing about both of them is that they act as different return values from a function / method. The different return values should lead to different code execution paths.</p><p>They also share a big downside. It’s easy to mess up with both of them.</p><p>With an exception, you may:</p><ul><li>forget to catch it</li><li>wrongly assume that some code higher in the call stack will catch it</li><li>accidentally catch it higher in the call stack in a place that’s not prepared to handle it properly</li></ul><p>Also, you can completely avoid checking error values.</p><p>It’s very easy to forget or mess up. Even if you don’t, someone else might. So, you have to be very diligent.</p><p>Or, you can use a programming language that forces you to check all errors. (More on that later.)</p><h3>Differences between exceptions and error values</h3><p>Exceptions and error values have some differences:</p><h3>Performance</h3><p>Throwing and catching exceptions are commonly considered slow. Returning error values is fast.</p><p>However, exceptions are supposed to be “exceptional” (thrown very rarely). In practice, this means that the performance of your application shouldn’t be negatively affected by using them.</p><h3>Crashing the program vs silent bugs</h3><p>Uncaught exceptions crash the program. More rarely, exceptions can also result in silent bugs (if you catch them higher in the call stack without intending to).</p><p>Unchecked error values result in silent bugs.</p><p>Exceptions are better in this case. As explained in <a href="https://programmingduck.com/articles/error-responses">how to respond to errors</a>, crashing the program is a better default option than silent bugs.</p><h3>Bubbling</h3><p>Exceptions can “bubble” up the call stack. An exception that’s not caught in a catch block will be thrown in the caller (the previous code in the call stack). If it&#39;s not caught there, the process will repeat. If it reaches the end of the call stack, the program will crash.</p><p>Bubbling is both good and bad.</p><p>The benefit is that it’s very convenient. You can have a single try / catch block in some parent function. The exception will propagate to it and will be caught there.</p><p>The downside is that the flow of execution is not explicit. You have to keep track of it yourself. You also have to remember which exceptions are caught where in the call stack.</p><p>This can put you into a bad situation. Sometimes you might not remember or know if an exception will be caught or not, or where it will be caught, or by what.</p><p>In comparison, error values are standard return values. If you want them to propagate, you have to propagate them manually. You have to manually return them across different functions / methods, all the way up the stack.</p><p>The benefit of this is that it’s very explicit. It’s very easy to track and reason about. The downside is that it’s very verbose. You need many return statements across many different function / method calls.</p><p>Note that you can technically manually propagate exceptions if you want to. However, that’s not common practice. For more details on this please see “checked exceptions” in a later section.</p><h3>Suitability in functional programming</h3><p>Generally, exceptions are less common in functional programming.</p><p>That’s because functional programming promotes immutability and pure functions.</p><p>With exceptions, sometimes you need to break immutability. For example, often, you need to declare variables outside of try / catch blocks and then mutate them in try / catch.</p><p>Here’s a code example:</p><pre>let a;<br>try {<br>  a = new Something();<br>  // do stuff with `a`<br>} catch (error) {<br>  // handle error<br>} finally {<br>  a.close();<br>}</pre><p>Also, thrown exceptions are not standard return values. This messes up the “pure function” point.</p><h3>Exceptions and error values in some newer languages</h3><p>Some newer languages, like Rust and Swift, change things up a bit.</p><p>Most importantly, they force you to check all error values and thrown exceptions. This means that you can never forget to check for errors or to handle exceptions.</p><p>In the case of Swift, it also makes exception bubbling more explicit. It still allows exceptions to propagate automatically. However, it requires intermediate functions (that an exception will propagate through), to be marked with the keyword “throws”.</p><p>This additional explicitness makes exceptions easier to track throughout your code.</p><p>The downside is that it makes things more verbose.</p><p>(Rust uses error values, which you have to propagate explicitly anyway.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1OEOeHE2XT3PidXh.jpg" /></figure><h3>Which should you use?</h3><p>Overall, it seems like this is a question of robustness and amount of safety measures vs verbosity.</p><p>Enforcing error checking and having explicit error propagation have obvious benefits. It makes it much harder to forget to do your error handling. You’ll have to intentionally ignore it to avoid it.</p><p>However, verbosity has downsides too. It can can make code less readable. It can also make it harder to make large changes to code. This can be especially prominent if you’re propagating everything manually.</p><p>For example, imagine that you change a low-level function (or add a new one) to sometimes return an error value. That error may need to be handled at a higher-level function. This means that you’ll need to add code to every intermediary function to keep propagating the error.</p><p>That’s a large change. In comparison, if you added an exception that bubbled automatically, you would just add a try / catch block at the high-level function and you’d be done.</p><p>So it’s up to you to decide where you stand on the safety measures vs verbosity scale.</p><p>For maximum safety measures, you should probably use a language that forces you to check all errors and forces explicit propagation of them. The downside is that the error handling will be more verbose.</p><p>One level lower in safety is to use error values. I regard these as more robust than throwing exceptions. That’s because propagating error values is more explicit than bubbling exceptions. The downside is that there’s more verbosity. Also, note that you need to be very diligent with these. If you forget to check an error, you’ll get silent bugs. Unchecked error values are worse than uncaught exceptions.</p><p>Otherwise, go for throwing “normal” exceptions (such as the ones in Java, C# and JavaScript). They’re the least verbose. This doesn’t mean that you can’t create robust programs with them. It just means that it’s up to you to be diligent with errors and to track everything.</p><p>It’s probably also a good idea to consider the convention in your programming language. Some programming languages prefer exceptions. Some others prefer error values.</p><p>My personal preference is to lean towards higher safety for larger scoped and more critical projects. For smaller scoped projects, I lean towards less verbosity and more convenience (exceptions).</p><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>For the next steps, I recommend looking at the other articles in the <a href="https://programmingduck.com/articles/errors">error handling series</a>.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Images:</p><ul><li>Duelling Legos — Photo by Stillness InMotion on Unsplash</li><li>Typewriter and laptop — Photo by Glenn Carstens-Peters on Unsplash</li><li>Post-it notes — Photo by Will H McMahan on Unsplash</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/exceptions-error-values"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7f83f4df63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practices for error catching and handling]]></title>
            <link>https://sargalias.medium.com/best-practices-for-error-catching-and-handling-2247325042c9?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2247325042c9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:03:10 GMT</pubDate>
            <atom:updated>2021-11-21T03:23:28.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsGiwoE7xS8SPMTHfkiZlA.jpeg" /></figure><p>Catching and handling errors is an important part of <a href="https://programmingduck.com/articles/errors">error handling</a>.</p><p>Here are some best practices for it. Generally, it’s good to:</p><ul><li>be very thorough with your error checking</li><li>do your error checking first</li><li>handle errors at the earliest appropriate place</li><li>(for exceptions) put the minimum code you can in your try blocks</li><li>restore state and resources so the program can keep executing correctly</li></ul><p>Here are the best practices in more detail.</p><p>(Note: For this article, “error” is defined in <a href="https://programmingduck.com/articles/error-meaning">Terminology — Errors and non-errors</a>. It means anything you might throw an exception or return an error value for. It doesn’t just mean an “unrecoverable error”.)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fn9pu4dPiDEg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dn9pu4dPiDEg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fn9pu4dPiDEg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6e530342f277c57684cd83b24eca4e2/href">https://medium.com/media/f6e530342f277c57684cd83b24eca4e2/href</a></iframe><h3>Be very thorough with your error checking</h3><p>Unfortunately, programmers aren’t perfect. We create bugs and make mistakes. In fact, we do that quite often. That’s why we have so many error correction tools to help us.</p><p>So, in general, you should go by the assumption that everything in your program that can fail will fail. Other things that you didn’t think of will also fail.</p><p>To minimise the issue, you should be very thorough with your error checking. Always catch all possible exceptions and check all error values. Then, handle them appropriately.</p><h3>Check for errors first</h3><p>This one is a stylistic convention.</p><p>In your code, it’s good to do your error checking before anything else. Leave the normal program execution for after.</p><p>For example, in methods that throw exceptions, try to check for errors and throw the exception as early as possible.</p><p>Here’s a code example:</p><pre>class Example<br>{<br>    public void Foo(string a)<br>    {<br>        if (a.Length === 0)<br>        {<br>            throw new InvalidArgumentException(&quot;Parameter {a} must not be the empty string.&quot;);<br>        }<br>        // normal program execution<br>    }<br>}</pre><p>Method Foo starts by doing its error checking. The normal code execution comes afterwards.</p><p>Avoid doing something like this:</p><pre>class Example<br>{<br>    public void Foo(string a)<br>    {<br>        // do some &quot;normal program execution&quot; that doesn&#39;t need parameter `a`<br><br>        // check parameter `a` right before you need it<br>        if (a.Length === 0)<br>        {<br>            throw new InvalidArgumentException(&quot;Parameter {a} must not be the empty string.&quot;);<br>        }<br>        // more normal program execution<br>    }<br>}</pre><p>In this code, Foo executes some code. Then, it does some error checking for parameter a.</p><p>The same principle applies to checking error values. Try to check for errors before you continue your normal program execution.</p><p>Here is a code example:</p><pre>function foo() {<br>  const result = bar();<br><br>  if (result.error) {<br>    // handle error<br>  }<br><br>  else {<br>    // normal code execution<br>  }<br>}</pre><p>The code above first checks for errors. Then, it continues normal program execution.</p><p>This organises your code into recognisable blocks. Errors first, normal code after. It makes your code easier to scan through and easier to understand.</p><p>It also helps with debugging. When an error is thrown, less normal code will have ran. This reduces the amount of code you’ll have to check through when debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qsKmboLlfK9Y6D2M.jpg" /></figure><h3>Handle errors at the first appropriate place</h3><p>Sometimes, you can’t handle errors immediately. You might need to propagate them to higher level code.</p><p>To showcase this, consider this example: You have a function that searches the file system for a file. If it finds it, it reads its contents. Otherwise, it throws an exception. How should the code handle this exception? Should it:</p><ul><li>crash the program?</li><li>create a new file?</li><li>search for a backup file in a different location?</li><li>notify the user that the file couldn’t be found and ask them to try a different file?</li></ul><p>The file system code doesn’t know. Different programs will want different behaviour if the file isn’t found. This means that the file system code can’t have hardcoded behaviour to handle the exception.</p><p>Instead, the exception should be handled at a more appropriate place. The place that can decide what to do about it. Often, that means some code higher up in the call stack. So, the exception (or error value) needs to propagate up to that place.</p><p>For exceptions, that means that you should let the exception bubble up. Then, have a try / catch block at the place where you’ll handle it.</p><p>For error values, you’ll have to manually return them until they reach the correct place in the call stack.</p><p>Having said that, you should handle errors at the <strong>first</strong> appropriate place. Don’t propagate them higher than necessary. The earlier you handle errors, the closer they’ll be to the code that raised them. This makes the execution flow of the code easier to track and understand.</p><p>Here’s a code example where we search the database for a record:</p><pre>// server.js<br>import { getSpriteById } from &#39;./myDatabase.js&#39;;<br><br>app.get(&#39;/:spriteId&#39;, async (req, res) =&gt; {<br>  const spriteId = req.spriteId;<br>  try {<br>    await getSpriteById(spriteId);<br>  } catch (error) {<br>    // exception from database is handled here.<br>    // In this case, it responds with a 404.<br>    res.sendStatus(404);<br>    return;<br>  }<br>  res.send(&#39;Sprite found&#39;);<br>});<br><br>app.post(&#39;/foo&#39;, async (req, res) =&gt; {<br>  const spriteId = req.body.spriteId;<br>  try {<br>    await getSpriteById(spriteId);<br>  } catch (error) {<br>    // exception from database is handled here.<br>    // In this case, it redirects<br>    // to another page for the user to fill in correct information<br>    res.redirect(&#39;/form&#39;);<br>    return;<br>  }<br>  res.send(&#39;Data accepted&#39;);<br>});<br><br>// myDatabase.js<br>const db = await connectToDatabase(&#39;connectionString&#39;);<br><br>const getSpriteById = async (spriteId) =&gt; {<br>  // throws exception if it doesn&#39;t find the record<br>  const sprite = await db.findById(spriteId);<br>  return sprite;<br>};<br><br>export { getSpriteById };</pre><p>(By the way the code is pseudocode, don’t expect it to work if you actually run it. However, it showcases the point.)</p><p>In the example, the function getSpriteById searches the database. If it doesn&#39;t find the record it&#39;s looking for, it throws an exception. It doesn&#39;t handle the error itself. Instead, the handlers in server.js decide how to handle the error. Both handlers have try / catch blocks which handle the exception differently based on what they need.</p><h3>(For exceptions) Be careful of how much code you put in your try blocks</h3><p>It’s considered best practice to put as little code as possible in each try / catch block. This means that you may need multiple try / catch blocks, instead of just one.</p><p>The benefits of this are that:</p><ul><li>it’s easy to see which code raises which exceptions (and which code doesn’t raise exceptions)</li><li>it “separates concerns” more clearly. Each try / catch block is a separate piece of functionality. This makes it easier to refactor it into a separate function.</li><li>it prevents the accidental swallowing of exceptions. This happens if you put some code in try without thinking. That code might throw an exception that you weren&#39;t prepared to handle. However, it will be caught in catch (and potentially handled incorrectly). Then, the program will continue executing, potentially producing the wrong result.</li></ul><p>It’s also a solution for when certain lines of code can throw the same type of exception, but each case needs to be handled differently.</p><p>On the flip side, having small try / catch blocks can make the code more verbose.</p><p>In the end, you need to be pragmatic. Keep the benefits and downsides in mind. Then, make your decision. Usually, correctness and clarity are more important, even if they’re more verbose. However, it’s okay to make the code more concise sometimes, especially if you don’t think correctness and clarity are too affected.</p><p>For example, this code could be separated further, but is still pretty good:</p><pre>BufferedReader bufferedReader = null;<br>try {<br>    bufferedReader = new BufferedReader(new FileReader(&quot;path&quot;));<br>    String line = bufferedReader.readLine();<br>    while (line != null) {<br>        doSomething(line);<br>        line = bufferedReader.readLine();<br>    }<br>} catch (FileNotFoundException | IOException e) {<br>    e.printStackTrace();<br>} finally {<br>    try {<br>        bufferedReader.close();<br>    } catch (IOException e) {<br>        e.printStackTrace();<br>    }<br>}</pre><p>Here is the same example separated more:</p><pre>BufferedReader bufferedReader = null;<br>try {<br>    bufferedReader = new BufferedReader(new FileReader(&quot;path&quot;));<br><br>    try {<br>        String line = bufferedReader.readLine();<br>        while (line != null) {<br>            doSomething(line);<br>            line = bufferedReader.readLine();<br>        }<br>    } catch (IOException e) {<br>        e.printStackTrace();<br>    }<br><br>} catch (FileNotFoundException e) {<br>    e.printStackTrace();<br>} finally {<br>    try {<br>        bufferedReader.close();<br>    } catch (IOException e) {<br>        e.printStackTrace();<br>    }<br>}</pre><p>The second version would be necessary if each catch block needed to have different code. Otherwise, you can choose either version.</p><p>(The best solution is probably to use a with / using / try-with-resources statement, or the equivalent for your programming language. It automatically closes the bufferedReader at the end. The code above is just to showcase the point.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*le_ctXfP8u4uM2MF.jpg" /></figure><h3>Restore state and resources</h3><p>If you successfully handle an error, then the program should be able to continue executing correctly. It should continue almost as though the error never happened.</p><p>This means that you need to:</p><ul><li>restore state to something correct</li><li>close any side effects that were started by erroring code</li></ul><h3>Restore state</h3><p>After recovering from an error, your program needs to have the correct state. If it doesn’t, then you haven’t really recovered.</p><p>This means that you might need to fix or restore your program’s state in your error handling code.</p><p>Here’s an example.</p><p>Consider that you have a Boolean variable. The Boolean variable should start as false. However, while some code is running, you set it to true. At the end, you set it to false again.</p><p>But, if the program errors at some point, the variable won’t be reset. This will leave your program in a bad state, even if the error is handled.</p><p>Here’s an example of some “dangerous code”, which will have invalid state if an error occurs:</p><pre>let isBusy = false;<br><br>async function handleUserEvent(event) {<br>  if (!isBusy) {<br>    isBusy = true;<br>    // do something asynchronous which may throw an exception, for example:<br>    // await doSomething()<br>    isBusy = false;<br>  }<br>}</pre><p>If handleUserEvent errors, the value of isBusy will remain false forever. handleUserEvent won&#39;t be able to run properly again.</p><p>For that reason, you need to manually reset the state if an error occurs.</p><p>Here’s a code example:</p><pre>let isBusy = false;<br><br>async function handleUserEvent(event) {<br>  if (!isBusy) {<br>    isBusy = true;<br>    try {<br>      // do something asynchronous which may throw an exception, for example:<br>      // await doSomething()<br>    } finally {<br>      isBusy = false; // fix the state<br>      // exception is sent higher up because there&#39;s no catch block<br>    }<br>  }<br>}<br><br>// equivalent example<br>async function handleUserEvent(event) {<br>  if (!isBusy) {<br>    isBusy = true;<br>    try {<br>      // do something asynchronous which may throw an exception, for example:<br>      // await doSomething()<br>    } catch (error) {<br>      isBusy = false; // fix the state<br>      throw error;<br>    }<br>    isBusy = false;<br>  }<br>}</pre><p>In this example, if an error occurs in handleUserEvent, there&#39;s no problem. The state is restored and handleUserEvent will execute correctly afterwards.</p><p>The same principle applies across all of your code in the call stack. Imagine that an error occurs in function bar. But, you handle the error in function foo, which is 5 function calls earlier in the call stack. For the program to be in a valid state, you need to make sure that you&#39;ve fixed all of the state from bar to foo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*puuGBuVxDnrZoSip.png" /></figure><p>Basically, it means that you may need many intermediate try / catch blocks in different functions in the call stack. You fix the state in each one. That way, if the error is handled higher up, the state of all the intermediate code has been fixed. They can run again as though nothing went wrong.</p><p>For example:</p><pre>// handleUserEvent<br>import foo from &#39;./foo.js&#39;;<br><br>// this is the top-level function<br>async function handleUserEvent() {<br>  try {<br>    await foo();<br>  } catch (error) { // handle the error at the top level<br>    // record error<br>    // display message to user that action didn&#39;t work<br>  }<br>}<br><br>// foo.js<br>import bar from &#39;./bar.js&#39;;<br><br>let isBusy = false;<br><br>async function foo() {<br>  if (isBusy) {<br>    return;<br>  }<br>  isBusy = true;<br>  try {<br>    await bar();<br>  } finally {<br>    isBusy = false; // restore this module&#39;s state<br>    // exception is sent further up because there is no catch block<br>  }<br>}<br><br>export default foo;<br><br>// bar.js<br>let isBusy = false;<br><br>async function bar() {<br>  if (isBusy) {<br>    return;<br>  }<br>  try {<br>    // do something asynchronous which may throw an exception, for example:<br>    // await doSomething()<br>  } finally {<br>    isBusy = false; // restore this module&#39;s state<br>    // exception is sent further up because there is no catch block<br>  }<br>}<br><br>export default bar;</pre><p>(Yes, I know the code in the examples is very contrived, but hopefully it illustrates the point 😅)</p><h3>Close side effects</h3><p>Some side effects come in pairs. For example, if you open a file, you should also close it. It can be unsafe to leave it open.</p><p>So, make sure that resources like that are properly released.</p><p>If you use exceptions:</p><ul><li>use with blocks. These automatically close resources if an error occurs. Some examples are with in Python, try-with-resources in Java or using in C#.</li><li>otherwise, use finally blocks (or their equivalent in different programming languages)</li></ul><p>If you’re using error values, place the “closing” code somewhere appropriate. It should run both in the error case and the non-error case.</p><p>Here’s an example with finally:</p><pre>// pseudocode<br><br>let file;<br>try {<br>  file = openFile(&#39;foo.txt&#39;); // open the resource<br>  writeToFile(file, &#39;bar&#39;);<br>} catch (error) {<br>  // code to handle exceptions<br>} finally {<br>  close(file); // close the resource<br>}</pre><p>Here’s an example with error values:</p><pre>// pseudocode<br><br>const [fileError, file] = openFile(&#39;foo.txt&#39;);<br>if (fileError) {<br>  // handle error<br>  close(file);<br>  return;<br>}<br>const [writeError, _] = writeToFile(file.value, &#39;bar&#39;);<br>if (writeError) {<br>  // handle error<br>}<br>close(file);</pre><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>For the next steps, I recommend looking at the other articles in the <a href="https://programmingduck.com/articles/errors">error handling series</a>.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Image credits:</p><ul><li>Net — Photo by Raghavendra Saralaya on Unsplash</li><li>Arrow — Photo by Hello I’m Nik on Unsplash</li><li>Squirrel in treehouse — Photo by Joakim Honkasalo on Unsplash</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/error-catching-handling"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2247325042c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error recording — How to record errors in your application to debug later]]></title>
            <link>https://sargalias.medium.com/error-recording-how-to-record-errors-in-your-application-to-debug-later-9b26260585c5?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b26260585c5</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:02:34 GMT</pubDate>
            <atom:updated>2021-11-09T14:20:42.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error recording — How to record errors in your application to debug later</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6iQAF8u5CZ0Cjomo.jpg" /></figure><p>Recording errors is an important part of <a href="https://programmingduck.com/articles/errors">error handling</a>. In short, when certain errors occur in programs, you want to know about it. This is particularly important with bugs.</p><p>You need to:</p><ol><li>know that they occurred</li><li>have useful information about them so you can debug them later</li></ol><p>One way to do this is to use an error monitoring or logging service. Some examples are <a href="https://newrelic.com/">New Relic</a> and <a href="https://www.splunk.com/">Splunk</a>. These will automatically record any program errors and such.</p><p>In particular, logging is very useful. It records a lot of information about what’s happening in your program. This can help a lot with debugging.</p><p>Alternatively, you can manually record information about errors.</p><h3>How to manually record errors</h3><p>The goal is to be able to view errors later. You can achieve that in any number of ways.</p><p>One way is to manually record errors in a database.</p><p>To do this, you can:</p><ol><li>prepare your database for recording errors</li><li>set up some code to record errors to the database</li><li>set up a global error handler to catch errors. (This error handler would call the code from step 2)</li><li>set up an endpoint in the back end so the front end can record errors too. (This endpoint would call the code from step 2)</li></ol><p>For example, you might use a <a href="https://www.mongodb.com/">MongoDB database</a> with a collection for errors. Every time an error occurs in your application, add information about it to the collection. You can organise the information in any way you like. For example, you could organise by the type of error or exception, by the error message, or by the last code in the call stack for the error.</p><p>After setting that up, you could set up a global error handler. This error handler would be called on errors that occur in your application. In the handler, record the error in your database.</p><p>Different frameworks and “environments” provide different ways to set up global error handlers. For example, in the Unity game engine, you can use Application.logMessageReceived += Handler;. On the front end of a website, you can use window.addEventListener(&#39;error&#39;, handler);.</p><p>Finally, you can set up an endpoint so that the front end can record errors too. Then, the front end can make a network request with information about the error it encountered.</p><p>Here’s an example call you could make from the front end:</p><pre>function handleError(errorEvent) {<br>  const {error} = errorEvent;<br>  const data = {stack: error.stack, message: error.message, type: error.name};<br>  fetch(&#39;https://example.com/errors&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)});<br>}<br>window.addEventListener(&#39;error&#39;, handleError);</pre><p>The function handleError above is executed any time an error occurs. It creates an object with useful information about the error. Then, it sends a network request to the back end. The back end will then record the information about the error so it can be viewed later.</p><h3>What information to record</h3><p>You want as much useful information about the error as possible. This will help you debug it later.</p><p>The article <a href="https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions">.NET best practices on exceptions</a> has some guidelines for this. Adapted for both error values and exceptions, they are to:</p><ul><li>use the predefined error types in your programming language if they’re relevant. Only create custom types if the predefined ones don’t apply.</li><li>if you create custom error types:</li><li>they should usually be subclasses of the main error types (if you use an OOP language)</li><li>they can optionally have custom properties (if they would be useful)</li><li>use grammatically correct error messages. For example ‘The file “foo.txt” could not be found.’.</li><li>include a localised string message in every error (if your application is localised)</li></ul><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>For the next steps, I recommend looking at the other articles in the <a href="https://programmingduck.com/articles/errors">error handling series</a>.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Recording photo — Photo by Krists Luhaers on Unsplash</p><p><em>Originally published at </em><a href="https://programmingduck.com/articles/error-recording"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b26260585c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to respond to errors — Crashing, ignoring, recovering and their use cases]]></title>
            <link>https://sargalias.medium.com/how-to-respond-to-errors-crashing-ignoring-recovering-and-their-use-cases-188d39b2c196?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/188d39b2c196</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 18:00:42 GMT</pubDate>
            <atom:updated>2021-11-08T15:44:18.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to respond to errors — Crashing, ignoring, recovering and their use cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWPTwnLBSgrKVb3uqAvdvw.jpeg" /></figure><p>What should a program do when it encounters errors? In my experience, a lot of programs hardly give any thought to this. Usually it’s just the bare minimum of silently ignoring bugs and <strong>maybe</strong> recording that they occurred.</p><p>However, this is an important consideration in <a href="https://programmingduck.com/articles/errors">error handling</a>. A program should behave correctly when errors occur.</p><p>In this article, we’ll examine:</p><ul><li>possible responses to errors</li><li>examples of error responses in common programs</li><li>how to handle bugs in your program</li><li>how to handle other errors in your program</li></ul><p>Let’s dive in.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvnz49ENj4J4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dvnz49ENj4J4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvnz49ENj4J4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4791b2fa5092e716d7a1d28a7a39f2fe/href">https://medium.com/media/4791b2fa5092e716d7a1d28a7a39f2fe/href</a></iframe><h3>Response options</h3><p>There are different ways that you can respond to errors. You can:</p><ul><li>crash the program</li><li>silently ignore the error</li><li>try to recover in some way</li></ul><p>Crashing the program is a good default option. There are multiple benefits to it.</p><p>One benefit is that the program won’t be doing the wrong thing. There have been multiple situations where software doing the wrong thing has been disastrous.</p><p>This doesn’t mean that crashing is good. It means that it’s <em>probably</em> better than silently ignoring bugs. For example, it’s fine for a calculator program to crash. You can just restart it and continue what you were doing. But, if a calculator has errors and produces the wrong result, that can be a big problem.</p><p>Another benefit to crashing is that it makes errors obvious. This means that you can debug the problem immediately.</p><p>In addition, crashing as soon as possible means that the stack trace will be more helpful. It will point to the problem code. Instead, if you silently ignore the error, the program may not crash until later (if at all). At that point, it won’t point to the real source of the error. This means that debugging will be harder.</p><p>Another option is to silently ignore errors. Sometimes, this option is good. It depends on the user experience. Later on, we see a few examples where ignoring the error is probably the best option.</p><p>The final option is to try to recover from the error in some way. The result should be as though the error never happened. The program should be able to continue executing correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eiERcZR3-93fM-HY.jpg" /></figure><h3>Examples of responses to errors</h3><p>Here are some examples of how different programs may respond when encountering errors.</p><h3>A program that’s in early development</h3><p>If a program is in early development, it’s probably fine to just crash on errors. This will make debugging easier.</p><h3>Most desktop applications</h3><p>Most desktop applications crash when something goes wrong (if they can’t recover in the background). This is usually fine. It’s very easy for the user to start the program again.</p><p>For programs that are “viewers” (such as Windows Photos), no data is lost.</p><p>For programs which change data (such as Microsoft Word), very little tends to be lost. These programs tend to have autosave features to minimise lost data.</p><h3>Error on “add to cart”</h3><p>Consider that you have an ecommerce website. There could be an error in the “add to cart” button where sometimes the product isn’t being added to cart.</p><p>How should that error be handled?</p><p>For starters, you probably want to notify the user. It would be very bad if the user doesn’t realise that a product is missing from their cart. They might go through checkout and order everything, wait for the item to arrive and never receive it. (I mean, I’ve done that without any errors to “add to cart” and I can tell you it’s bad…)</p><p>To notify the user, you could display a message to them. For example, you could tell them:</p><ul><li>the action failed</li><li>that they should try again later</li><li>that they should refresh the page and try again</li></ul><h3>A simple animation</h3><p>Consider that you have a simple website with a small animation that you trigger with JavaScript.</p><p>For this website, if the animation fails to trigger, it’s probably not a big deal.</p><p>In this case, you essentially want to ignore the error silently. Don’t notify the user that a problem occurred. The animation isn’t important enough to notify and distract the user from what they’re doing.</p><h3>A single player video game</h3><p>If there is a bug in a single player video game, it probably doesn’t matter. In most cases, it’s very bad for the user experience for the game to crash. Having buggy gameplay is preferred to crashing. In this case, the best option is probably to silently ignore the bug.</p><h3>An important system in an airplane</h3><p>For something life-critical, you would want to recover from errors very carefully and deliberately.</p><p>This might mean having redundancy. For example, you might have backup systems so that one can take over if something goes wrong. Or you might have a live-monitoring program, which can restart and reinitialise other programs that have errored or crashed. Or any other number of things. You might also use <a href="https://programmingduck.com/articles/defensive-programming">defensive programming</a> to prevent certain programs from failing in the first place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XYBdJ1qpaZiE_Klw.jpg" /></figure><h3>How to handle bugs</h3><p>A bug is when something unexpected or obviously wrong happens in your program. It arises from faulty coding. It wouldn’t be there if the code was correct.</p><p>When handling bugs (or any error), you need to consider:</p><ul><li>whether the bug is recoverable or not</li><li>the user experience</li><li>the development time for different responses</li></ul><p>Also, regardless of what you do, you should <a href="https://programmingduck.com/articles/error-recording">record errors to debug them later</a>.</p><h3>Is the bug recoverable (without crashing)?</h3><p>Some bugs are impossible to recover from. For example, there’s nothing you can do if some important code always fails. The only solution is to fix the code.</p><p>However, some bugs may be recoverable.</p><p>One example of possibly recoverable bugs are intermittent bugs. These are bugs that only occur under certain circumstances. This includes race conditions or errors that only happen with specific state.</p><p>With some effort, you may be able to handle these without restarting the main program. For example, if an operation fails, you could:</p><ul><li>try to run the operation again. If the problem is a race condition, it may work next time.</li><li>try to restart a faulty subprogram in the background. Then retry the operation afterwards.</li><li>try to manually fix the state of the program to something that works</li><li>offload the erroring operation to a server</li></ul><p>Another example may be something like running out of memory. Even this can be recoverable sometimes.</p><p>However, one issue is that you may not know that your program has a particular bug. After all, if you knew about the bug, then the best solution would be to fix it. So, if you don’t know about the bug, you might not have error handling for it.</p><p>The exception is if you’re doing <a href="https://programmingduck.com/articles/defensive-programming">defensive programming</a>. In this case, you’ll have error handling “just in case”. You won’t actually know of whether you have a bug or not. Instead, you’ll implement error handling pre-emptively for all kinds of possible bugs.</p><p>So, in summary:</p><ul><li>some bugs aren’t recoverable</li><li>some bugs are recoverable but you won’t have error handling for them</li><li>some bugs are recoverable and you’ll have error handling for them</li></ul><h3>The user experience</h3><p>As shown in the examples above, different programs need to respond to errors differently. Sometimes, it’s fine to crash the program. The user can restart it or another process can restart it automatically. At other times, you can silently ignore the error. In other cases, you may need to do everything in your power to recover.</p><h3>Effort in implementing different error responses</h3><p>In general, even though some bugs are recoverable, recovery can be extremely difficult. Some of the issues with it are explained in <a href="https://programmingduck.com/articles/defensive-programming">defensive programming</a>.</p><p>In comparison, crashing the program is very easy. Also, this usually fixes errors just as well (if not better) than manually recovering.</p><h3>Summary of handling bugs</h3><p>Generally, when you encounter bugs, the rule of thumb is to crash the program. The most important reason for this is because defensive programming can be very difficult to implement.</p><p>At other times, it’s okay to ignore the bugs. For example, when the area of the codebase that errored is insignificant.</p><p>Recovering from bugs is rare. It’s only reserved for defensive programming. Defensive programming is mostly used for software where uptime and correctness are extremely valuable.</p><p>Finally, regardless of what you do, remember to <a href="https://programmingduck.com/articles/error-recording">record errors to debug them later</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gNrGtRQ-n9La5T07.jpg" /></figure><h3>How to handle other errors</h3><p>“Other errors” are things which aren’t bugs in your program. These can include things like:</p><ul><li>failing to send a network request because the network connection dropped</li><li>failing to read a file from the filesystem because the file was deleted by the user, manually, a few milliseconds ago</li></ul><p>These “errors” are normal and expected. They are things that any program may encounter. There is nothing that your program can do to completely prevent them.</p><p>Once again, you need to consider:</p><ul><li>whether the error is recoverable or not</li><li>the user experience</li><li>the development time for different responses</li></ul><p>In general, many of these errors are both recoverable and easy to recover from.</p><p>For example, consider that a network request failed to send because the user lost internet connection. It’s relatively easy to show the user a message. Then, you can ask them try again after ensuring they’re connected to the internet. This also results in a good user experience. In comparison, crashing the program would be a very bad user experience.</p><p>As another example, you might try to write to a file that doesn’t exist. In this case, an appropriate and easy solution might be to create the file first.</p><p>So, overall, the common advice for these errors is to handle and recover from them. Of course, the details depend on your program. Some of these errors may be unrecoverable. In this case, crashing the program may be a better option.</p><h3>Final notes</h3><p>So that’s it for this article. I hope that you found it useful.</p><p>As always, if any points were missed, or if you disagree with anything, or have any comments or feedback then please leave a comment below.</p><p>For the next steps, I recommend looking at the other articles in the <a href="https://programmingduck.com/articles/errors">error handling series</a>.</p><p>Alright, thanks and see you next time.</p><h3>Credits</h3><p>Image credits:</p><ul><li>Signs photo — Photo by Alexander Schimmeck on Unsplash</li><li>Jenga photo — Photo by Michał Parzuchowski on Unsplash</li><li>Person photo — Photo by Sebastian Herrmann on Unsplash</li><li>Chess photo — Photo by Nothing Ahead from Pexels</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/error-responses"><em>https://programmingduck.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188d39b2c196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naming (in code) — The ultimate guide and reference]]></title>
            <link>https://sargalias.medium.com/naming-in-code-the-ultimate-guide-and-reference-d356c8f7c387?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d356c8f7c387</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 18:00:27 GMT</pubDate>
            <atom:updated>2021-06-22T01:27:50.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>Naming (in code) — The ultimate guide and reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpLKavD3LDJSpLltH3JxQw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMsqQCfq5xNY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMsqQCfq5xNY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMsqQCfq5xNY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/39bd0210650001f00313031553b383eb/href">https://medium.com/media/39bd0210650001f00313031553b383eb/href</a></iframe><p><a href="https://programmingduck.com/articles/programming-principles">Programming principles</a> tell us that naming in code is important. This article aims to be a complete learner’s guide for naming in code. It also aims to be a reference about naming that you can refer to in the future if you need to.</p><p>For certain things, such as naming methods, there are different naming conventions. We’ll mention a few so that you’re aware of how they work and the options you can choose from.</p><p>Overall, we’ll examine:</p><ol><li>the motivation for wanting good names</li><li>general naming tips for all code</li><li>established naming conventions for specific things such as variables and classes</li></ol><h3>Motivation for good names</h3><p>The motivation for good names comes from <a href="https://programmingduck.com/articles/programming-principles">clean code and programming principles</a>. Code should be:</p><ul><li>immediately obvious and easy to understand</li><li>easy to change</li></ul><p>Being easy to understand helps because:</p><ul><li>code that’s easy to understand will be faster to understand. This means that you can work faster. You’ll spend less time trying to understand old code and more time writing new code.</li><li>code will be possible to understand. In comparison, if some code is difficult to understand, you may not understand it even after spending a long time reading it. Someone who’s less experienced may have even worse luck. Additionally, you may misunderstand how the code works, especially if you’re not fully paying attention that day. Misunderstanding code makes it very easy to create bugs.</li></ul><p>Good names help with both cases.</p><h3>How good names make code faster to understand</h3><p>If something is well-named, then you don’t need further details to understand it. This saves you time.</p><p>For example, consider:</p><ul><li>a function named printHelloToTheScreen</li><li>a function named multiplyBy2</li><li>a constant named PI</li><li>a constant named MAXIMUM_ALLOWED_LOGIN_ATTEMPTS</li><li>a static class or module named Math</li><li>a variable named circumference</li><li>a variable named userInfo</li></ul><p>In a codebase, you would have a pretty good idea of what those do just from the name.</p><h3>How good names make code easier to understand</h3><p>When reading code, you have to:</p><ol><li>read (parse) what it does</li><li>understand why it does it, or rather, understand what it’s trying to do conceptually</li></ol><p>For example, it’s not enough to think “this code removes initial whitespace from the string, then it sends a network request”. Instead, you have to understand “this code formats the username and then sends a password reset request”.</p><p>Here’s a code example that’s difficult to understand:</p><pre>function foo(a, b) {<br>  const c = PI * a ** 2 * 8 / b;<br>  return c &gt; 1 ? c : 1;<br>}</pre><p>What’s the 8 there for? What&#39;s b? Why does it return a minimum of 1? What&#39;s the purpose of this function?</p><p>If you’re trying to do something such as change the area, you don’t know if this function is relevant or not. Even if you suspect it is, you don’t know what it does or why.</p><p>Something like this would be much better:</p><pre>function calculateRemainingArea(radius, reductionFactor) {<br>  const area = PI * radius ** 2;<br>  const remainingArea = area * AREA_REDUCTION_RESISTANCE / reductionFactor;<br>  return Math.min(remainingArea, MINIMUM_AREA);<br>}</pre><p>So, good names help, because <strong>they provide meaning</strong>. They help you understand what the code does and why it does it.</p><p>To get the benefit, all you have to do is give a good name to the thing.</p><p>As another example, someone may not understand PI * a ** 2. They may think &quot; PI, a, power of 2... What the heck is that??&quot;. To make it easier, all you have to do is replace that line with const circleArea = PI * radius ** 2. It helps a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6WIzBjJHHlzJaeY.jpg" /></figure><h3>General naming tips for code</h3><p>In short, a good name is something that immediately tells you what something is or does. It’s not surprising. It doesn’t take effort to understand it. You understand it without thinking about it.</p><p>A bad name is something that you read and you wonder “what’s that”, or “what does that do?”. Something that requires you to think more.</p><p>When writing names, they should be understandable by someone that’s never seen this code before. They need to make sense, be consistent and be sufficiently descriptive.</p><p>Here are some pointers to accomplish this.</p><h3>Have clear naming conventions</h3><p>Your codebase should have clear conventions. This is probably the most important point in this article. If you’re already following a convention, it’s probably best to stick to it, even if an alternative may be more descriptive.</p><p>Conventions apply consistency. <a href="https://programmingduck.com/articles/programming-principles">Programming principles</a> tell us that consistency is very important.</p><p>It allows you to work faster. You can make certain assumptions about how the code works and what certain things mean. Additionally, when thinking of a name for something, the convention may already have a rule for it. This makes things easier.</p><p>Also, not following conventions can cause mistakes. You may assume that a common convention is being followed in the codebase. If you’re wrong, then you may have the wrong idea about how some code works. At that point, it’s very easy to create bugs.</p><p>Ideally, you should follow conventions that already exist in your programming language or framework. This makes things easier for new developers to the company. Some examples are the <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines">.NET naming guidelines</a> and <a href="https://github.com/airbnb/javascript">Airbnb JavaScript style guide</a>. Otherwise, you can also create your own custom conventions for your project or company.</p><h3>Prefer descriptive names</h3><p>Always consider, will the next person who looks at this name understand it easily?</p><h4>Use full words</h4><p>Generally, full words are easier to understand. For example calculateArea or createWindow. Abbreviated words may be harder to understand. In general, avoid names like calcArea or cWin.</p><h4>Avoid very short variable names</h4><p>In particular, avoid single-letter or very short variables, such as d. It could mean anything: the document, data, date, or days.</p><p>The exception to this is when the name is used in a very small scope and what it represents is immediately obvious. In this case, it’s easy to look one or two lines up and see where it was defined. Here’s a code example using the variable e.</p><pre>function sendData() { /* sends a network request */ }<br>function handleFormSubmission(e) {<br>  const formElement = e.target;<br>  const formData = FormData(formElement);<br>  sendData(formData);<br>}</pre><p>Here, the variable e represents the event object. We know this because the name handleFormSubmission and the function signature represent an event handler. e is only used one line under where it is defined, so it&#39;s still easy to work with.</p><p>Nevertheless, I would still personally use event. I consider readability more important than minor saving of keystrokes like that.</p><p>Another acceptable example is using i in for loops and such. That&#39;s a convention that everyone understands.</p><h4>Acronyms</h4><p>If an acronym is very common, then it’s okay to use it. Some examples are the acronyms HTML, UI, IO, OS, JSON, XML, HTTP.</p><p>If an acronym is uncommon, then prefer the fully expanded name. If in doubt, you should probably use the full version.</p><h3>Conciseness matters</h3><p>Names that are sufficiently descriptive come first. However, that doesn’t mean that you need super long names.</p><p>Super long names, such as a variable named integerNumberOfEnginesInObject are difficult to work with. engineCount would be sufficient.</p><p>In general, if you can have the same clarity with a shorter name, use the shorter name.</p><h3>Consider the context</h3><p>The name of the surrounding context can provide useful clues for the purpose of something. This means that sometimes, you can get away with using shorter names.</p><p>For example, if you have a class called Users, then the method for creating a new user can be called create. The usage of it would be something like users.create() (where users is an instance of Users). That&#39;s sufficiently descriptive. You don&#39;t need to call the method createUser in this case.</p><h3>Casing</h3><p>The prevalent casings in programming (excluding HTML and CSS) are pascal case, camel case and snake case. The one you use depends on the conventions for your programming language or framework.</p><h4>General format of each casing</h4><p>Snake casing is lower cased and uses underscores to separate words. For example this_is_snake_case.</p><p>In pascal casing, every word begins with a capital letter. For example ThisIsPascalCase.</p><p>Camel casing is similar to pascal casing, except that the first word begins with a lowercase letter. For example thisIsCamelCase.</p><h4>Casing for acronyms</h4><p>For acronyms, the conventions vary.</p><p>On the front end, it seems that acronyms are always fully capitalised, regardless of length. Some examples are performance.toJSON(), XMLDocument, HTMLCollection and DOMString.</p><p>However, in some other languages, such as the .NET languages, the convention is:</p><ul><li>if an acronym is only two letters long, the second letter should have the same casing (upper or lower case) as the first one. For example, UIInput (pascal case), uiInput (camel case) and fooUIInput.</li><li>if an acronym is three letters or longer, only the first letter should be capitalised if necessary. For example JsonFoo (pascal case), jsonFoo (camel case).</li></ul><h4>Capitalisation for compound words</h4><p>It’s a convention to treat compound words as one word in terms of capitalisation. For example, use callback and endpoint instead of callBack and endPoint. You can find a thorough list of common compound words, used in programming, on the <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions">.NET naming guidelines on capitalisation</a>.</p><h3>Prefer semantic naming</h3><p>Semantic naming means to name something after its purpose or meaning. In order of priority, this means:</p><ol><li>what the purpose of it is, or what it does</li><li>how it does it</li></ol><p>As a bonus, it also results in code that is less likely to change in the future.</p><p>When naming things, consider: what’s the most important thing about the thing you’re naming? What’s the most suitable name for someone else to understand it conceptually?</p><p>Usually, users care more about what something is doing, rather than how it’s doing it. Although, sometimes, it’s the “how” that’s the most important.</p><p>Here are some examples of semantic naming.</p><h4>Example with a variable name</h4><p>If you have a variable that holds a collection of users, the important part is that it contains users. Whether it’s a list or a map is less important. Not to mention that your IDE and type declarations provide that information anyway.</p><p>Therefore, the name:</p><ul><li>users would be suitable</li><li>userList is less preferable. The &quot;list&quot; part is less important than the users part. Also, if you change the data structure in the future you&#39;ll have to update the variable name.</li><li>userCollection is also less preferable, because the &quot;collection&quot; part is less important than the &quot;user&quot; part. However, at least you won&#39;t have to update the variable name if you change the data structure in the future.</li></ul><h4>Example with interfaces and implementations</h4><p>In OOP code, you tend to have interfaces with potentially multiple implementations. An interface may be called something semantic and generic, such as Sorter, for a sorting algorithm. That&#39;s the significant thing about it, the fact that it sorts. The how isn&#39;t important at the interface level.</p><p>The different implementations can be called after the sorting algorithm they implement. That’s the important thing about them and the only thing that separates them from one another. It’s the information a user of that specific class would want. For example BubbleSort, MergeSort, Quicksort.</p><h4>Example with a method for sorting</h4><p>Imagine that you have a class containing a collection of something. You also have a method for sorting it, say, alphabetically.</p><p>If you only have one sorting method, then it would be preferable to name it sort. A name such as sortWithQuicksort or quicksort would be unnecessary information that the user doesn&#39;t care about. If you think about it, the caller of the code wants to sort. They aren&#39;t particularly interested in the specific algorithm your class uses. (The only exception is if your class is an actual bottleneck to performance or something, but that&#39;s a different topic.)</p><p>Additionally, in the future, you may change the sorting algorithm that the class uses to merge sort. In that case, the name sortWithQuicksort wouldn&#39;t make sense any more.</p><p>The solution is to name your public method sort.</p><p>The fact that you’re using quicksort is still important. Developers working on the implementation of the class would want to know that. Some options for that are to have a private method named quicksort, or import and use a quicksort function from somewhere else in the codebase.</p><p>For example:</p><pre>// pseudocode<br><br>class Users<br>{<br>  // the public method with a name that&#39;s useful to callers<br>  public User[] Sort()<br>  {<br>    return _quicksort(this.users);<br>  }<br><br>  // the private method with a name that&#39;s userful to someone working on this class<br>  private T[] _quicksort&lt;T&gt;(T[] items)<br>  {<br>    /* implementation of quicksort */<br>  }<br>}</pre><h4>Example with front end CSS</h4><p>In front end CSS, there are a few approaches. The approach you choose decides what’s important about the name of your class.</p><p>When using the BEM naming convention, the important thing is the purpose of the element, not the styling. For example, you would use the CSS class page-heading instead of large-heading-red. That&#39;s because, tomorrow, the styling of the page heading may change. At that point, the non-semantic name won&#39;t make sense anymore, but the semantic name will.</p><p>If you’re using a UI component library, then the styling of the component is more important than the purpose of the component. For example button-primary instead of add-to-cart-button. That&#39;s because classes like button-primary are the main ones you&#39;ll be working with throughout your code.</p><h3>Other tips from Uncle Bob</h3><p>Some tips that are mentioned in <a href="https://www.oreilly.com/library/view/clean-code-a/9780136083238/">Uncle Bob’s book Clean Code</a> are to:</p><ul><li>make meaningful distinctions. Avoid variables that seem similar or the same, such as accountInfo or accountData. A user of that code won&#39;t be able to tell the difference.</li><li>use pronounceable names. Names should be easy to read out loud. Some examples to avoid are names such as genymdhms and modymdhms. Better names would be generationTimestamp and modificationTimestamp.</li><li>use searchable names. Names should be easy to search using your code editor. Essentially, avoid names that are one or two letters long, as searching for them will return too many matches.</li><li>avoid using cute / offensive words. Avoid names such as whack() and seeYouLaterFiles(). Be professional and consistent.</li><li>pick one word per concept. For example, don’t mix the words “fetch”, “get” and “retrieve” for the same kind of operation throughout your codebase. Pick one of them and use it consistently.</li><li>avoid puns. Avoid using the same word for different concepts. For example, if in one class add() adds two numbers, in a different class add() shouldn&#39;t insert into a list.</li></ul><h3>Other tips from the .NET naming conventions</h3><p>.NET makes some additional recommendations. Some of them are specifically for .NET languages. However, you may want to keep them in mind anyway.</p><p>The recommendations are to:</p><ul><li>prefer naturally readable names. For example, use HorizontalAlignment instead of AlignmentHorizontal.</li><li>avoid using names that conflict with common keywords in other programming languages</li><li>prefer semantic names rather than language specific names. For example, use GetLength instead of GetInt.</li><li>prefer generic CLR type names instead of language-specific names. For example name a method ToInt64 instead of ToLong. That&#39;s because methods like these may be used in other CLR-compatible languages where the data type long doesn&#39;t exist. Therefore, that name won&#39;t make sense in those languages. However, Int64 exists and makes sense for all CLR languages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pVVuzZtxecOEQRNV.jpg" /></figure><h3>Naming conventions for specific use cases</h3><p>Here are some common naming conventions for things such as variables, functions, classes, etc.</p><h3>Variables</h3><p>Variables are just names or labels for values and objects. Some general conventions for them are that:</p><p>The rules change a bit for constants and variables holding Boolean values.</p><h4>Constants</h4><p>Some programming languages write constants fully capitalised and with snake case. This includes JavaScript, Python and Java. Some example constants are:</p><p>Here, “constant” refers to special values. These are values that don’t depend on runtime. They could easily be placed in a configuration file, away from your application code.</p><p>“Constant” doesn’t refer to a normal local variable that just happens to be immutable. Those follow the same conventions as normal variables.</p><p>Here are some examples of “constants” and “normal variables that just happen to be immutable”:</p><ul><li>final MAX_ATTEMPS_BEFORE_LOCKOUT = 5 (this could be in a configuration file, it&#39;s a special constant)</li><li>final float result = SomeClass.factorial(someNumber) (this is just a local variable that happens to be immutable. It varies at runtime depending on someNumber. It can&#39;t be placed in a configuration file)</li><li>const URL_ENDPOINT = &#39;/ajax/foo&#39; (this could be in a configuration file, it&#39;s a special constant)</li><li>const filteredArray = array.filter(a =&gt; !a) (this is just a local variable that happens to be immutable. It varies at runtime depending on array. It can&#39;t be placed in a configuration file)</li></ul><h4>Booleans</h4><p>For variables that have Boolean values, the convention is to phrase them as a question. Start them with a predicate such as “is”, “has”, “had” and “can”. These clearly denote that the variable holds a Boolean.</p><p>Some example Boolean variables are:</p><p>In addition to being readable standalone, they read nicely in conditional statements:</p><pre>if (hasLoaded) {<br>  doSomething();<br>} else {<br>  doSomethingElse();<br>}</pre><p>In comparison, if you don’t use a predicate, you would use a name such as complete. This is both a verb and an adjective. It can denote a number of things. It could be a function that you run to complete something, or a variable that holds things that have already completed, or a Boolean that states whether something has completed or not, or an event name. What it represents is more ambiguous, so prefer predicates instead.</p><p>A verb like completing is slightly better. It can&#39;t denote a function, because the &quot;ing&quot; in &quot;completing&quot; means that something is already happening. It&#39;s not something that you can start running now (like a function call). However, it can still be any of the other options. Overall, it&#39;s still preferable to use predicates.</p><h3>Functions</h3><p>Functions are units of code that do something. Conventions for function names are that:</p><ul><li>they should be verbs</li><li>they generally use camel case or snake case, depending on your programming language</li></ul><p>Some example function names are:</p><p>For functions that return a Boolean, a common convention is for them to start with a predicate. This is similar to variables that contain Boolean values.</p><p>Some example names for functions that return Booleans are:</p><p>Another convention I’ve seen is for “transformer” or “converter” functions. These are functions that convert from one thing to another. They usually begin with “to”, followed by the type they’re converting to.</p><p>Some examples of transformer function names are:</p><h3>Classes</h3><p>Classes are units of code that contain methods and attributes.</p><p>Some conventions for classes are that:</p><ul><li>they use Pascal case</li><li>they should be nouns (or noun phrases)</li></ul><p>Some example class names are:</p><h4>General property names</h4><p>In general, attributes are named similarly to variables. Methods are named similarly to functions.</p><p>However, as mentioned earlier, the name of the class provides some context.</p><p>This means that you may be able to use a less specific name for a method / attribute than you would use for the equivalent function / variable.</p><p>For example, inside a class Users, you may have a method named create. The usage of it would be something like users.create() (where users is an instance of Users), which is sufficiently descriptive.</p><h4>Casing and prefixing for properties</h4><p>In terms of casing and prefixes, different languages and frameworks have different conventions.</p><p>For example, the <a href="https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html">Java naming conventions</a> mention that methods and attributes should be camel cased.</p><p>The <a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 Python naming convention</a> also mentions camel casing. However, it adds that private properties should be prefixed with an underscore. For example (_privateProperty).</p><p>The <a href="https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions">C# coding conventions</a> seem the strictest. They state that:</p><ul><li>public properties should be pascal cased (for example PublicMethod or PublicVariable)</li><li>private or internal properties should be prefixed with underscore and be camel cased (for example private void _privateMethod)</li><li>private or internal static properties should be prefixed with s_ and be camel cased (for example private static foo s_workerQueue)</li><li>private or internal thread properties should be prefixed with t_ and be camel cased (for example private static foo t_timeSpan)</li></ul><p>If, for whatever reason, you were creating your own convention, I would personally recommend:</p><ul><li>pascal casing for methods and camel casing for attributes (this is the convention used in the Unity game engine). The reason for this is be to differentiate between Boolean attributes (such as isValid) and methods that return Booleans (such as IsValid(data)). As a second choice, I would use camel case for methods.</li><li>underscore prefix for non-public properties</li><li>possibly (not sure yet) the s and t prefixes from C# for the relevant things. As the <a href="https://www.python.org/dev/peps/pep-0020/">Zen of Python</a> says &quot;Namespaces are one honking great idea - let&#39;s do more of those!&quot; (I consider prefixes to have a similar effect)</li></ul><h3>Interfaces</h3><p>Names for interfaces are similar to class names. They use pascal case and are usually nouns. Sometimes they can be named with an adjective, for example “Readable”.</p><p><a href="https://www.oreilly.com/library/view/clean-code-a/9780136083238/">In the book Clean Code</a>, Uncle Bob recommends avoiding the I prefix for interfaces. The <a href="https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html">Java naming conventions</a> recommend the same. For example interface Foo.</p><p>The C# coding conventions recommend prefixing interfaces with I. For example interface IFoo.</p><p>Personally, I have a minor preference for avoiding the prefix. That’s because, as a user of the code, I’m not particularly interested on whether I’m working with an interface or a class.</p><h3>Enums</h3><p>The Java convention is to treat enums like classes with constants. This means to name the enum type with pascal case and the fields fully uppercase.</p><p>C# also treats them the same as classes. This means to name both the enum type and the fields using pascal case.</p><p>Personally, I prefer the Java convention because it differentiates between constants and other values.</p><h3>Events, event handlers, messaging systems and commands</h3><p>There are a few things to consider regarding events and their relevant functions.</p><h4>Event names</h4><p>Event names:</p><ul><li>refer to an action</li><li>are normally named using verbs. For example “downloaded”, “loaded”, “deleted”, “damaged”, “moved”.</li><li>generally use present tense for events that fire before an action starts. For example, before submitting a password reset request, you might fire an event named “passwordResetRequestSubmitting”.</li><li>generally use past tense for events that fire after an action completes. For example, after submitting a password reset request, you might fire an event named “passwordResetRequestSubmitted”.</li></ul><p>In my experience, these conventions are common across many languages. However, there isn’t much official documentation for them. One exception is with <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members">.NET, where they formally state these guidelines</a>.</p><p>For the actual name of the event, you can use whatever makes sense to you. If your event is created in a class, the class name may provide sufficient context. For example, if you have a class Shape, you may have an event named areaChanged. The usage would be something like myShape.areaChanged += someHandler or myShape.areaChanged.subscribe(someHandler). The event name &quot;areaChanged&quot; is sufficiently descriptive in this case.</p><p>In terms of casing, follow the convention in your programming language. C# uses pascal casing for public members (including events). Most other languages use camel casing.</p><p>Some example event names are:</p><ul><li>fileDownloading / fileDownloaded</li><li>userRegistering / userRegistered</li><li>uiElementXUpdating / uiElementXUpdated</li></ul><h4>Event handlers</h4><p>For event handler functions, there are a few conventions. In front end, <a href="https://reactjs.org/docs/handling-events.html">React tends to use the prefix “handle”</a>. C# recommends the suffix “EventHandler”. Other languages may have other conventions.</p><p>Some example names of event handler functions are:</p><ul><li>handleUserSubscribed / userSubscribedHandler / UserSubscribedEventHandler</li><li>handleFileDownloaded / fileDownloadedHandler / FileDownloadedEventHandler</li></ul><p>My personal preference is to use the “handle” prefix. This keeps the function a verb, which is the convention for functions.</p><h4>“On” functions</h4><p>Functions that exist solely to raise events tend to have the name on&lt;EventName&gt;. For example &quot;onAreaChanged&quot;.</p><p>One case for using these is in classes that may be derived.</p><p>Here’s a C# example:</p><pre>class Foo<br>{<br>  public event EventHandler FileDownloaded;<br><br>  protected virtual void OnFileDownloaded(EventArgs e)<br>  {<br>    EventHandler handler = FileDownloaded;<br>    if (handler != null) {<br>      FileDownloaded(this, e);<br>    }<br>  }<br><br>  public void Something()<br>  {<br>    OnFileDownloaded(EventArgs.Empty);<br>  }<br>}</pre><p>Here, we have a method named OnFileDownloaded whose only purpose is to raise the event.</p><p>This convention may work a bit differently in front end, but it still follows the general idea. For example, in React, you can name props something like “onClick” or “onSomeEvent”. Event handler functions that you define inside a component can use the “handle” prefix.</p><p>Here’s a React example:</p><pre>import React from &#39;react&#39;;<br><br>const ParentComponent = () =&gt; {<br>  function handleButtonClicked() {/* do something */}<br>  return &lt;ChildComponent onClick={handleButtonClicked} /&gt;;<br>};<br><br>const ChildComponent = ({ onClick }) =&gt; {<br>  const handleClick = (e) =&gt; {<br>    console.log(&quot;clicked&quot;);<br>    onClick(&quot;foo&quot;);<br>  };<br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>};</pre><p>Here, each component creates event handler functions prefixed with “handle”. The child component has the prop named “onClick”. In the child component, the handleClick function calls the onClick prop.</p><h4>More global message names</h4><p>PubSub (message bus) and analytics have similarities to local events, but they are more global. They span a much larger area of the codebase. The can even span multiple applications (as might be the case for analytics).</p><p>With these, it’s important to use more specific names, otherwise you won’t know what they refer to.</p><p>A good way to do this is to use namespaces and prefixes, along with specified delimiters.</p><p>For example, with PubSub event names, you can have a namespace for the relevant area of the codebase. The format of the event name can be &lt;areaOfCodebase&gt;/&lt;eventName&gt;. For example:</p><ul><li>ui/themeChanged</li><li>ui/fontSizeChanged</li><li>player/damaged</li><li>player/poweredUp</li><li>user/registering</li><li>user/registered</li><li>user/deleted</li></ul><p>And, as explained on <a href="https://davidwells.io/blog/clean-analytics">clean analytics by David Wells</a>, for analytics you could use a format like &lt;Source&gt;:&lt;object&gt;_&lt;actionName&gt;. For example:</p><ul><li>site:newsletter_subscribed</li><li>app:site_deployed</li><li>cli:user_login</li><li>api:site_created</li></ul><p>These are just examples. In your own codebase, you can use as many namespaces as you want. The namespaces can be anything.</p><p>Likewise, the delimiter(s) can be anything you want. Some examples are “/”, “::”, “:”, “_”, or even no delimiter.</p><h4>Commands</h4><p>Commands are written similarly to functions. They are verbs in an imperative mood. They are also used in PubSub. The notes about namespaces and delimiters, mentioned above, apply to them.</p><p>Commands also usually expect a response. In other words, a command such as “CreateUser” will have a response message such as “CreateUserResult”, “CreateUserSucceeded” or even “UserCreatedNotification”. Overall, I’m not aware of strong conventions for these, so you can probably use whatever you like.</p><p>My personal preference for response names comes from <a href="https://jimmybogard.com/message-naming-conventions/">Jimmy Bogard’s post on message naming conventions</a>. I generally append “Result”, “Reply” or “Response” to the original command name.</p><p>Some example formats for command names and their namespaces are &lt;Verb&gt;&lt;Subject&gt; and &lt;subject&gt;/&lt;verb&gt;. For example:</p><ul><li>Possible commands are “RegisterUser” or “user/register”. Possible responses are “registerUserResponse” or “user/register_result”</li><li>Possible commands are “DamagePlayer”, “player/damage”. Possible responses are “DamagePlayerResponse”, “player/damage_result”</li></ul><h3>File names</h3><p>For file names, you need to consider conventions for casing, as well as what to name the file based on the code it contains.</p><h4>File name casing conventions and delimiters</h4><p>For file naming, there are different conventions depending on the language, framework and style guide you follow.</p><p>Many conventions recommend file names that are all lower case. Words can be separated with either hyphens (-) or underscores (_). For example:</p><ul><li>in HTML, the convention is all lower case, with hyphens as separators. Underscores are far less common. One reason for this is because the HTML file name may reflect in the URL (especially with older servers). Underscores in URLs are far less common than hyphens.</li><li>in CSS, the convention is all lower case with hyphens or underscores as separators</li><li>In Python, PEP 8 recommends file names to be all lower case, with underscores as separators</li><li>the Google JavaScript style guide recommends file names to be all lower case, with underscores or hyphens as separators</li></ul><p>Between hyphens and underscores, you can use either. Both are acceptable. In general, I prefer to use hyphens to be consistent with my CSS classes (which conventionally use hyphens) and for the reasons mentioned for the HTML. However, if you commonly use snake case in your programming language, or if you don’t write HTML and CSS, it might feel more consistent to use underscores instead of hyphens.</p><p>Some example file names are:</p><ul><li>index.html, index.css, index.js</li><li>third-party-analytics.js</li><li>enemy-mover.js</li></ul><p>Along with that, there are other conventions that recommend camel or pascal case for your files. For example:</p><ul><li>C# and Java recommend naming your file the same as the main thing in your file. This means using pascal case, same as your classes and interfaces.</li><li>the AirBnB JavaScript style guide recommends naming your file the same thing as your default export. Again, this means using camel or pascal case, at least for your JavaScript files.</li></ul><p><a href="https://reactjs.org/docs/faq-structure.html">React takes it a step further and recommends naming all of your files consistently in each folder</a>. For example:</p><ul><li>MyComponent.js</li><li>MyComponent.css</li><li>MyComponent.test.js (test files tend to have the special extension .test.js)</li></ul><p>So which should you choose? First, consider if one of the conventions is more common than the others for your programming language or framework. That’s the natural choice. Otherwise, you can do whatever you like. My personal recommendation is to choose the naming convention that best matches the code in your files. For example, when working on the front end, the convention is for everything in your HTML and CSS to be lower case with hyphens as separators. Therefore, you might want to use that as the naming convention.</p><p>As another example, when working on React applications that use CSS modules, you might prefer to write CSS using pascal case and underscores. This makes it easier to use your CSS in your JavaScript, for example styles.Foo_bar (where Foo_bar is your CSS class), as hyphens aren&#39;t allowed in JavaScript. In this case, it may feel more natural to name your files using pascal case.</p><h4>Choosing a file name based on the code it contains</h4><p>In general, you want to name your file based on its purpose.</p><p>This is supported by the C# naming conventions and Java naming conventions. They state that your file name should be the same as the main thing you define in your file. For example, if you define a class Foo, your file name should be Foo.cs or Foo.java.</p><p>The AirBnB JavaScript style guide also agrees with this. It states that your file should be named after your default export. Whether or not you use default exports is a separate matter. But the point is the same. It means to name it after the purpose, or the most important thing in your file. Normally (but not always) that’s thing that you would export default, if you were using export default.</p><p>One exception is if your default export is named “main”, “setup” or something similar. It doesn’t make sense for a file to be called “main”, especially if many files have a similar default export. In that case, consider what the purpose of the file is. An alternative is to consider what the equivalent OOP code would be.</p><p>For example, consider that you have a class that deals with carousel functionality. Your OOP code would probably be a class named “Carousel”. In comparison, if you write it using functions, it might look like this:</p><pre>function handleChangeToNextSlide() {<br>  // code to change to next slide when user clicks the relevant button<br>}<br><br>function main() {<br>  // find DOM elements that are supposed to be carousels<br>  // set up event listeners on those elements<br>}<br><br>export default main;</pre><p>In the equivalent OOP code, the code in main would be in the constructor of the class Carousel. In this case, my recommendation would be to name the file carousel. That&#39;s its true purpose. Alternatively, you could also change main to setupCarousel or something and name the file after that.</p><p>As for some other cases:</p><ul><li>If your file defines multiple classes: Well, most style guides would tell you to avoid files with multiple classes. Consider whether you can separate each class into its own file. Although, if you only have one public class, then that’s fine. Name the file after the one public class, not the private ones.</li><li>If you use functions instead of classes, there might be some cases where none of the functions would suitable to export default. Again, you need to consider what the purpose of the file is. For example, if you have some functions that are used in your test files, then perhaps “test-utilities” would be a good name. Alternatively, you can consider what the equivalent OOP code would be. You would probably have a static class with static methods. Name your file after the name of that static class.</li></ul><h3>Package names and namespaces</h3><p>In practice, many packages don’t follow naming conventions at all. That’s because a developer can upload a package with whatever name they want. There usually aren’t many checks.</p><p>However, there are naming conventions for packages and for different package repositories.</p><p>Java and <a href="https://search.maven.org/">Maven</a> use the format of &lt;groupID&gt;&lt;artifactID&gt;. The group ID part is generally a reversed domain name. For example, if your domain is example.com, the group ID would be &quot;com.example&quot;. It can have subgroups (additional namespaces). For example &quot;com.example.plugins&quot;. The artifactID is the name of the jar. For example &quot;junit&quot; or &quot;spring-web&quot;. In general, artifact IDs tend to be fully lower case with hyphens to separate words.</p><p><a href="https://www.npmjs.com/">NPM (node package manager)</a> tends to use direct package names, such as “react-dom”, or prefixed with a namespace or company name, such as “@babel/preset-env”. They tend to be fully lower case with hyphens to separate words.</p><p>With <a href="https://www.nuget.org/">NuGet</a> (package repository for .NET), the number of namespaces vary, just like with Maven and subgroups. There are many packages with a single name, such as “Moq”. There are also many packages of the format &lt;CompanyName&gt;.&lt;Package&gt;, such as &quot;AWSSDK.Core&quot;. There are also packages with many namespaces, such as &quot;Microsoft.Extensions.FileProviders.Abstractions&quot;. If you want to follow the example of the packages released by Microsoft, then use pascal case, optionally a company prefix and as many namespaces as you need.</p><p>Namespaces (in code) seem to follow similar concepts and conventions to packages.</p><h3>Final tips</h3><p>Remember that naming is hard.</p><blockquote><em>There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton</em></blockquote><p>However, spending some time to come up with a reasonable name is usually worth it.</p><p>Also, as always, be pragmatic. It’s okay to break these conventions once in a while. They are only here to help you make good and consistent decisions most of the time. For example, it’s okay if you feel that adding the data structure to the name will help, such as userList. It&#39;s up to you to decide what&#39;s best for your project.</p><p>In addition, you probably can’t spend an unreasonable amount of time coming up with good names. So, sometimes, if you’ve already spent too long, you might need to use the best name you’ve come up with so far and move on.</p><p>Overall, the most important thing from this article is that you understand the principles behind naming. In particular, that names should make the code easy to understand. If you understand that, then you’ll be fine. You’ll be able to come up with your own solutions and conventions even in unfamiliar situations.</p><h3>Final notes</h3><p>So that’s it for the article. I hope that you found it useful.</p><p>If you’ve encountered any awful names in code you’ve worked on, please leave a comment with them!</p><p>Also, if you want to discuss anything, disagree with anything, or have any feedback in general, please leave a comment below.</p><p>Alright, see you next time 🙂</p><h3>Image credits</h3><ul><li>Cover photo (modified) — Photo by Paul Stollery on Unsplash</li><li>Clear Bulb Beside White Notepad on White Surface — Photo by Burak Kebapci on Pexels</li><li>Green leaf with white card — Photo by Helena Hertz on Unsplash</li></ul><p><em>Originally published at </em><a href="https://programmingduck.com/articles/naming"><em>https://programmingduck.com</em></a><em> on June 15, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d356c8f7c387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Carousel slider tutorial with HTML, CSS and JavaScript]]></title>
            <link>https://sargalias.medium.com/carousel-slider-tutorial-with-html-css-and-javascript-373b6d308617?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/373b6d308617</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Thu, 27 May 2021 18:00:45 GMT</pubDate>
            <atom:updated>2021-06-06T00:14:59.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1K52YJo3Kdw9UKi3.jpg" /></figure><p>In this post we’ll look at how to make a simple carousel with HTML, CSS and JavaScript. We will use good code practices, keep accessibility in mind and also consider how we can test the carousel.</p><p>The carousel will be a “moving carousel”. Slides will move in from left to right, or right to left, with a transition. It won’t be an in-place carousel where a slide fades out while another one fades-in.</p><p>If you prefer a video version, here it is. It goes into much more detail than this post.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQruodbmSq0A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQruodbmSq0A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQruodbmSq0A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/095aae89cbe8ce8e14bd1165d3a3d360/href">https://medium.com/media/095aae89cbe8ce8e14bd1165d3a3d360/href</a></iframe><h3>Basic functionality</h3><p>We’ll start with the basic functionality. That’s the basic HTML, CSS and JavaScript.</p><h3>HTML</h3><p>We’ll keep the HTML fairly simple. We basically need:</p><ul><li>a container for the carousel</li><li>the carousel controls</li><li>the slides</li></ul><p>We won’t focus very much on the HTML head or anything other than the carousel. The rest is standard stuff.</p><p>As for the actual carousel, here is some HTML we can use.</p><pre>&lt;head&gt;<br>&lt;!-- Import font-awesome somewhere in the HTML --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css&quot; integrity=&quot;sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot; /&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./index.css&quot;&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div class=&quot;carousel&quot; data-carousel&gt;<br>    &lt;div class=&quot;carousel-buttons&quot;&gt;<br>      &lt;button<br>        class=&quot;carousel-button carousel-button_previous&quot;<br>        data-carousel-button-previous<br>      &gt;<br>        &lt;span class=&quot;fas fa-chevron-circle-left&quot;&gt;&lt;/span&gt;<br>      &lt;/button&gt;<br>      &lt;button<br>        class=&quot;carousel-button carousel-button_next&quot;<br>        data-carousel-button-next<br>      &gt;<br>        &lt;span class=&quot;fas fa-chevron-circle-right&quot;&gt;&lt;/span&gt;<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;slides&quot; data-carousel-slides-container&gt;<br>      &lt;div class=&quot;slide&quot;&gt;<br>        &lt;!-- Anything can be here. Each slide can have any content --&gt;<br>        &lt;h2&gt;Slide 1 heading&lt;/h2&gt;<br>        &lt;p&gt;Slide 1 content<br>      &lt;/div&gt;<br>      &lt;div class=&quot;slide&quot;&gt;<br>        &lt;!-- Anything can be here. Each slide can have any content --&gt;<br>        &lt;h2&gt;Slide 2 heading&lt;/h2&gt;<br>        &lt;p&gt;Slide 2 content<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;</pre><p>In the head, we are linking font awesome and also our custom styles CSS file.</p><p>In the body:</p><ul><li>we have an outer div for the entire carousel.</li><li>we have two buttons, one for “previous slide” and one for “next slide”. The buttons use font-awesome icons.</li><li>we have a div for the slides. Inside that, we have a div for each slide. The content inside each slide is irrelevant to us, it can be anything.</li></ul><p>As for the data- attributes, those are what we&#39;ll use as selectors in JavaScript.</p><p>I personally prefer using data- attributes for JavaScript because I want to separate concerns. For example, classes are standard to use for CSS. When someone tries to change the styling of the carousel in the future, they may replace the class name for a more descriptive one. They may also change some CSS modifier classes or something. I don&#39;t want them to be paranoid that if they change the CSS they may break the JavaScript, or the automated tests, or the asynchronous content insertions, or anything else. I want them to feel safe when working with the CSS.</p><p>This means, that I do not use classes to select elements with JavaScript.</p><p>An exception to this is if you use classes with a prefix such as js-. E.g. &lt;div class=&quot;js-carousel&quot;&gt;&lt;/div&gt;, which are exclusively for JavaScript use. That achieves the same result.</p><p>But my preference is to use data- attributes. That&#39;s what data-carousel and the others are for.</p><h3>CSS</h3><p>Our CSS:</p><ol><li>is going to have the basic styling for our carousel</li><li>is going to have the mechanism for changing the slides</li></ol><p>The way our carousel will work is by having all slides horizontally next to each other. However, only one slide will show at a time. That’s because every slide, except the one that’s visible, will be overflowing outside of the top-level carousel div. That div will have overflow: hidden, so nothing that&#39;s overflowing will show.</p><p>We’ll decide which slide is currently showing with the line transform: translateX(/* something */). That way, we&#39;ll translate the slides div, so that only the correct slide is visible.</p><p>Here is the CSS.</p><pre>.carousel {<br>  --current-slide: 0;<br>  /* we set position relative so absolute position works properly for the buttons */<br>  position: relative;<br>  overflow: hidden;<br>}<br><br>.carousel-button {<br>  /* vertically centering the buttons */<br>  position: absolute;<br>  top: 50%;<br>  transform: translateY(-50%);<br>  z-index: 1;<br><br>  /* basic styling */<br>  padding: 0;<br>  margin: 0.5rem;<br>  border-radius: 50%;<br>  background-color: transparent;<br>  border: none;<br><br>  font-size: 1.5rem;<br>  cursor: pointer;<br><br>  transition: color 0.1s;<br>}<br><br>.carousel-button:hover {<br>  color: rgba(0, 0, 0, 0.5);<br>}<br><br>.carousel-button_next {<br>  /* The &quot;next slide button&quot; will be at the right */<br>  right: 0;<br>}<br><br>.slides {<br>  display: flex;<br>  transition: transform 0.5s;<br>  transform: translateX(calc(-100% * var(--current-slide)));<br>}<br><br>.slide {<br>  flex: 0 0 100%;<br>}<br><br>@media screen and (min-width: 768px) {<br>  .carousel-button {<br>    font-size: 2rem;<br>    margin: 1rem;<br>  }<br>}</pre><p>With this CSS, every div has its default width of 100%. This means that the carousel will take the full width of its parent container. Every slide will also take up the full width of the carousel.</p><h4>Controls</h4><p>In the carousel-button class, we provide some simple styling for the buttons. We&#39;re using font-awesome icons, so we give them a font-size so they&#39;re large and visible. We also remove some of the default button styling (things like borders and background color).</p><p>Also, we position the buttons in the middle (vertically) of the entire carousel. We do this by using the position: absolute; top: 50%; transform: translateY(-50%); trick.</p><h4>Changing slides</h4><p>The trick for how the carousel actually changes slides is the CSS in .slides and .slide. In .slide, we make each slide have 100% of the width of the carousel. This is done with the flex property. In other words, one slide will take up the entire width of the carousel.</p><p>Since .slides is display: flex;, all of the slides will be horizontally next to each other. This means that one slide will take up the entire width of the carousel and all other slides will overflow horizontally next to it. The carousel div has overflow: hidden;, so none of the overflowing slides will show.</p><p>At some point, using JavaScript, we’ll move the .slides div to the right or left. This means that the slides will move, so a different slide will be visible inside the carousel.</p><p>The declaration transform: translateX(calc(-100% * var(--current-slide))); is our movement mechanism. Here we&#39;re saying to move the slides container -100% (the full-width of the carousel, or the full width of a slide) to the left (the negative sign means to the left), as many times as the slide index we&#39;re on.</p><p>For example, if we’re on slide index 0 (first slide), -100% * 0 = 0, so we don&#39;t translate at all and the first slide is visible.</p><p>If we’re on slide index 1 (second slide), then `-100% * 1` = -100%, so we translate 100% (one slide width) to the left. This means that we’re displaying the second slide.</p><p>We’ll set the --current-slide property using JavaScript.</p><h3>JavaScript</h3><p>Our JavaScript needs to:</p><ul><li>handle events for the two buttons (switch to previous slide and next slide)</li><li>work independently for any number of different carousels on the page</li></ul><p>Here is the JavaScript.</p><pre>function modulo(number, mod) {<br>  let result = number % mod;<br>  if (result &lt; 0) {<br>    result += mod;<br>  }<br>  return result;<br>}<br><br>function setUpCarousel(carousel) {<br>  function handleNext() {<br>    currentSlide = modulo(currentSlide + 1, numSlides);<br>    changeSlide(currentSlide);<br>  }<br><br>  function handlePrevious() {<br>    currentSlide = modulo(currentSlide - 1, numSlides);<br>    changeSlide(currentSlide);<br>  }<br><br>  function changeSlide(slideNumber) {<br>    carousel.style.setProperty(&#39;--current-slide&#39;, slideNumber);<br>  }<br><br>  // get elements<br>  const buttonPrevious = carousel.querySelector(&#39;[data-carousel-button-previous]&#39;);<br>  const buttonNext = carousel.querySelector(&#39;[data-carousel-button-next]&#39;);<br>  const slidesContainer = carousel.querySelector(&#39;[data-carousel-slides-container]&#39;);<br><br>  // carousel state we need to remember<br>  let currentSlide = 0;<br>  const numSlides = slidesContainer.children.length;<br><br>  // set up events<br>  buttonPrevious.addEventListener(&#39;click&#39;, handlePrevious);<br>  buttonNext.addEventListener(&#39;click&#39;, handleNext);<br>}<br><br>const carousels = document.querySelectorAll(&#39;[data-carousel]&#39;);<br>carousels.forEach(setUpCarousel);</pre><p>This code may be appear a bit confusing because of the nested functions. If you’re not used to this syntax, then here is a class alternative for the setUpCarousel function which does exactly the same thing.</p><pre>class Carousel {<br>  constructor(carousel) {<br>    // find elements<br>    this.carousel = carousel;<br>    this.buttonPrevious = carousel.querySelector(&#39;[data-carousel-button-previous]&#39;);<br>    this.buttonNext = carousel.querySelector(&#39;[data-carousel-button-next]&#39;);<br>    this.slidesContainer = carousel.querySelector(&#39;[data-carousel-slides-container]&#39;);<br><br>    // state<br>    this.currentSlide = 0;<br>    this.numSlides = this.slidesContainer.children.length;<br><br>    // add events<br>    this.buttonPrevious.addEventListener(&#39;click&#39;, this.handlePrevious.bind(this));<br>    this.buttonNext.addEventListener(&#39;click&#39;, this.handleNext.bind(this));<br>  }<br><br>  handleNext() {<br>    this.currentSlide = modulo(this.currentSlide + 1, this.numSlides);<br>    this.carousel.style.setProperty(&#39;--current-slide&#39;, this.currentSlide);<br>  }<br><br>  handlePrevious() {<br>    this.currentSlide = modulo(this.currentSlide - 1, this.numSlides);<br>    this.carousel.style.setProperty(&#39;--current-slide&#39;, this.currentSlide);<br>  }<br>}<br><br>const carousels = document.querySelectorAll(&#39;[data-carousel]&#39;);<br>carousels.forEach(carousel =&gt; new Carousel(carousel));</pre><p>Basically, we’re holding some state, the currentSlide and the numSlides variables. We&#39;re also holding references to some HTML elements, such as the carousel element, because we&#39;ll need them when changing slides. Finally, we add event listeners to the buttons.</p><p>When the user clicks on the “next slide” button, we run the handleNext function. The call to modulo(currentSlide, numSlides) sets currentSlide to the correct index for the next slide. So, if there are 5 slides, and we&#39;re on slide index 0, it will set currentSlide to 1. But, if we&#39;re already on slide index 4 (the fifth and final slide), then the next slide index is 0, not 5. The modulo function takes care of the wrapping back to 0 for us.</p><p>Really, we could have used the % (modulo) operator for this. The reason why we have the modulo function is because % doesn&#39;t play well with negative numbers. -1 % 5 evaluates to -1, rather than 4 (the index of the slide we would actually want). We created our own modulo function to handle that case.</p><p>Finally, we set the CSS property --current-slide to the correct number. Then, the CSS changes the visible slide by translating the slides div appropriately.</p><p>The independence of different carousels on the page happens because we use querySelector on the parent carousel element, not on the document. This means that, for example, carouselElement1.querySelector([data-carousel-button-next]), will only get the button inside that carousel element. Whereas document.querySelector(&#39;[data-carousel-button-next]&#39;) would get the first matching element it finds on the page, rather than the target carousel.</p><h3>Accessibility</h3><p>At the moment, this carousel is very unfriendly to screen reader users. You’ll need to actually use a screen reader and listen to it to hear it for yourself (or watch the accessibility section of the embedded video), but basically:</p><ul><li>it doesn’t mention anything about the content being a carousel</li><li>for the buttons, it just says “button” and nothing else (because the buttons don’t have text or a label)</li><li>on “auto read”, it reads through all of the content of every slide, as though it was a normal web page full of text (because we’re not telling it to only read the visible slide)</li></ul><p>To fix those issues, we need to go to the <a href="https://www.w3.org/TR/wai-aria-practices-1.1/">WAI-ARIA authoring practices document</a>. There is a section for carousels. We just go to it and follow the instructions. It’s actually not too difficult. It has step-by-step instructions for us.</p><p>In the end, our HTML looks like this:</p><pre>&lt;div<br>  class=&quot;carousel&quot;<br>  aria-role=&quot;group&quot;<br>  aria-roledescription=&quot;carousel&quot;<br>  aria-label=&quot;Student testimonials&quot;<br>  data-carousel<br>&gt;<br>  &lt;div class=&quot;carousel-buttons&quot;&gt;<br>    &lt;button<br>      class=&quot;carousel-button carousel-button_previous&quot;<br>      aria-label=&quot;Previous slide&quot;<br>      data-carousel-button-previous<br>    &gt;<br>      &lt;span class=&quot;fas fa-chevron-circle-left&quot;&gt;&lt;/span&gt;<br>    &lt;/button&gt;<br>    &lt;button<br>      class=&quot;carousel-button carousel-button_next&quot;<br>      aria-label=&quot;Next slide&quot;<br>      data-carousel-button-next<br>    &gt;<br>      &lt;span class=&quot;fas fa-chevron-circle-right&quot;&gt;&lt;/span&gt;<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div<br>    class=&quot;slides&quot;<br>    aria-live=&quot;polite&quot;<br>    data-carousel-slides-container<br>  &gt;<br>    &lt;div<br>      class=&quot;slide&quot;<br>      aria-role=&quot;group&quot;<br>      aria-roledescription=&quot;slide&quot;<br>      aria-hidden=&quot;false&quot;<br>      aria-labelledby=&quot;bob&quot;<br>    &gt;<br>      &lt;h2 id=&quot;bob&quot;&gt;Bob&lt;/h2&gt;<br>    &lt;/div&gt;<br><br>    &lt;div<br>      class=&quot;slide&quot;<br>      aria-role=&quot;group&quot;<br>      aria-roledescription=&quot;slide&quot;<br>      aria-hidden=&quot;true&quot;<br>      aria-labelledby=&quot;alice&quot;<br>    &gt;<br>      &lt;h2 id=&quot;alice&quot;&gt;Alice&lt;/h2&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>A quick summary of what we did is:</p><ul><li>we added an aria-role, aria-roledescription and aria-label to the carousel div. Now, the screen reader says something like &quot;Student testimonials carousel&quot;, immediately indicating that this is a carousel and what content it represents.</li><li>for each button, we added an aria-label. Now the screen reader says something like &quot;button previous slide&quot;, instead of just &quot;button&quot;. (An alternative technique here would be to add &quot;screen-reader only text&quot;. This is text that exists in the HTML but is hidden visually using particular methods.)</li><li>we added an aria-role and aria-roledescription to each slide. Now the screen reader knows when it&#39;s entering a slide or leaving a slide and it will notify the user as necessary.</li><li>we also added a label to each slide using aria-labelledby. This is the same as aria-label except that you point it to some text that already exists on the page, using an HTML ID. In this case, since our label already exists on the page (the heading for each slide), we used aria-labelledby instead of aria-label.</li><li>we added aria-hidden=&quot;true&quot; to the hidden slides. Now the screen reader won&#39;t read them.</li><li>we added an aria-live region. Now the screen reader will re-read the content of the carousel whenever there are changes (when the user changes the slide).</li></ul><p>There are some other aria attributes that would be useful, but I’m ignoring them for now because they’re not mentioned in the carousel part of the WAI-ARIA authoring practices. One example is <a href="https://tink.uk/using-the-aria-controls-attribute/">aria-controls</a>. If you want to learn more about these, it might be worth looking at the <a href="https://www.w3.org/TR/wai-aria-practices-1.1/">WAI-ARIA authoring practices</a> in your own time. If you want to learn more about accessibility in general, I’ve written a learning guide in <a href="https://programmingduck.com/articles/accessibility">Web accessibility — Everything you need to know</a>.</p><p>Our JavaScript needs some updates as well. Specifically, when we change slides, we need to change the aria-hidden property to false for the new active slide. We also need to hide the previous slide that we&#39;re no longer looking at.</p><p>Here is some example code we can use:</p><pre>function changeSlide(slideNumber) {<br>  // change current slide visually<br>  carousel.style.setProperty(&#39;--current-slide&#39;, slideNumber);<br><br>  // handle screen reader accessibility<br>  // here we&#39;re getting the elements for the previous slide, current slide and next slide<br>  const previousSlideNumber = modulo(slideNumber - 1, numSlides);<br>  const nextSlideNumber = modulo(slideNumber + 1, numSlides);<br>  const previousSlide = slidesContainer.children[previousSlideNumber];<br>  const currentSlideElement = slidesContainer.children[slideNumber];<br>  const nextSlide = slidesContainer.children[nextSlideNumber];<br><br>  // here, we&#39;re hiding the previous and next slides and unhiding the current slide<br>  previousSlide.setAttribute(&#39;aria-hidden&#39;, true);<br>  nextSlide.setAttribute(&#39;aria-hidden&#39;, true);<br>  currentSlideElement.setAttribute(&#39;aria-hidden&#39;, false);<br>}</pre><h3>Testing</h3><p>What ways are there to test something like this?</p><p>In short, I would write end-to-end tests for it. I would hesitate to write unit tests for it.</p><p>Here’s why.</p><p>An end-to-end test shows you that the entire thing works correctly.</p><p>Depending on your test framework, you could do things like:</p><ul><li>check that only a particular div (slide) is visible on the page, and the others aren&#39;t</li><li>check that the correct div (slide) is visible after pressing the next / previous slide button</li><li>check that the transition for changing slides works correctly</li></ul><p>But if you unit test, you can only check that your JavaScript works correctly.</p><p>You could do a test where you set up some HTML, then run your JavaScript and finally check that the resulting HTML is what you expect.</p><p>Or you could do something like spy on your JavaScript code, run your JavaScript and ensure your spies were called.</p><p>With the first unit test example (where you check the final HTML), the problem is that, while your tests may be passing, your carousel may not be working. For example, someone may have changed how the CSS works. They may have renamed the property --current-slide to --index or whatever else. Maybe they changed the entire CSS mechanism for changing the slides (for example, to improve performance).</p><p>In this case, your JavaScript will be executing without errors and the tests will be passing, but the carousel won’t be working.</p><p>The tests won’t provide confidence that your code works.</p><p>The only thing they’ll do is freeze your JavaScript implementation. This is the scenario where you’ve already checked the carousel yourself, manually, in the browser. You think “I can see that it’s working, let me write some unit tests for it that check that the JavaScript is doing X”. What this does, is it prevents anyone from accidentally changing the JavaScript in the future. If they do so, the tests will fail.</p><p>But, it also makes intentional changes more difficult. Now, if you want to change the implementation in the future, you need to change your CSS, JavaScript and your 10 tests. This is one of the reasons why people dislike unit tests. They make changes to the implementation more difficult (at least with unit tests like these).</p><p>So, for these reasons, I would personally recommend writing end-to-end tests instead. Now, if you really want to prevent accidental changes in the JavaScript, that’s fine. You need to do what you need to do. It’s up to you to decide if the peace of mind is worth the downsides and the time it takes to write those tests.</p><p>As for the other scenario of unit testing, where you check that your spies were called, I just don’t see a benefit to that. With those tests, you’re not even testing that your JavaScript is doing what you think. You could break the JavaScript implementation in the future and your tests would still pass, as long as you’re calling the same functions.</p><p>But, those are just my thoughts on the matter. I’m open to differences in opinion. Please leave a comment below if you think I’m missing something.</p><h3>Final notes</h3><p>So that’s it. I hope that you found this article useful.</p><p>If you want a fuller view of the code, <a href="https://github.com/Programming-Duck/carousel">here is the code repository</a>.</p><p>Please note that this is not meant to be production-ready. The code can be cleaned up more. It can probably be made more appropriate to what you need to use. Etc.</p><p>This is just a little tutorial to show you the general idea on how to make a simple carousel.</p><p>If you have any feedback, anything that was missed or could have been done better, or anything else, please leave a comment below.</p><p>Alright, thanks very much and see you next time.</p><p><em>Originally published at </em><a href="https://programmingduck.com/articles/javascript-carousel"><em>https://programmingduck.com</em></a><em> on May 27, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373b6d308617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenge — Function that only runs with no arguments (intermediate / advanced functional…]]></title>
            <link>https://sargalias.medium.com/challenge-function-that-only-runs-with-no-arguments-intermediate-advanced-functional-ad4aa621ef0b?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4aa621ef0b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 18:00:29 GMT</pubDate>
            <atom:updated>2021-05-04T10:26:34.213Z</atom:updated>
            <content:encoded><![CDATA[<h3>Challenge — Function that only runs with no arguments (intermediate / advanced functional programming)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbsKpH9cJVu2HRWh.jpg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSz-m3i66DZs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSz-m3i66DZs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSz-m3i66DZs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/31788589e98bdddd25ef93ea1fd5ed2f/href">https://medium.com/media/31788589e98bdddd25ef93ea1fd5ed2f/href</a></iframe><p>This is an intermediate / advanced functional programming challenge I had to solve in an interview. I found it very interesting and it had me thinking for a while.</p><p>If you’re interested in a brain teaser, have a go. You can also complete it using classes and methods if you prefer, but we’ll use functions in this article.</p><p>(If you don’t know a lot about functional programming and want to look at that first, then check out <a href="https://programmingduck.com/articles/functional-programming-introduction">functional programming — the ultimate beginner’s guide</a>.)</p><h3>The challenge</h3><p>There were two parts to the challenge. Part 1 and part 2. Each part increases in difficulty.</p><p>I’ve also added a small part 3.</p><h3>Challenge, part 1</h3><p>Design a function that you can keep calling in a chain as long as you keep passing in arguments. For example, foo(argument1)(argument2). During this time, it shouldn’t do anything except collect the arguments. Finally, when you call the function without an argument, it should call a real function, such as console.log, with the arguments you’ve passed in so far.</p><p>Here is a code example showing how this function should behave:</p><pre>foo(&#39;a&#39;); // nothing happens<br>foo(&#39;a&#39;)(&#39;b&#39;); // nothing happens</pre><pre>foo(); // logs an empty line (calls console.log())<br>foo(&#39;a&#39;)(); // logs &#39;a&#39; (calls console.log(&#39;a&#39;))<br>foo(&#39;a&#39;)(&#39;b&#39;)() // logs &#39;a b&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;))<br>foo(&#39;a&#39;)(&#39;b&#39;)(&#39;c&#39;)() // logs &#39;a b c&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;))&#39;</pre><pre>// optionally, the function can accept more than one argument at once<br>foo(&#39;a&#39;, &#39;b&#39;)() // same as foo(&#39;a&#39;)(&#39;b&#39;)()<br>foo(&#39;a&#39;)(&#39;b&#39;, &#39;c&#39;)() // same as foo(&#39;a&#39;)(&#39;b&#39;)(&#39;c&#39;)()COPY</pre><h3>Challenge, part 2</h3><p>Implement a function similar to question 1, but make it “stateless”?</p><p>Different function calls shouldn’t share state with each other.</p><p>For example:</p><pre>const a = foo(&#39;a&#39;);<br>const ab = a(&#39;b&#39;);<br>const abc = ab(&#39;c&#39;);</pre><pre>a(); // logs &#39;a&#39; (calls console.log(&#39;a&#39;))<br>abc(); // logs &#39;a b c&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;))<br>ab(); // logs &#39;a b&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;))</pre><p>The difference compared to part 1, is that calling a(&#39;b&#39;) shouldn’t also add the argument &#39;b&#39; to the call for a(). a() should log &#39;a&#39;, not &#39;a b&#39;.</p><h3>Challenge, part 3</h3><p>Make a function similar to the one for part 2, but the first time it’s called it must be called with a single argument. That argument should be the function it will run in the end.</p><p>Then, as normal, the function should keep accepting and collecting arguments. When it’s finally called without an argument, it should execute the function you passed in as the first argument with the arguments it has collected.</p><p>For example:</p><pre>const log = actWhenCalledWithoutArguments(console.log);<br>const a = log(&#39;a&#39;);<br>const ab = a(&#39;b&#39;);<br>const abc = ab(&#39;c&#39;);</pre><pre>log(); // logs an empty line (calls console.log())<br>a(); // logs &#39;a&#39; (calls console.log(&#39;a&#39;))<br>abc(); // logs &#39;a b c&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;))<br>ab(); // logs &#39;a b&#39; (calls console.log(&#39;a&#39;, &#39;b&#39;))</pre><h3>Hints — Part 1</h3><p>So what would your solution to these questions be? Before reading on, try solving them on your own.</p><p>If you need help, read on for some hints.</p><h3>Hint 1 — Currying</h3><p>For the first hint, notice that these functions sound a lot like currying. Curried functions also accept arguments multiple times, before finally executing the “real functionality” with all of the arguments they’ve collected. This is very similar to what you’re trying to do in this challenge.</p><p>In particular, the curry utility seems very relevant. That’s a function that takes a normal function, which isn’t curried, and turns it into a curried function. In its implementation, it has a mechanism for storing arguments and then calling a function with all of the stored arguments later.</p><p>So, you may want to start by implementing the curry utility first. Looking at its source code may be helpful for the challenges.</p><p>Feel free to try to implement it yourself.</p><p>Otherwise, here is an example implementation:</p><pre>function curry(fn, arity = fn.length) {<br>  function execute(...args) {<br>    if (args.length === arity) {<br>      return fn(...args);<br>    }<br>    function gatherMoreArgs(...moreArgs) {<br>      return execute(...args, ...moreArgs);<br>    }<br>    return gatherMoreArgs;<br>  }<br>  return execute;<br>}</pre><pre>// example usage<br>function foo(a, b, c, d) {<br>  console.log(a, b, c, d);<br>}</pre><pre>const curriedFoo = curry(foo, 3);<br>curriedFoo(&#39;a&#39;)(&#39;b&#39;, &#39;c&#39;)(&#39;d&#39;); // logs &#39;a b c d&#39; (console.logs(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;))</pre><h3>Hint 2 — More functions</h3><p>For the challenges, you don’t need to have just one top-level function. Just like the curry utility, you can have more functions. The curry utility itself is made up of 3 nested functions in total.</p><p>If you’re stuck on your solution, explore what you can do with 1 function, 2 functions or even 3 functions, nested or not.</p><h3>Hint 3 — How to gather arguments for part 1</h3><p>This hint is more spoiler-heavy. It talks about a possible implementation for part 1.</p><p>One way to gather the arguments is to have an array. Then, every time the function is called with arguments, push them to that array.</p><h3>Solution — Part 1</h3><p>Alright, if you’re ready, here’s the solution for part 1:</p><pre>const logWhenCalledWithoutArguments = (...args) =&gt; {<br>  const argsSoFar = [];</pre><pre>  const execute = (...moreArgs) =&gt; {<br>    if (moreArgs.length === 0) {<br>      console.log(...argsSoFar);<br>    } else {<br>      argsSoFar.push(...moreArgs);<br>      return execute;<br>    }<br>  }</pre><pre>  return execute(...args);<br>}</pre><p>logWhenCalledWithoutArguments is a higher order function (a function that returns another function). This is needed so that it can create a private array (argsSoFar), that exists only for that invocation of logWhenCalledWithoutArguments. That way, different calls of logWhenCalledWithoutArguments won’t share the same arguments.</p><p>Other than that, the execute function does the real work. First, it checks whether it was called without arguments. If that’s the case, then it calls console.log with all of the arguments collected so far. Otherwise, it adds the new arguments to argsSoFar. Then, it returns itself so that the user can call the function again and keep providing arguments.</p><p>At the end of logWhenCalledWithoutArguments, we immediately call the execute function and return its result. That way, we start checking and collecting arguments from the first call.</p><h3>Hint — Part 2 — Making it stateless</h3><p>This is another spoiler hint.</p><p>Part 2 of the solution can’t share state like part 1 did. With the solution for part 1, this code wouldn’t work:</p><pre>const a = logWhenCalledWithNoArguments(&#39;a&#39;);<br>const ab = a(&#39;b&#39;);<br>a(); // incorrectly logs &#39;a b&#39;<br>ab(); // correctly logs &#39;a b&#39;</pre><p>So you can’t use a shared array like in part 1.</p><p>Instead, you have to find a way to pass in the arguments across different calls using closures.</p><h3>Solution — Part 2</h3><p>Alright, if you’re ready, here’s the solution to part 2.</p><pre>const logWhenCalledWithoutArguments = (...firstArgs) =&gt; {<br>  const gatherArgs = (...args) =&gt; {<br>    const execute = (...moreArgs) =&gt; {<br>      if (moreArgs.length === 0) {<br>        return console.log(...args);<br>      }<br>      return gatherArgs(...args, ...moreArgs);<br>    }<br>    return execute;<br>  }<br>  const firstExecute = gatherArgs();<br>  return firstExecute(...firstArgs);<br>}</pre><p>This function has a lot of similarities to the solution for part 1. The main difference is that, instead of capturing arguments in an array, we use the function gatherArgs to hold the arguments.</p><p>Also, just like before, we run the execute function straight away, to check if we got an argument on the first call.</p><h3>Solution — Part 3</h3><p>For part 3, the first call must be a single argument, the function to execute at the end. Everything else is the same.</p><p>If you’re ready, here’s the solution:</p><pre>const actWhenCalledWithoutArguments = (fn) =&gt; {<br>  const gatherArgs = (...args) =&gt; {<br>    const execute = (...moreArgs) =&gt; {<br>      if (moreArgs.length === 0) {<br>        return fn(...args);<br>      }<br>      return gatherArgs(...args, ...moreArgs);<br>    }<br>    return execute;<br>  }<br>  return gatherArgs();<br>}</pre><p>The solution is very similar to the solution for part 2.</p><p>The main difference is that we don’t need to check for an argument on the first call. As a result, we don’t need to run execute straight away. All we have to do is return it.</p><p>The other difference is that we replace the call to console.log with fn (the first argument).</p><p>Other than that, everything else is the same.</p><h3>Final notes</h3><p>Anyway, that’s it for this challenge.</p><p>I hope you enjoyed it.</p><p>Let me know if you completed it, and whether you thought it was easy or difficult, in the comments. It’s not the kind of thing you have to implement at work every day.</p><p>Also, if you have any similar challenges, or if you have any tips or feedback for this one, then please leave a comment.</p><p>Alright, see you next time.</p><p><em>Originally published at </em><a href="https://programmingduck.com/articles/challenge-act-when-no-arguments"><em>https://programmingduck.com</em></a><em> on March 14, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4aa621ef0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write clean code units (functions and methods)]]></title>
            <link>https://sargalias.medium.com/how-to-write-clean-code-units-functions-and-methods-f62c386ecab3?source=rss-f8ab8bda909b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62c386ecab3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Spyros Argalias]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 18:00:13 GMT</pubDate>
            <atom:updated>2021-04-26T17:54:44.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lM5p-sjpU3saNy_b.jpg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLfEMBnUrMuU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLfEMBnUrMuU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLfEMBnUrMuU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/529210317192b9c143e36a349a3fd665/href">https://medium.com/media/529210317192b9c143e36a349a3fd665/href</a></iframe><p>Code units at the edges of your application should be small, independent and only do one thing.</p><p>This is a direct application of many established <a href="https://programmingduck.com/articles/programming-principles-introduction">programming principles</a>. This includes KISS, separation of concerns, single responsibility principle and many more.</p><p>So, to have “good code”, apply this principle where possible.</p><p>This article will show you how to apply it. It will also examine why this principle is important and how it makes your code better.</p><p>To showcase, we’ll use units at the edge of an application. They’re easier to use to illustrate this point. But, after you learn the guidelines, you can apply them to any kind of code unit.</p><p>Overall, the main point of this article can be summarized in the following example. Example 1 has a large makeRequest function, which is worse than example 2. In example 2, that function has been separated into two smaller and more specific functions.</p><p>Example 1, the bad version:</p><pre>function main() {<br>  const data = getData();<br>  makeRequest(data);<br>}<br><br>function makeRequest(data) {<br>  if (isValid(data)) {<br>    fetch(&#39;https://myfakeapi.com/&#39;, {<br>      method: &#39;POST&#39;, body: JSON.stringify(data)<br>    });<br>  } else {<br>    fetch(&#39;https://errormonitoringservice.com/&#39;, {<br>      method: &#39;POST&#39;, body: JSON.stringify(data)<br>    });<br>  }<br>}</pre><p>Example 2, the good version:</p><pre>function main() {<br>  const data = getData();<br>  if (isValid(data)) {<br>    makeRequest(data);<br>  } else {<br>    reportError(data);<br>  }<br>}<br><br>function makeRequest(data) {<br>  fetch(&#39;https://myfakeapi.com/&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)});<br>}<br>function reportError(data) {<br>  fetch(&#39;https://errormonitoringservice.com/&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)});<br>} </pre><p>Let’s examine why example 1 is worse.</p><p><strong>Note: In this article, a unit refers to a function / method / module / class. We’ll be using functions, but any of them can be used.</strong></p><h3>Small, independent units</h3><p>An “edge” unit of code is a fairly small piece of functionality that doesn’t have any dependencies. It does some fairly low-level stuff and it doesn’t call any other functions to help it. It’s at the extremities, the very edges, of your application.</p><p>It’s safe code that you call to help you do something.</p><p>When you call it, you know what it’s going to do and you know that it’s not going to break anything.</p><p>It should be like a well-tested library that you’ve imported into your project. It does something small and specific and you expect it to work 100% of the time.</p><p>To do that, these kinds of units:</p><ul><li>should be small</li><li>should only do one small, specific thing</li><li>should be independent</li><li>shouldn’t have side effects, unless the only purpose of the unit is to perform a side effect</li></ul><h3>Examples of good code units</h3><p>Here are some examples of these kinds of good units:</p><pre>function add(a, b) {<br>  return a + b;<br>}<br><br>function getProperty(object, propertyName) {<br>  return object[propertyName];<br>}<br><br>function appendElementToBody(element) {<br>  document.body.append(element);<br>}<br><br>function doubleSpeed(gameObject) {<br>  gameObject.speed = gameObject.speed * 2;<br>}<br><br>function incrementSpeedDamaged(gameObject) {<br>  gameObject.speed = gameObject.speed + 0.5;<br>}<br>function incrementSpeed(gameObject) {<br>  gameObject.speed = gameObject.speed + 1;<br>}</pre><p>Notice that these units:</p><ul><li>don’t have conditionals (if / else statements)</li><li>do very little</li><li>don’t read / write to anything except their parameters (except for appendElementToBody, because the document object is a global singleton)</li><li>only have side effects if they do nothing else</li></ul><p>In comparison, here are some units that don’t follow these guidelines:</p><pre>const valueToAdd = 5;<br>function add(x) {<br>  return valueToAdd + x;<br>}<br><br>const object = {/* has some properties here*/};<br>function getProperty(propertyName) {<br>  return object[propertyName]<br>}<br><br>function appendElementToBody(element) {<br>  if (element.id === &#39;foo&#39;) {<br>    return; // do nothing<br>  }<br>  document.body.append(element);<br>}<br><br>let shouldDouble = true;<br>function doubleSpeed(gameObject) {<br>  if (shouldDouble) {<br>    gameObject.speed *= 2;<br>  })<br>}<br><br>function incrementSpeed(gameObject, isDamaged) {<br>  if (isDamaged) {<br>    gameObject.speed += 0.5;<br>  } else {<br>    gameObject.speed += 1;<br>  }<br>}</pre><p>We’ll examine each of them in detail, including what makes them good or bad.</p><p>But first, let’s examine the advantages and disadvantages of the guidelines in general. What are the benefits that you gain from the good code examples, rather than the bad ones?</p><h3>Benefits of good code units</h3><p>If you follow the guidelines, you get the benefits of good code. Things such as:</p><ul><li>code that is easy to understand</li><li>code that works correctly, predictably, without unintended consequences</li><li>code that is easy to reuse</li><li>code that is easy to change</li><li>code that is easy to test</li></ul><p>If you use the bad versions, you get the opposite. Things such as:</p><ul><li>code that is harder to understand</li><li>code that is not predictable, can have unintended consequences, is harder to track and easier to get wrong</li><li>code that is not reusable</li><li>code that is brittle and hard to change</li><li>code that’s much harder to test</li></ul><p>Next, let’s see how the examples given affect these benefits / disadvantages.</p><h3>Examining examples of code units and their benefits</h3><p>Let’s go through each example one by one. Some will be more trivial and faster than others.</p><h4>Example: add</h4><p>The add function is trivially simple.</p><pre>function add(a, b) {<br>  return a + b;<br>}</pre><p>However, it showcases the point of good units well. This function is:</p><ul><li>extremely simple to understand</li><li>reusable every time you need it</li><li>extremely easy to test</li></ul><p>One thing you may be wondering is “so what”? Why should you have an add function when you can just add things inline when you need to?</p><p>Well, let’s just say that there are many valid reasons to have one. For example, you may need to pass it into a higher order function like map, or to use partial application.</p><p>In addition, add just showcases the principle. Instead of add you might have some real functionality which works exactly like add internally. For example, you may have a function formUserGreeting(username, userFlair), which may concatenate (add) the username and userFlair together.</p><p>Here is the bad version of the add code:</p><pre>const valueToAdd = 5;<br>function add(x) {<br>  return valueToAdd + x;<br>}</pre><p>This version is much worse.</p><p>For starters, it has a weird signature which you might not expect. If you were working in some file foo and you imported this function to use it, you probably wouldn&#39;t remember or expect it to work the way that it does. It would confuse you for a moment until you examined the function closer.</p><p>This breaks the principle of least astonishment (one of the fundamental principles). When something works differently to how you expect, it’s easy to create bugs.</p><p>This function is also more difficult to understand. You have to spend additional time to read the source code of this function before you understand how it works.</p><p>Also, it’s not reusable. It always adds 5 to the number you provide. This means that you can never reuse it unless you want to add 5.</p><p>So overall, it’s much worse.</p><p>To create the good version, make sure that the function it only accesses its local scope. It should receive everything it needs to work as an argument. It shouldn’t access anything else.</p><p>Finally, it takes no effort to have the better version, so you might as well have it.</p><h4>Example: getProperty</h4><p>Next is the getProperty example.</p><p>Here is the code for the good version:</p><pre>function getProperty(object, propertyName) {<br>  return object[propertyName];<br>}</pre><p>Here is the code for the bad version:</p><pre>const object = {/* has some properties here*/};<br>function getProperty(propertyName) {<br>  return object[propertyName]<br>}</pre><p>The benefits / disadvantages are the same as the add example.</p><p>The good version is:</p><ul><li>100% predictable</li><li>easy to understand</li><li>easy to reuse</li><li>easy to test</li></ul><p>The bad version has a signature that a developer may not expect until they look at the code. It’s also not reusable if you want to work with a different object.</p><p>To get the good version, write the function in a way where it doesn’t read anything outside of its local scope.</p><h4>Example: appendElementToDom</h4><p>Now we’re starting to examine functions that may seem more realistic. These are functions that you probably have in your codebase (or something similar to them).</p><p>Here is the good version:</p><pre>function appendElementToBody(element) {<br>  document.body.append(element);<br>}</pre><p>Here is the bad version:</p><pre>function appendElementToBody(element) {<br>  if (element.id === &#39;foo&#39;) {<br>    return; // do nothing<br>  }<br>  document.body.append(element);<br>}</pre><p>The second version of the code is concerning. It has a conditional that’s not obvious to a user of the function unless they look at its source code.</p><p>Consider, if you use a function named appendElementToBody, what would you expect it to do?</p><p>You would probably expect it to append an HTML element to the body element, 100% of the time, not just some of the time.</p><p>Also consider, when you import a library to use in a project, you expect it to do what it says on the tin. You don’t expect it to have hidden conditions where it sometimes does what you expect, other times it doesn’t do anything and other times it does something different altogether.</p><p>The problem with this code is the following scenario:</p><p>Tomorrow, you realise that have a bug in your program. It turns out that whenever a user creates a particular todo list item, it doesn’t get added to the DOM. Maybe it doesn’t get added to the database either (you may have a similar condition there).</p><p>In this situation, unless you specifically remember how the appendElementToBody works (read: you already know where the bug is), it will probably take you a few hours to find the bug.</p><p>Most likely, you’re going to trace the code from the start, from where the user clicks “submit” for the new todo. The appendElementToBody is the last function that gets run, so you might not examine it for a long time.</p><p>Now, this example is very small and trivial. It’s unlikely that you’ll run into trouble for checking if an element has an ID of foo.</p><p>But it’s not difficult to see how something like this can become a problem under different circumstances. You may have more complicated conditions. You may also have conditions in many functions all over your codebase.</p><p>Something, at some point, will cause a bug. In the meantime, there could already be bugs without anyone realising.</p><p>Anyway, that’s enough of a rant. The point is, don’t do this.</p><h4>Possible improvements</h4><p>Your unit functions should be 100% predictable and do one small thing. They shouldn’t have conditionals in them. That’s not their responsibility or where that conditional logic should be.</p><p>Most of all, they shouldn’t have implicit (unexpected and non-obvious) conditions like this.</p><p>Explicit conditionals are at least predictable. Something like this would be better:</p><pre>function appendElementToBody(element, excludedSelectors) {<br>  for (let i = 0; i &lt; excludedSelectors.length; i++) {<br>    const selector = excludedSelectors[i];<br>    if (document.querySelector(selector)) {<br>      return; // exit the function and do nothing<br>    }<br>  }<br>  document.body.append(element);<br>}</pre><p>A better option may be to change the name of the function so its functionality is obvious:</p><pre>function maybeAppendElementToBody(element, excludedSelectors) {<br>  for (let i = 0; i &lt; excludedSelectors.length; i++) {<br>    const selector = excludedSelectors[i];<br>    if (document.querySelector(selector)) {<br>      return; // exit the function and do nothing<br>    }<br>  }<br>  document.body.append(element);<br>}</pre><p>In this version, the function acts predictably. It does nothing for particular selectors, but at least you expect that.</p><p>But, for the best improvements, consider:</p><ul><li>rethinking your program design so you don’t need the condition</li><li>putting the condition in a higher-level function. “Move the logic up”, so to speak, to a more appropriate place.</li></ul><p>For example, you could have something like this:</p><pre>// Extremely simple TODO creator with very basic code<br><br>const todos = [];<br><br>function handleNewTodoSubmit(event) {<br>  event.preventDefault();<br><br>  // read the DOM to see what the user has typed as the TODO title<br>  const title = document.querySelector(&#39;#todo-input&#39;).value;<br><br>  // condition is checked here (albeit slightly altered to the original)<br>  if (!doesTodoTitleAlreadyExist(todos, title)) {<br>    const todo = createTodoObject(title);<br>    todos.push(todo);<br>    displayTodo(todo);<br>  }<br>}<br><br>function doesTodoTitleAlreadyExist(todos, title) {<br>  function hasTargetTitle(todo) {<br>    return todo.title === title;<br>  }<br>  return todos.some(hasTargetTitle); // returns true if any of a todo in the array has the same title<br>}<br><br>function createTodoObject(title) {<br>  return { title };<br>}<br><br>function displayTodo(todo) {<br>  const todoElement = createTodoElement(todo);<br>  appendElementToBody(todoElement);<br>}<br><br>function createTodoElement(todo) {<br>  const todoElement = document.createElement(&#39;div&#39;);<br>  todoElement.id = todo.title;<br>  todoElement.textContent = todo.title;<br>  return todoElement;<br>}<br><br>function appendElementToBody(element) {<br>  document.body.append(element);<br>}<br><br>const todoForm = document.querySelector(&#39;#todo-form&#39;)<br>todoForm.addEventListener(&#39;submit&#39;, handleNewTodoSubmit);</pre><p>In this example code, every function, including appendElementToBody, does what you expect 100% of the time.</p><p>The validation of the todo was moved from appendElementToBody to handleNewTodoSubmit. This is a much more appropriate place for it.</p><p>The correct way to think about it is that the todo should not be created if it already exists. That’s the domain of the handleNewTodoSubmit function, not of the appendElementToBody function.</p><p>In other words, the check is now at a place where you would expect it to be. This means that debugging will be easier if there is a problem, because you’ll find the relevant code faster.</p><h4>Example: doubleSpeed</h4><p>Code for the good version of doubleSpeed:</p><pre>function doubleSpeed(gameObject) {<br>  gameObject.speed = gameObject.speed * 2;<br>}</pre><p>Code for the bad version of doubleSpeed:</p><pre>let shouldDouble = true;<br>function doubleSpeed(gameObject) {<br>  if (shouldDouble) {<br>    const currentSpeed = gameObject.speed;<br>    gameObject.speed = currentSpeed * 2;<br>  })<br>}</pre><p>This example is the same as the appendElementToBody example.</p><p>doubleSpeed should do what it says on the tin. It shouldn&#39;t have implicit conditions where it does what you expect sometimes and nothing at other times. That&#39;s unexpected and can only lead to trouble.</p><p>Instead, some code higher up should decide if it needs to call it in the first place. Then it can either call it or not call it.</p><p>The benefits of the good version of the code are that it’s:</p><ul><li>predictable, easy to track and less likely to have weird bugs that depend on weird state and time</li><li>easy to understand</li><li>reusable. You can reuse this function anywhere in the codebase. However, you can’t reuse the bad version unless you need the exact same condition.</li><li>easy to test. The bad version is practically impossible to test (because your test file can’t modify the variable shouldDouble, unless you do a lot of work to circumvent that).</li></ul><h4>Example: incrementSpeed</h4><p>This example showcases why you should avoid having Boolean parameters.</p><p>Here is the good version of the code:</p><pre>function incrementSpeedDamaged(gameObject) {<br>  gameObject.speed = gameObject.speed + 0.5;<br>}<br>function incrementSpeed(gameObject) {<br>  gameObject.speed = gameObject.speed + 1;<br>}</pre><p>Here is the bad version of the code:</p><pre>function incrementSpeed(gameObject, isDamaged) {<br>  if (isDamaged) {<br>    gameObject.speed += 1;<br>  } else {<br>    gameObject.speed += 0.5;<br>  }<br>}</pre><p>Does the Boolean parameter matter?</p><p>Yes, it does. Not a tremendous amount in this example, but it’s definitely worse.</p><p>One problem with Boolean parameters is that they multiply the number of code paths in the function. In other words, there is an if / else statement in there.</p><p>For example:</p><pre>function (booleanParameter) {<br>  if (booleanParameter) {<br>    doSomething();<br>  } else {<br>    doSomethingElse();<br>  }<br>}</pre><p>Every additional Boolean parameter can double the number of possible code paths.</p><p>For example, with two Boolean parameters, this is what the code may look like. Pay particular attention to the sendData function:</p><pre>function sendData(data, isValid, isDataFormatted) {<br>  if (isDataValid) {<br>    if (!isDataFormatted) {<br>      data = formatData(data);<br>    }<br>    fetch(&#39;https://myfakeapi.com&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)})<br>  } else {<br>    if (!isDataFormatted) {<br>      data = formatInvalidData(data);<br>    }<br>    fetch(&#39;https://myfakeapi.com/errors&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)})<br>  }<br>}<br><br>function formatData(data) {<br>  return data.split(&#39;&#39;);<br>}<br><br>function formatInvalidData(data) {<br>  return &#39;Error: &#39; + data;<br>}<br><br>function main() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateData(data);<br>  const isDataFormatted = false;<br>  sendData(data, isDataValid, isDataFormatted);<br>}</pre><p>The sendData function is quite complicated. It&#39;s difficult to understand and read through it. It has nested conditionals, which make code harder to understand and work with.</p><p>It’s also not reusable, unless you need those exact conditions and arguments elsewhere. In particular, if you need if more conditions tomorrow, you’ll need to add even more code to sendData to handle them. This means that sendData may grow over time, and become even more complicated.</p><p>It’s also difficult to test. You need tests covering each possible code path.</p><p>In short, it’s difficult to work with and it can become even more complicated in the future.</p><p>The better version is to have simple unit functions, that only do one thing, without conditionals. For example:</p><pre>function sendData(data) {<br>  fetch(&#39;https://myfakeapi.com&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)});<br>}<br>function reportDataError(data) {<br>  fetch(&#39;https://myfakeapi.com/errors&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)});<br>}<br>function formatData(data) {<br>  return data.split(&#39;&#39;);<br>}<br>function formatIvalidData(data) {<br>  return &#39;Error: &#39; + data;<br>}<br>function main() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateData(data);<br>  if (isDataValid) {<br>    const formattedData = formatData(data);<br>    sendData(formattedData);<br>  } else {<br>    const formattedData = formatInvalidData(data);<br>    reportDataError(formattedData);<br>  }<br>}</pre><p>Notice that the sendData function is now trivially simple.</p><p>You may be thinking “but those conditions just moved to the main function, isn&#39;t that the same thing?&quot; That&#39;s a fair argument. However, this code still has some advantages. In this version:</p><ul><li>the unit functions are simple and easy to understand</li><li>the unit functions are reusable all over the codebase. If you need to handle new conditions, you can handle them in a different high-level function like main and still reuse the small unit functions.</li><li>the unit functions are trivial to test</li><li>the program in general is easier to modify or extend if you need more functionality</li></ul><p>A more important reason is how the good version of the code can grow tomorrow, versus the bad version of the code.</p><p>For example, if new conditions arise tomorrow, the good version of the code may end up like this:</p><pre>// We&#39;ve kept the unit functions like sendData, but they&#39;re omitted for brevity<br><br>// More simple functions for new use-cases<br>function validateDataADifferentWay(data) {}<br>function validateSpecialData(data) {}<br><br>function main1() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateData(data);<br>  if (isDataValid) {<br>    const formattedData = formatData(data);<br>    sendData(formattedData);<br>  } else {<br>    const formattedData = formatInvalidData(data);<br>    reportDataError(formattedData);<br>  }<br>}<br><br>function main2() {<br>  const data = &#39;123&#39;; // get data from somewhere, it should always be valid<br>  const speciallyFormattedData = formatDataADifferentWay(data);<br>  sendData(speciallyFormattedData);<br>}<br><br>function main3() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateSpecialData(data);<br>  if (isDataValid) {<br>    const formattedData = formatData(data);<br>  } else {<br>    const formattedData = formatInvalidData(data);<br>    reportDataError(formattedData);<br>  }<br>}</pre><p>This is quite good.</p><p>The unit functions we had are still 100% the same. We handle the new conditions in the different main functions which aren&#39;t too complicated. For new, specific functionality, we&#39;ve created the new unit functions validateSpecialData and formatDataADifferentWay. (We&#39;ve omitted the implementations for brevity.)</p><p>However, the bad version of the code wouldn’t fare so well. Every new condition would be handled in sendData. As a result, sendData would become much more complicated.</p><p>Consider this example where we add a Boolean parameter needsSpecialFormatting. It&#39;s a flag which says that we should format the data in a different way:</p><pre>function sendData(data, isValid, isDataFormatted, needsSpecialFormatting) {<br>  if (isValid) {<br>    if (!isDataFormatted) {<br>      if (needsSpecialFormatting) {<br>        data = formatDataADifferentWay(data);<br>      } else {<br>        data = formatData(data);<br>      }<br>    }<br>    fetch(&#39;https://myfakeapi.com&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)})<br>  } else {<br>    if (!isDataFormatted) {<br>      if (needsSpecialFormatting) {<br>        formattedData = formatDataADifferentWay(data);<br>      } else {<br>        formattedData = formatInvalidData(data);<br>      }<br>    }<br>    fetch(&#39;https://myfakeapi.com/errors&#39;, {method: &#39;POST&#39;, body: JSON.stringify(data)})<br>  }<br>}<br><br>function main1() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateData(data);<br>  const isDataFormatted = false;<br>  sendData(data, isDataValid, isDataFormatted, false);<br>}<br><br>function main2() {<br>  const data = &#39;123&#39;; // get data from somewhere, it will always be valid<br>  const speciallyFormattedData = formatDataADifferentWay(data);<br>  sendData(data, true, false, true);<br>}<br><br>function main3() {<br>  const data = &#39;123&#39;; // get data from somewhere<br>  const isDataValid = validateSpecialData(data);<br>  if (isDataValid) {<br>    sendData(data, true, false, false);<br>  } else {<br>    sendData(data, false, false, false);<br>  }<br>}</pre><p>As you can see, with one more Boolean parameter, sendData is becoming much more complicated. Things would become even worse as more parameters are added.</p><p>On top of that, even the call for sendData(data, true, false, false) is difficult to look at. It&#39;s a mental exercise trying to match each Boolean to the parameter it represents. It&#39;s possible to improve this by making sendData accept an object instead, but it&#39;s still more effort than the simple version.</p><p>In addition, what sendData does may be unexpected at first glance by a programmer who&#39;s not familiar with the code. As mentioned earlier, a programmer would expect that function to send some data and call it a day, not to do anything else. After all, the function&#39;s name is sendData, not send_data_if_valid_otherwise_report_error_and_also_format_the_data_if_needed (used underscore case to make it easier to read).</p><p>Finally, this function is breaking many of the programming principles, because:</p><ul><li>it does many things, which breaks separation of concerns / single responsibility principle</li><li>it’s not simple, which breaks KISS</li><li>it has many conditions with logic coupled together, which makes it more error prone to change. This breaks the goal of programming principles themselves, which is that code should be easy to work with.</li><li>it’s not reusable for different conditions unless you add even more logic. This breaks the open-closed principle.</li></ul><p>So instead, prefer small unit functions that only do one thing. If you have to pass a Boolean to a function, consider splitting it into two functions instead. One will handle the true case and the other will handle the false case.</p><h3>Linking back to programming principles</h3><p>The main thing to keep in mind is that these guidelines are just applications of the core programming principles. That includes KISS, the principle of least astonishment, separation of concerns / single responsibility principle and handling side effects well.</p><p>All of those principles point towards functions that tend to be small, only do one thing, are reusable, easy to understand, easy to change and easy to test.</p><p>Additionally, someone who understands those principles well would naturally create code units like the ones described in this article.</p><p>So the point of this article isn’t necessarily to be prescriptive about how to create small units. Instead, think of it as an example for how to apply those principles in this situation.</p><p>In other words, it’s a specific use-case to help you become more familiar with these principles in general. That way, you can apply them everywhere, without having to learn how to handle an infinite number of individual use-cases like this one.</p><p>So, to write even better code, I recommend looking at the programming principles more closely. To do that, you can have a look at <a href="https://programmingduck.com/articles/programming-principles-introduction">clean code and programming principles — the ultimate beginner’s guide</a>, which is a crash course on some fundamental programming principles.</p><h3>Applying these guidelines to other code units</h3><p>We examined functions at the edge of an application because those can afford to be simple. Other functions may be more complicated.</p><p>As shown in the examples, higher-level functions can have conditionals and they can be longer.</p><p>As nice as it would be to avoid conditionals altogether, that’s just not possible.</p><p>Every real program needs to do different stuff under different circumstances. The very best case is to format your conditionals differently and to put them in a more appropriate place, so that they’re easy to work with.</p><p>Also, it’s not possible for all of your functions to truly only do one small thing. The only functions with that luxury tend to be the functions at the very edge of your application. For everything else, it’s more likely that they’ll do a few things, say, 3 things, at an appropriate level of abstraction, in a way that it can be described as one thing.</p><p>For example:</p><pre>function handleFormSubmit(event) {<br>  event.preventDefault(); // necessary to handle form submission with JavaScript, rather than HTML<br>  const data = getDataFromForm();<br>  const formattedData = formatData(data);<br>  sendData(formattedData);<br>}</pre><p>The handleFormSubmit function does 4 things. It has 4 lines of code after all. However, you can also think of it as doing one thing. &quot;It handles the form submission&quot;, that&#39;s one thing. Both are correct, it depends on what level of abstraction you consider.</p><p>So, since you can’t just avoid conditionals and since your functions can’t just do one thing, what can you do? All you can do is apply programming principles. A.k.a. do anything you can to ensure that your code is correct and easy to change.</p><p>At any given time, consider if your code is:</p><h3>Be pragmatic</h3><p>As always, remember to be pragmatic. In this article, we examined how to write and structure good code units at the edge of your application.</p><p>That’s the ideal, but the ideal might not always be realistic. If you can write code units like this without much effort, then do it. But if that’s not possible, well, don’t postpone a critical feature by 1 month because you want to refactor every code unit in your codebase. That wouldn’t make sense or be realistic.</p><p>Instead, do the best you can and be pragmatic. You probably need to balance good code (which makes future development easier) and releasing features in an appropriate timeframe for your work.</p><h3>Final notes</h3><p>That’s it for this article.</p><p>I hope you found it useful and I hope that the concepts and the reasons for them made sense.</p><p>What are your opinions on how code units should be, particularly units at the “edge” of your application? Is there anything you disagree with? Anything that wasn’t covered? If there is anything, please leave a comment below.</p><p>Otherwise, for more details on how to write clean code and apply programming principles, please check out <a href="https://programmingduck.com/articles/programming-principles-introduction">clean code and programming principles — the ultimate beginner’s guide</a>.</p><p><em>Originally published at </em><a href="https://programmingduck.com/articles/edge-code-units"><em>https://programmingduck.com</em></a><em> on March 12, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62c386ecab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>