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...

Sharing to help myself

It's been a while since my last post but I have a good excuse. I've been in a new customer project (well new for me) for two months now and have absorbed a lot of new information on the technology stack and the project itself. This time I'll be sharing a short post about sharing code and how it can help the one who's sharing the code. I'll be giving a real life example of how it happened to me. My story Back when I was implementing first version of my simple-todo REST-service I used Scala and Play framework for the service and specs2 for testing the implementation. Since then I've done a few other implementations of the service but I've continued to use specs2 as a testing framework. I wrote about my implementation and shared the post through various services and as a result someone forked my work and gave me some pointers on how I could improve my tests. That someone was Eric Torreborre  the man behind specs2 framework. I didn't take his ref...

Simple code: Immutability

Immutability is a special thing that in my mind deserves a short explanation and praise. If you're familiar with functional programming you surely recognice the concept of immutability because it's a key ingredient of the paradigm. In the world of object oriented programming it's not as used and as easy to use approach but there are ways to incorporate immutability to parts of the code and I strongly suggest you to do so. Quick intro to immutablity The basic idea of immutability is unchangeable data.  Lets take a example. We have a need to modify a object's property but because the object is immutable we can't just change value but instead we make a copy of the object and while making the copy we provide the new value for the copy. In code it looks something like this. val pencil = Product(name = "Pencil", category = "Office supply") val blackMarker = pencil.copy(name = "Black marker") The same idea can be applied in functions and metho...