開源日報 每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,堅持閱讀《開源日報》,保持每日學習的好習慣。
今日推薦開源項目:《手焊鍵盤 python-keyboard》
今日推薦英文原文:《Your Code Should Read Like a Book》

今日推薦開源項目:《手焊鍵盤 python-keyboard》傳送門:GitHub鏈接
推薦理由:作者手焊了一個 Python 代碼實現的 USB 藍牙雙模鍵盤,並提供了手把手設計(焊接)教程。跑 Python 的鍵盤,不僅是個鍵盤,也是一個U盤,鍵盤的 Python 代碼則保存在U盤中,可以用任意文本編輯器修改 Python 代碼,無需配置任何開發環境,也就是說,可以自己設計鍵盤的功能。目前該項目的成品已經登陸淘寶。
今日推薦英文原文:《Your Code Should Read Like a Book》作者:Zachary Minott
原文鏈接:https://medium.com/better-programming/your-code-should-read-like-a-book-873b27f71fe5
推薦理由:優美整潔的代碼令人賞心悅目,雜亂無章的代碼……還是忘了它吧。

Your Code Should Read Like a Book

It makes life easier for everyone involved

There』s a pandemic among programmers. Long functions, broad and nondescriptive names for functions, classes, and variable names, overly commented code, disorganized structure, and a lack of overall streamlined flow.

It』s much too often that I take a peek at someone else』s working code just to notice that I have to exert a strenuous amount of effort just to understand what it does in the first place.

I have to try my best to reason about ambiguous variable names such as i, k, num, counter, etc. What type of num are we representing, and what is the purpose of the operations that surround it? What is the purpose of the counter? What is it tracking? Why is it there?

I have to constantly jump all over the class to see how each function builds on top of the other functions around it, just to realize that the names of each function don』t really tell me anything about what the function does.

I』d even have to sometimes read paragraphs of comments that explain the purpose of what a function might do, but still, I shouldn』t have to be reading an essay to simply understand what a function does. I should be able to reason about this simply by taking a quick glance at the function.

Your code should read like a book. Just how a book is structured through paragraphs and chapters that follow a descriptive story that flows in a streamlined and progressive fashion, your code should be structured and designed in a way that I can enter into a class and be able to understand its purpose within moments of engagement. Please don』t make any developer, including yourself, who is looking at your code have to embody Sherlock Holmes in order to deduce the purpose and meaning behind what you wrote.

What exactly should you do?

Self Commenting Code Through Meaningful Names

Code should be self-commenting, which means that the names of your functions, your classes, and your variables should be so descriptive that commenting would be completely unnecessary. A sure sign of poorly written code is matched with its need to have comments.

Stop abbreviating names (unless the translation of the abbreviation is blatantly obvious), stop using letters as variables, and start writing names with the intent to describe exactly what that function』s or variable』s purpose is. The names must be both intention-revealing and pronounceable.

In essence, don』t just write code that only a computer will read. Write code that is human-readable as well. This is extremely simple in practice, but you』ll find that you will become a lot more thoughtful about the naming of everything you write and it』ll allow you to better reason about the intent of what you are programming which ultimately will influence fluid production of your code.

「A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment.」 ― Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
If you still don』t understand, here is a simple example of me populating a picklist with values (language is in Salesforce』s Apex, but you should still understand the gist of what I』m trying to convey):
public static final Integer YEARS_IN_SCHOOL = 12;
public static final Integer GRADUATION_MONTH = 6;
private List<Integer> getGradYearPicklistValues() {
    List<Integer> gradYearValuesList 
            = new List<Integer>();
    Integer earliestYearInPicklist = Date.today().year();
    Integer latestYearInPicklist 
            = earliestYearInPicklist + YEARS_IN_SCHOOL;
    if (Date.today().month() >= GRADUATION_MONTH) {
        earliestYearInPicklist += 1;
        latestYearInPicklist += 1;
    }
    for (Integer year = earliestYearInPicklist; year <= latestYearInPicklist; year++) {
        gradYearValuesList.add(year);
    }
    return gradYearValuesList;
}
As you can see, I use very descriptive variable names and use descriptive function names so that we know exactly the purpose of each variable, and what the purpose this function serves. It becomes very easy for other developers to reason exactly what this function is doing.

Organized Top-Down Code Structure

The way you format your code serves as a direct indicator of the amount of thoughtfulness, attention to detail, and effort put into writing it. When others come to review your code, you want them to be struck with the impressive neatness, orderliness, and readability of the code. The last thing you want is to deliver a monolithic wall of scrambled, unorderly code that at a glance looks like it was written while being hammered off of White Claws and Bud Lights. This only leads to the conclusion that no thought or attention to detail was put into the code whatsoever, which ultimately reflects poorly on you.

The way you should format your code is best explained by the Newspaper Metaphor in Robert C Martin』s Clean Code (a book all programmers should read, by the way):

「Think of a well-written newspaper article. You read it vertically. At the top, you expect a headline that will tell you what the story is about and allows you to decided whether it is something you want to read. The first paragraph gives you a synopsis of the whole story, hiding all the details while giving you the broad-brush concepts. As you continue downward, the details increase until you have all the dates, names, quotes, claims, and other minutiae. We would like a source file to be like a newspaper article.」

What does this tell us? Our class name is our headline — it』s going to describe the contents of what we can find inside the class. At the top of the class is where we are going to find our high-level concepts and algorithms and as we traverse down the class we should be seeing the details increase and increase until we find ourselves at the lowest level function.

How do we follow this structure? Well, it』s very easy, actually. We essentially want the most important details to come first and express those concepts downward with the most precise and concise details. Any function that is called should be placed right below the function that is doing the calling. If a function is too large (my rule of thumb is to keep functions below 20–25 lines), break it up into smaller bite-size functions that provide complete clarity about what a few lines of code are processing. Normally large functions indicate that function is doing too much and that it is starting to get messy, so that』s why we do this. To be more descriptive. To be more neat and orderly.

Takeaway

Programming is very mentally challenging work as it is, and I understand how the importance of great readable code can easily be ignored given that we become so engulfed in the act of programming that we completely forget about the art and design of it. Take a step back and think about what you』re doing — the intention, the neatness, and its readability. It』ll not only help you understand the code you write more but help others understand it better as well. Ultimately, you』ll become a better and more revered programmer because of it. Who knows, you may get some praise for producing something beautiful.


下載開源日報APP:https://openingsource.org/2579/
加入我們:https://openingsource.org/about/join/
關注我們:https://openingsource.org/about/love/