loading...

Code Indirection

stereobooster profile image stereobooster Originally published at stereobooster.com on ・2 min read

Code indirection

Code readability

Readability is the ease with which a reader can understand a written text.

-- Wikipedia

Readability is what makes some texts easier to read than others.

-- The Principles of Readability

Many factors play into the readability of text. For example, contrast, font, choice of words and many more. (See: readability for natural languages)

Some factors are subjective e.g. depends on the reader - if the reader knows given programming language, if the reader knows the context if the reader familiar with the jargon, etc. There is a great talk on the subject: Laura Savino - Talk Session: Readable Code. She says that "readability needs a reader".

Some factors are objective e.g. doesn't depend on the reader - length of the text, indirection in code, etc.

Code indirection

In this post, I want to talk about one specific readability metric - code indirection. At some point of reading code, you will find yourself asking the question: "where does this variable (or function) come from?". Then you can go to definition of the variable (Cmd/Ctrl-click) and trace variable to the origin. For example:

import a from "./a.ts";

const b = a();

function c() {
  b;
}
  • from b; to const b = a();
  • from const b = a(); to import a from "./a.ts";
  • from import a from "./a.ts" to file a.ts
  • etc.

In the given example you can easily "trip" from start to end. But there are cases when the trip is not so trivial, for example:

let b = a();

// ...

b;

Cmd/Ctrl-click on b will bring you to let b = a();, but you can't be sure this is the actual value of b, because let allows reassignment, so you need to use search of "b" (which could match more than the desired variable) to find first previous occurrence of b.

Or the second example:

function c(b) {
  b;
}

to find a source of b you will need to find where c is called and where it gets arguments.

The more code indirections you have the harder it is navigating through the code base, the less readable code.

Direct code:

e ← d ← c ← b ← a

Indirect code:

e → d ← c ← b ← a

PS

More about readability:

Posted on by:

stereobooster profile

stereobooster

@stereobooster

Hello, I'm a full stack web developer. Follow me on Twitter!

Discussion

pic
Editor guide