1. 程式人生 > 實用技巧 >dll簡潔易懂_如何保持您的程式碼簡潔易懂

dll簡潔易懂_如何保持您的程式碼簡潔易懂

dll簡潔易懂

Being able to write clean code is crucial to becoming a better software developer. Not only will this practice make your life easier, but it will help others who are accessing your code and work to grow your reputation as a developer who is known for being thorough. This article is a high-level run-through of different tips and techniques that you can use to write clean and understandable code in a project; helping you to maintain code for a longer period of time without any hassle.

能夠編寫乾淨的程式碼對於成為更好的軟體開發人員至關重要。 這種做法不僅會使您的生活變得更輕鬆,而且還將幫助其他正在訪問您程式碼的人,並努力提高您作為以全面而聞名的開發人員的聲譽。 本文是不同技巧和技術的高階概括,可用於在專案中編寫簡潔易懂的程式碼。 幫助您更長久地維護程式碼,而不會遇到麻煩。

什麼是乾淨程式碼? (What is clean code?)

To understand clean code we first need to have an idea of what bad code is — then we can identify problems and solutions to achieve clean code from there.

為了理解乾淨的程式碼,我們首先需要了解什麼是壞程式碼-然後我們可以識別問題和解決方案以從那裡實現乾淨的程式碼。

There is a famous analogy about defining bad code that is first narrated by Thomas Holwerda, later in Robert C Martin’s book, in which the measurement of code quality in WTFs/minute!

托馬斯·霍爾維達( Thomas Holwerda )首先敘述了一個有關定義錯誤程式碼的著名類比,後來在羅伯特·馬丁

( Robert C Martin )的書中談到,用WTF /分鐘來衡量程式碼質量

Image for post
The original image can be found here .
原始影象可以在 這裡 找到

Suppose we wrote a piece of code and some other teammates are reading or reviewing the code. If they immediately understand what the code is meant to do, that’s good code. But sometimes we ourselves can’t even understand something that we wrote a few months ago because we ignored understandability practices and wrote bad codes!

假設我們編寫了一段程式碼,而其他一些隊友正在閱讀或檢視該程式碼。 如果他們立即瞭解該程式碼的用途,那就是好程式碼。 但是有時我們自己甚至無法理解幾個月前寫的東西,因為我們忽略了可理解性實踐並編寫了錯誤的程式碼!

有意義的名字 (Meaningful Names)

Sometimes we developers say that naming something is the toughest job while writing code, yes indeed! A variable, function, or a class should be self-explanatory to the person who is reading the code, which makes naming very important.

有時,我們的開發人員會說在編寫程式碼時給某事命名是最困難的工作,的確如此! 變數,函式或類對於正在閱讀程式碼的人員來說應該是不言自明的,這使得命名非常重要。

Look at this sample code:

看下面的示例程式碼:

Image for post

Here, we can see two variables list1 and list2 but from the names, we are not getting what the values are or the types of these variables. Here comes the first tip (i.e. using intention-revealing names which also helps developers to stop the spread of disinformation). Please also note that the arrow function inside the filter has the argument named item. This is not very clear as we can’t say what kind of thing this item is!

在這裡,我們可以看到兩個變數list1list2但是從名稱來看,我們沒有得到這些變數的值或型別。 這是第一個技巧(即使用意圖揭示名稱,這也有助於開發人員阻止虛假資訊的傳播)。 另請注意,過濾器中的arrow函式具有名為item的引數。 這不是很清楚,因為我們不能說這是什麼東西!

Let’s refactor it and see how we can make improve here:

讓我們對其進行重構,看看如何在此處進行改進:

Image for post

The distinction between function names based on what they do is very important. Suppose we have a function that returns all the users, but now we need the other two functions which will return a specific user by id as well as a list of users who are admins.

基於函式名稱之間的區別非常重要。 假設我們有一個返回所有使用者的函式,但是現在我們需要另外兩個函式,這些函式將按ID返回特定的使用者以及admin使用者列表。

I have seen so many codebases where I found function names like this:

我看到了很多程式碼庫,在其中找到了這樣的函式名:

Image for post

It’s not until you read what is inside the function that you can say what this function intends to do. This type of function names creates ambiguity and also keeps other developers in a dark zone where they don’t know about the existing functions and end up creating a new one which does the same thing as getUsers2.

直到您閱讀了函式內部的內容後,您才能說出該函式打算做什麼。 這種型別的函式名稱會造成歧義,並使其他開發人員無法瞭解現有功能,因而陷入了一個黑暗的地帶,最終建立了一個與getUsers2相同功能的新開發人員。

Let’s refactor this.

讓我們重構一下。

Image for post

You can see in all of the function names we have added the action i.e. get as a prefix. Using verbs as a prefix of the function name is a convention that we should follow because it says what action the function does.

您可以在所有添加了操作的函式名稱中看到,例如,獲取作為字首。 使用動詞作為函式名稱的字首是我們應該遵循的約定,因為它說明了函式將執行的操作。

There are times when super-coders form a team and use super acronyms in every other thing that they write. When we go through their code we can see some short names and sometimes we can’t even pronounce the names they have written down.

有時,超級編碼者組成一個團隊,並在他們編寫的所有其他東西中使用超級縮寫。 當我們瀏覽他們的程式碼時,我們可以看到一些短名稱,有時我們甚至無法念出他們寫下的名稱。

Let’s look into this piece of beautifully created but incomprehensible code:

讓我們看一下這段建立精美但難以理解的程式碼:

Image for post

Here, we have a class named Box (always remember that a class name cannot be a verb and should always be a noun). In this Box class, we have some variables as h, w, a_m, a_ft . Do you understand what these mean and what they store in them? If the answer is yes then this is most likely because it is a pretty simple, small code block and a simple one, but trust me, if you see something like this in a big project you will feel completely confused.

在這裡,我們有一個名為Box的類(總是記住,一個類名不能是動詞,而應該始終是名詞)。 在這個Box類中,我們有一些變數,如hwa_ma_ft 。 您瞭解這些含義以及它們儲存在其中的含義嗎? 如果答案是肯定的,那麼這很有可能是因為它是一個非常簡單,很小的程式碼塊和一個簡單的程式碼塊,但是請相信我,如果您在大型專案中看到類似的東西,您會感到完全困惑。

Let’s refactor the above code and try to understand how we’re doing it:

讓我們重構上面的程式碼,並嘗試瞭解我們的做法:

Image for post

We have explicitly written down the variable and function names and also added their units. Adding units in the variable names is very important when you have a program that deals with multiple units. It also saves a lot of time while debugging and adding new features.

我們已經明確寫下了變數和函式名稱,並添加了它們的單位。 當您有一個處理多個單位的程式時,在變數名稱中新增單位非常重要。 在除錯和新增新功能時,它還節省了大量時間。

When writing names, we can follow different conventions for choosing case styles e.g. Snake Case, Pascal Case, Kebab Case, Camel Case. Some languages have their own conventions for using a case style, but we should follow a single case-style throughout the codebase.

在編寫名稱時,我們可以遵循不同的約定來選擇大小寫樣式,例如Snake Case,Pascal Case,Kebab Case,Camel Case。 某些語言在使用案例樣式時有其自己的約定,但是我們應該在整個程式碼庫中遵循一種案例樣式。

有意義的功能 (Meaningful Functions)

Functions are a key component of any programming language, and we write a lot of functions in any project. Sometimes they are called the building blocks of the business logic inside the codebase. We might see a long function having a body of hundreds of lines of code but it gets difficult to catch the gist of what it’s doing inside of it. To resolve this issue we follow a simple rule: write small functions that only do one thing.

函式是任何程式語言的關鍵組成部分,我們在任何專案中都編寫了很多函式。 有時,它們被稱為程式碼庫內部業務邏輯的構建塊。 我們可能會看到一個長函式包含數百行程式碼,但要了解其內部功能的要點變得很困難。 要解決此問題,我們遵循一個簡單的規則:編寫僅做一件事的小函式。

Sometimes we write functions where we fetch multiple data-points from the database, filter them on different attributes, sort them, run additional transformation methods on the data, generate the HTML from a template, and so on. When this occurs, we can separate out those functions and create small functions. This also creates a good separation of concern among the functions.

有時,我們會編寫一些函式,從資料庫中獲取多個數據點,對它們進行不同屬性的過濾,對它們進行排序,對資料執行其他轉換方法,從模板生成HTML,等等。 發生這種情況時,我們可以分離出這些功能並建立較小的功能。 這也會在功能之間建立良好的關注點分離。

Let’s look into this example function:

讓我們看一下這個示例函式:

Image for post

Reading the function you might lose the context of what’s happening inside of it. Here, we are fetching all the pending messages from the database for users who are a merchant and then creating multiple batches based on the BATCH_SIZE before pushing these batches to the job queue and finally updating the status of the sent messages.

閱讀該函式可能會丟失其內部正在發生的情況的上下文。 在這裡,我們正在從資料庫中為商人使用者獲取所有待處理訊息,然後基於BATCH_SIZE建立多個批次,然後再將這些批次推送到作業佇列中,最後更新已傳送訊息的狀態。

It works, but it looks really cluttered, right? Let’s break this long function into multiple small pieces where each of them performs a single task.

它可以工作,但是看起來很混亂,對嗎? 讓我們將此長函式分成多個小塊,每個小塊執行一個任務。

This is how the refactored function will look:

這就是重構函式的外觀:

Image for post

From the look of it, we can identify what these separate functions are doing, making it easy for developers to narrow down the scope while they refactor or debug around this function.

從外觀上,我們可以確定這些單獨的功能在做什麼,從而使開發人員在圍繞該功能進行重構或除錯時,很容易縮小範圍。

Suppose there is a function that is doing multiple things and we cannot separate them as they are closely related. These types of functions need proper indentation and blocking in the code; this explains which block is doing what and creates an abstraction on that separation we were talking about above.

假設有一個函式正在執行多項操作,並且由於它們關係密切,我們無法將它們分開。 這些型別的函式需要在程式碼中進行適當的縮排和阻塞。 這解釋了哪個塊在做什麼,並建立了我們上面所討論的分離的抽象。

Function arguments are another important thing when it comes to clean code. A helpful convention to follow is to never use more than two arguments in a function, and if you must do this then use an object or a dictionary. As a result, anyone can understand what the data-points re that they are sending as arguments to the function from the keys of the objects.

當涉及到乾淨的程式碼時,函式引數是另一重要的事情。 遵循的一個有用的約定是,函式中不要使用兩個以上的引數,如果必須這樣做,則可以使用物件或字典。 結果,任何人都可以從物件的鍵中瞭解它們作為函式的引數傳送的資料點。

We also follow another rule called DRY (Do not Repeat Yourself) while writing functions. The mental model is pretty easy here, whenever we are writing a block of code that is already written somewhere in the codebase, we should treat that block of code as a function and create one to use in multiple places.

在編寫函式時,我們還遵循另一條稱為DRY (請勿重複自己)的規則。 心智模型在這裡非常簡單,每當我們編寫已經在程式碼庫中某處編寫的程式碼塊時,我們都應將該程式碼塊視為一個函式,並建立一個可在多個地方使用的程式碼塊。

相關評論 (Relevant Comments)

Comments are like butter on bread, without it the bread will be dryer and not as enjoyable to eat. If we put relevant comments in each of the modules or functions we write, then whenever someone jumps into that part of the code they might understand the intention behind the writing of that piece of code. Furthermore, if any change is required then they can do this more confidently as they understand what is going on inside of it!

評論就像麵包上的黃油,沒有它,麵包將變得更乾燥,吃起來也不愉快。 如果我們在編寫的每個模組或函式中新增相關的註釋,那麼每當有人跳入程式碼的那一部分時,他們可能就會理解編寫這段程式碼背後的意圖。 此外,如果需要任何更改,那麼他們可以更自信地做到這一點,因為他們瞭解其中發生的一切!

There are many different types of comments for different occasions, let’s check those out:

針對不同場合有多種不同型別的評論,讓我們檢查一下:

  • Legal Comments: Sometimes we developers are forced to write certain comments for legal reasons (e.g., copyright). Authorship of the code can be put at the top of each of the files.

    法律評論:有時,出於法律原因(例如,版權),我們開發人員被迫撰寫某些評論。 可以將程式碼的作者放在每個檔案的頂部。

Image for post
  • Informative Comments: In a line of code, we might share some information that might be taken as an assumption before writing that line of code. Putting that assumption as a piece of information before that line is a very good habit.

    內容豐富的註釋:在一行程式碼中,我們可能會共享一些資訊,這些資訊可能會在編寫該行程式碼之前作為假設。 將這一假設作為一條資訊放在該行之前是一個很好的習慣。

Image for post
  • Explanation of Intent: We have already talked about this, and most developers are kind of aware of this sort of comment in the codebase because these explanatory comments are highly effective while refactoring or debugging codes.

    意圖說明:我們已經討論過這一點,並且大多數開發人員都知道程式碼庫中的這種註釋,因為這些註釋在重構或除錯程式碼時非常有效。

Image for post
  • Warning of Consequences: These might be functions or jobs which are not intended to run in a particular environment, or any warning that a developer should know/notice before running that module.

    後果警告:這些警告可能是某些功能或作業,它們不打算在特定環境中執行,或者是開發人員在執行該模組之前應瞭解/注意的任何警告。

Image for post
  • TODO Comments: You may have come across a type of comment that starts with TODO or FIXME. We developers do this to remind us that there is something left that still needs to be completed or fixed. There are some tools that generate a tree from these comments and help developers to stay accountable.

    TODO評論:您可能遇到過以TODOFIXME開頭的評論型別 我們的開發人員這樣做是為了提醒我們,還有一些尚需完成或修復的問題。 有一些工具可以根據這些註釋生成一棵樹,並幫助開發人員保持責任心。

Other than these, sometimes we put comments to create auto-generated documentation for our projects. Creating documentation from code-snippets is pretty much famous in the open-source ecosystem as it helps contributors or users understand what the code does from the look of the documentation.

除此之外,有時我們會添加註釋以為專案建立自動生成的文件。 在開放原始碼生態系統中,從程式碼片段建立文件非常有名,因為它可以幫助貢獻者或使用者從文件的外觀中瞭解程式碼的作用。

整理和格式化 (Linting and Formatting)

Whatever development platform we use, they all have guidelines for code formatting which we should follow in order to maintain consistency in the codebase. Although a big team may have multiple team tracks that are working on the same repository, having some sort of code conventions applied in the repo helps to make the code clean.

無論我們使用什麼開發平臺,它們都具有程式碼格式化準則,為了保持程式碼庫的一致性,我們應該遵循這些準則。 儘管一個大團隊可能在同一個儲存庫上有多個團隊工作,但是在回購中應用某種程式碼約定有助於使程式碼乾淨。

Linting for static code analyzing is very helpful because it automatically checks a few things on top of the rules that we set and gives alerts if we try to break any of them. For JavaScript we use ESLint, Prettier is also a popular code formatting tool in this ecosystem. In Python, we use autopep8 or black as a formatter.

整理靜態程式碼分析非常有用,因為它會在設定的規則之上自動檢查一些內容,並在嘗試破壞任何規則時發出警報。 對於JavaScript,我們使用ESLint更漂亮也是在這個生態系統中一個流行的程式碼格式化工具。 在Python中,我們使用autopep8black作為格式化程式。

I believe that linting and formatting should be done automatically because we are humans and so make mistakes. There is a chance of pushing unformatted code with linter errors in it to the remote repository. Using Git hooks can be very helpful in avoiding this as it allows us to do auto linting and formatting before pushing or committing any codes to the Git.

我相信,整理和格式化應該自動完成,因為我們是人類,因此會犯錯誤。 有機會將其中包含linter錯誤的未格式化程式碼推送到遠端儲存庫。 使用Git鉤子對避免這種情況非常有幫助,因為它允許我們在將任何程式碼推送或提交到Git之前進行自動整理和格式化。

結論 (Conclusion)

Finally, writing clean and understandable code completely depends on the mental model of a developer. If we simply follow the boy scout rule i.e. “Leave your code better than you found it”, we can eventually end up having a codebase that is way better than before and that people love to work on. Making an effort today to improve your ability to write clean code will certainly pay off in the future, I hope that my article can play a helpful role in your software development journey.

最後,編寫清晰易懂的程式碼完全取決於開發人員的思維模式。 如果我們只是遵循童子軍規則,“讓程式碼比發現的要好” ,我們最終可能會擁有比以前更好的程式碼庫,並且人們喜歡繼續工作。 今天努力提高您編寫乾淨程式碼的能力肯定會在將來有所回報,我希望我的文章可以在您的軟體開發過程中發揮有益的作用。

翻譯自: https://codeburst.io/how-to-keep-your-code-clean-and-easy-to-understand-25b54e7a1b49

dll簡潔易懂