How to Write Self-Documenting Code

Only one way to do it!

Kislay Verma
Geek Culture

--

What is self-documenting code?

I love documenting code and systems. Many don’t. A major argument against documents is that they get outdated as the system evolves. And the faster a system evolves, the faster its documentation gets outdated. Ironically, this is the very type of system which needs the most up-to-date documentation!

An argument is often made, therefore, for self-documenting code. This is ostensibly the kind of code that doesn’t need separate documentation because it is designed and implemented in such a way as to be self-explanatory to the reader.

How does anyone reading a codebase understand it? First, they need to know what the code is “supposed to do”. Then they can graduate to figuring out how it does that. And this is where the problem of self-documenting code lies. Because reading code is essentially reading the how. “Query some things from a database table and process them into a map, match them against some other things from some other table, and return everything that does not match as a list”. Well-written code makes it simple to understand how it is doing something. But it doesn’t tell the reader why it is doing what it is doing. And hence the reader remains confused and documentation becomes necessary to understand the intent behind the system design.

So what kind of code would reveal, even in some limited way, why it does things the way it does them?

--

--