Skip to main content

Simple code: Readability

Readability, understandability, two key incredients of great code. Easier said than done, right?

What one person finds easy to read and understand another one finds incomprehensible. This is especially true when programmers have different levels of understanding on various subjects e.g. object oriented vs. functional or Node.js vs. Java. Even though there are obvious differences between paradigms and programming ecosystems there are some common conventions and ways to lower the barrier.

Different approaches

It's natural that in programming things happen sequentally e.g. you can have a list of objects and you need to do various things to the list like filter some values out and count a sum of the remaining objects based on some property.

With the given list

const stories = [
  {name: "authentication", points: 43},
  {name: "profile page", points: 11},
  {name: "shopping cart", points: 24},
  {name: "shopping history", points: 15},
  {name: "landing page", points: 7}
]


One way to do that would something like this via for loop.

let sum = 0
for (let x of stories) {
  if (x.points > 12) {
    sum += x.points
  }
}
return sum


Another way to do it would via filter, map and reduce.

return stories.filter(x => x.points > 12).map(x => x.points).reduce((a, b) => a + b))

Now depending on the readers background they might both be understandable or just one of them could be.

When thinking of readability we can improve on those. We have JavaScript, so lets use the tools it provides, it's conventions and take the second approach as our base but try to make it easier to read and understand.

const interestingStories = stories.filter(story => story.points > 12)
const storyPoints = interestingStories.map(story => story.points)
const storyPointsSum = storyPoints.reduce((acc, points) => acc + points)
return storyPointsSum


What I did there was that I extracted each step to it's own variable with a meaningful name and within the lambdas of each operation I also renamed the variables to have meaningful names. To make better use of the language's features I'd still write this a bit differently, something along these lines.

return stories
  .map(story => story.points)
  .filter(point => point > 12)
  .reduce((accumulator, currentStoryPoints) => accumulator + currentStoryPoints)


With this approach I can minimize the number of variables by still keeping the code readable and understandable by using meaningful names within the lambdas so that the context stays in the short term memory of the reader.

Readability conventions

First convention, standard API

Take advantage of the languages basic functionality i.e. it's standard API. It should be a prequisite to work with a language to have some understanding of the standard API and to know where to find it's documentation when in doubt.

Second convention, naming

Second convention is naming. Name things meaningfully. It's way easier to read code that has good variable and function naming than a poorly named (See the post about naming).

Third convention, empty lines

Third convention to readability is to keep in mind the separation of things by adding empty lines between things.

Add empty lines between things to improve readablity. When I have a variable assignment that spreads to multiple lines I add a empty line after that assignment, it helps me to read the code.

val currentTime = LocalDateTime.now()
val currentTimeInNewYork = someAmazinglyTrulyReallyLongFunctionName(currentTime)
  .format(dateTimeFormatter.ofPattern(myTimeFormat))

val identifier = UUID.randomUUID()


I usually also add a empty line before the return clause just so that it's easier  to distinquish from the rest of the code.

Another place where I've started adding empty lines to during the past year or two is around logging calls. Why? I think that logging is something special, a special side effect. Whenever something is logged it should be done for a good reason and because it's special it should pop out from the rest of the code.

Ordering of things

I prefer to order things in a module/class/object by their visibility, first publicly visible functions/methods/variables and things with private visibilty after those because I find it easier when the public functions are the first thing when I open the file.

Some have other opinions on what the order things should be and each language has it's own conventions but the keys here are to group related things together and be consistent.

Summary

Readability of the code makes a big difference whether the code is understandable, simple and maintainable.

The next post will be the final post of the seriers where I'll be wrapping it all together.

Popular posts from this blog

Simple code: Naming things

There are two hard things in programming and naming is one them. If you don't believe me ask Martin Fowler https://www.martinfowler.com/bliki/TwoHardThings.html . In this post I'll be covering some general conventions for naming things to improve readability and understandabilty of the code. There are lots of things that need a name in programming. Starting from higher abstractions to lower we need to name a project, API or library, we probably need to name the source code repository, when we get to the code we need to name our modules or packages, we give names to classes, objects, interfaces and in those we name our functions or methods and within those we name our variables. Overall a lot of things to name. TLDR; Basic rule There's a single basic convention to follow to achiveve better, more descriptive naming of things. Give it a meaningful name i.e. don't use shorthands like gen or single letter variables like a, x, z instead tell what it represents, what it does...

Simple code: Integration tests

Integration test is something that tests a functionality that is dependant on a external system e.g. a database, HTTP API or message queue. Integration vs unit tests The line is thin in my opinion. The integration part can be faked or a embedded services can be used in place of the actual integration point and with these solutions the interaction with the external system is bounded in the test context and the tests can be executed in isolation so they are very much like unit tests. The only difference with this type of integration test and unit test is that the startup time of the embedded or faked system usually takes some seconds and that adds total execution time of the tests. Even though the total test exection time is longer all the tests need to pass and all the cases need to be covered whether there's external systems involved or not so the importance is equal between the test types. This is why I wouldn't separate unit and integration tests from each other within the co...

Simple code: Simplicity

Simplest solutions are usually the best solutions. We as software developers work with hard problems and solve a lot of small problems every day. Solving a hard problem itself is a hard job. Though in my opinion it's not enough to solve a hard problem in any possible way but a hard problem should be solved with a simple solution. When a developer comes up with a simple solution to a hard problem then they can declare the problem solved. First a disclaimer. Coming up with a simple solution to a hard problems is itself a very hard problem and takes a lot of time, effort and practice. I've seen my share of "clever" solutions for hard problems and the problem with those is that usually the solution itself is so hard to understand that depending on the size of the problem it may take a developer from hours to days or even weeks to understand how that "clever" solution works. It's a rare occasion when a developer has come up with a simple solution to a hard pr...