😎 Self-documenting Code⚓︎
About the topic⚓︎
Let's look at the code case shown below:
Of course, it is hard to read and understand the code above. Let's see the self-documenting
version of the last code block:
Self-documenting version
Now, you can feel that self-documenting
is a good code-writing habit for code understanding and development, even if we do not have comments. But! If your self-documenting is too complex, the variable name itself will cause code smell, which affects the readability of codes. So why not also add comments!
Self-documenting + Comment version
But do not add comments on each line:
Bad Comment example
If your team requires zero comments
coding style, transfer your code block with comments into function closure
:
Self-documenting + Function closure version
Self-documenting in Swift⚓︎
Let's see how to do self-documenting in Swift
:
Question
Notice!
Swift restricts the parameter name
before each argument input when we implement the function, i.e., you are not encouraged to run greet("Bill", "Cupertino")
unless you use _
(Omitting Argument Labels) before parameter name
in the function signature
. This semantic diminishes ambiguities when compiler compiling.
In Swift, each function parameter has both a parameter name
and an argument label
.
-
The
parameter name
is used in the implementation of the function (infunction signature
). -
The
argument label
is used when calling the function; each argument is written in the function call with its argument label before it (incall site
).
So we do self-documenting firstly based on refining parameter name
.
Self-documenting in Swift
You can observe that when implementing the function, greet(person: "Will", hometown: "Portland")
still reads not like natural language. Let's add argument label
!
Self-documenting in Swift + Argument label
Thanks, the person who always visits us from Portland!
References:⚓︎
Created: November 16, 2022 07:42:13