A better way to do code documentation

Jit Chan
3 min readNov 8, 2021

There are several common ways people do code documentation, some people may use word documents, some others may add tones of remarks or commands at the beginning of the code, and lastly to using third-party tools. However most of the time we forgot about who are our target audience, and most of the time we are doing it due to some prior action. Most likely we doing documentation is because other programmers able to continue the project even some of us are absent. So let’s have a look at one of the document examples below:

The code itself is looking perfectly fine, there does not have any syntax error in the code. However, the logic explained in the remark part is not aligned with the code itself. This is commonly found in code, and most of the time it is due to programmers rarely maintaining texts that are not affecting the program. Most of the time these remarks will remain as it is till the day the whole file be removed. So how should we document it in a way, where the programmer had to modify it when code is updating.

One of the better options will be developers are mandatory to write a unit test to cover and explain the function. Which will be the example below:

The benefits of doing documentation in this way can ensure the written test will be easy to align with the description text stated above. It also will easily sport out any misalignment between the actual result and the title above, forcing the developer to update the description when any changes in the code. At the same time, it increases the reliability of the description text and validates the code constantly before any releases.

The is another option to reduce the dependency on remarks, that is using type restriction on the code and applying a better naming convention on the function. For example, if you are a javascript developer, you should master the latest ES coding syntax and apply typescript in your program.

Like the example above it give a clear message. What is the function about, what parameter it accepts, and what value will be returning, when you consume the function.

In the end, I personally think that if we practice clean code, master the language syntax, and write unit tests you are already doing the documentation for internal use. But there always has an exception, if your library will be used in the public or larger groups. A documentation file stills needed to speed up the learning process but the function that needs to document should be the public function only.

--

--

Jit Chan

A Chinese Malaysian programmer, who try to practice writing :)