Original link:https://www.zlovezl.cn/articles/if-programming-is-writing/
Many people compare programming to writing. For example, Bruce Eckel, the author of “Thinking in Java”, said: “A programmer is a writer.” There are indeed many similarities between the two. Good articles and good code are both inexact structures. with beautiful expression. When writing, everyone can use words to make sentences and form articles, but not everyone can write good articles, and the same is true of programming.
Strictly speaking, though, programming and writing, while somewhat similar, are still two very different skills, very different in many ways. For example, we rarely rewrite a published article, but refactoring a piece of code to work is commonplace.
But this time, let’s put aside the complex concepts of programming and have a whimsical thought: “If programming is writing, what can we learn from it?”
1. Use personal pronouns
When writing articles, we often use personal pronouns to refer to the names of characters to reduce redundancy and improve the fluency of the text. This technique can of course also be used in programming.
The following code reuses a verbose expression:
def run_server(): if check(data.servier_config.host): start_server(data.servier_config.host) else: logger.error('Server %s is invalid.', data.servier_config.host)
Define a temporary variable, used as a pronoun to simplify the code:
def run_server(): host = data.servier_config.host if check(host): start_server(host) else: logger.error('Server %s is invalid.', host)
2. Use long and short sentences together
When writing, how to choose the length of sentences is a matter of knowledge. Wang Zengqi said: “The mystery of language, to put it bluntly, is just the combination of long sentences and short sentences.” Long sentences have a lot of information, but too many long sentences will increase the reader’s reading burden. Short sentences have a strong sense of rhythm, but an article full of short sentences will also give people a sense of triviality.
Generally speaking, short sentences are the main, and long sentences are the supplementary style, which is a more readable style.
For code, the amount of information in each line of statement also varies depending on the length of the expression. When writing code, we shouldn’t “rush” too many function calls, literals, and operators into the same line of statements. Don’t be too “sloppy”, dividing the logic into too many short sentence fragments.
The following is a code that is too “long sentence”:
results = [ task.result if task.result_version == VERSION_2 else get_legacy_result(task) for tasks_group in tasks for task in in tasks_group if task.is_active() and task.has_completed() ]
Disassembled into short sentences, the code will be more readable:
results = [] for tasks_group in tasks: for task in tasks_group: if not (task.is_active() and task.has_completed()): continue if task.result_version == VERSION_2: result = task.result else: result = get_legacy_result(task) results.append(result)
On this basis, you can also try to fill in long sentences appropriately, and the rhythm of the code will change accordingly:
results = [] task_objs = (t for t in group for group in tasks) for task in task_objs: if not (task.is_active() and task.has_completed()): continue item = task.result if task.result_version == VERSION_2 else get_legacy_result(task) results.append(item)
3. Large and small paragraphs
Similar to sentences, paragraphs also have lengths. Unless we are doing serious literary work, we should never use too many long paragraphs in a row in an essay. The same as the principle of clauses, it is easier to read the style of small paragraphs and large paragraphs.
When writing code, we can appropriately use blank lines to segment long and long code, and use paragraphs to distinguish different stages of code logic to create a sense of rhythm. In addition to creating literal “paragraphs”, breaking long code into small functions can also work well.
4. Unified narrative angle
No matter what story is written, a proper narrative angle is essential. For example, in a detective novel, choosing to tell the story from the perspective of a criminal or a detective has a completely different effect. Generally speaking, within a complete novel chapter, mature authors will only use one narrative angle and will not switch at will.
It would be weird to read if the narrative angles were switched. Take the following text for example:
Xiao R sat on the sofa in the living room with his laptop in his arms, and opened the latest episode of “One Piece”, “Is this Luffy the Pirate King in the end?” He looked at it and said to himself. Little C walked out of the room with a yellow rubber duckling in his hand, “It’s so boring, who can I find to play with me?” She thought to herself.
In this passage, the author first describes his psychological activities from the perspective of small R, and then suddenly replaces it with small C. This switch can easily make readers feel confused and unnatural.
If it corresponds to programming, the switch of narrative perspective is very similar to the change of code responsibility. In order to make the code read more smoothly, it is best for a function to have only one responsibility, and its code needs to be maintained at the same level of abstraction.
For example, try reading the following code:
def render(request, app_id): """视图函数:停止应用""" app = App.objects.get(pk=app_id) stop_app_services(app.id) app.operator = request.user app.status = AppStatus.STOPPED app.save() # 拼装渲染页面所需参数storages = Storage.objects.filter_by_app(app) status = get_app_status(app) return render("app.html", {"app": app, "storages": storages, "status": status})
In the render
function, we first get the application object according to the app_id
parameter, then perform a series of operations to stop it, and finally complete the page rendering.
If you do a simple analysis, you will find that the first half of the function belongs to the model layer (operation application stops), and the second half belongs to the view layer (preparing parameters to complete rendering). When reading render()
, we don’t actually want to know too many details about “how the application stops” (it can be likened to the mental activity of a fictional character). Mixing up code like it does now seriously hurts the reader’s reading experience.
In order to improve the experience, we can encapsulate the first half of the code into a method stop
belonging to the App
model:
def render(request, app_id): """视图函数:停止应用""" app = App.objects.get(pk=app_id) app.stop(oprator=request.user) # 拼装渲染页面所需参数storages = Storage.objects.filter_by_app(app) status = get_app_status(app) return render("app.html", {"app": app, "storages": storages, "status": status})
After doing this, the narrative angle within the function is unified. When reading the code, the reader can be immersed in the “view rendering” narrative angle, without having to shuttle between different angles.
5. Know the rules, break the rules
Writing is an extremely free creative activity. You’ll find that while textbooks are packed with “how to write” rules, many of the works that people are familiar with continue to break those rules.
For example, the rules tell us: “paragraphs should be short rather than long”. But when I read “Lights of August”, I found some paragraphs as long as a page. For another example, the primary school Chinese teacher taught us: “Conversations should use quotation marks, preferably independent paragraphs”. But in the novel “Winter Swimming” by Shenyang writer Ban Yu, the characters’ dialogues are described throughout the text as follows:
Sui Fei said, “It’s good, and it’s easy. I said, according to the introducer, you work in the hospital. Sui Fei said that she used to be a nurse in a chemical factory hospital, but now she is not in a good condition. She has taken a long vacation and has not worked for half a year. I said, okay, take a good rest.
When an author chooses to break a rule, it usually has a clear purpose. For example, make the text more stylized, provide some kind of novel reading experience, etc., and hope to achieve a surprising effect.
Like writing, there are a lot of principles in the field of programming. For example, “Don’t Repeat Yourself (Don’t Repeat Yourself)” says: A knowledge can only have one manifestation in a project, so repeated functions and codes are not desirable. The “Law of Demeter” tells us that object methods can only access members directly related to them, so obj.Method()
can, but obj.b.Method()
violates the principle.
These various principles are the crystallization of the experience and wisdom of many predecessors. We should first understand them as much as possible and try to apply them in our own projects. But after that, it’s more important to know when to break the rules.
Programming is not equal to artistic creation, and people are not encouraged to pursue the ultimate limitlessly. Writers can spend years polishing a masterpiece, but programmers have a problem with code. Although code is created by individuals, programming is a collaborative engineering affair involving many people. Many times, as programmers, we need to weigh the pros and cons and selectively break certain principles in order to deliver a satisfactory answer to all parties within a limited time.
Epilogue
Although programming is very similar to writing, and even part of the job of programming (such as writing comments, writing documentation) is writing, there are many essential differences between the two activities. This article tries to find the similarities between the two from some angles, and summarizes some experiences. But regardless of programming or writing, the author belongs to the level of “sloshing half a bucket of water”, and many opinions may not be professional, I still hope Haihan.
But one thing I can be sure of is: whether programming or writing, only “writing” is the only way to improve your ability. Reading 100 writing tutorials and flipping through the code of 1000 open source projects will not make us masters. So what are you waiting for? Close the article and start writing now!
This article is reprinted from:https://www.zlovezl.cn/articles/if-programming-is-writing/
This site is for inclusion only, and the copyright belongs to the original author.