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.

Comments

Popular posts from this blog

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

Simple code: Unit tests

Unit tests are the developers number one safety net. Let that sink in. This is the number one reason for writing unit tests. Unit tests are written by developers for developers to ensure that the code works as expected and handles happy and sad paths correctly. With enough unit test coverage the tests enable a safe environment for refactoring and rewriting code. Unit test scope Unit test should test a single thing, a method or function call and it should test only one use case within. In other words a unit test should test a function with a single input. This is a important guideline to understand. When a unit test tests a function with single input it makes the test isolated, repeatable and predictable. Example of good tests: @Test fun findsAddress() {   val address = findAddress("Stevens street 35", "Southport", "Australia")   assertThat(address).isNotNull() } @Test fun doesNotFindAddress() {   val address = findAddress("Stevens street 697", &q