编写可读代码的艺术

开发 开发工具 后端
这是《The Art of Readable Code》的读书笔记,再加一点自己的认识。整本书都围绕“如何让代码的可读性更高”这个目标来写。这也是好代码的重要标准之一。

这是《The Art of Readable Code》的读书笔记,再加一点自己的认识。强烈推荐此书:

代码为什么要易于理解

“Code should be written to minimize the time it would take for someone else to understand it.”

日常工作的事实是:

  • 写代码前的思考和看代码的时间远大于真正写的时间
  • 读代码是很平常的事情,不论是别人的,还是自己的,半年前写的可认为是别人的代码
  • 代码可读性高,很快就可以理解程序的逻辑,进入工作状态
  • 行数少的代码不一定就容易理解
  • 代码的可读性与程序的效率、架构、易于测试一点也不冲突

整本书都围绕“如何让代码的可读性更高”这个目标来写。这也是好代码的重要标准之一。

如何命名

变量名中应包含更多信息

使用含义明确的词,比如用download而不是get,参考以下替换方案:

  1. send -> deliver, dispatch, announce, distribute, route
  2. find -> search, extract, locate, recover
  3. start -> lanuch, create, begin, open
  4. make -> create,set up, build, generate, compose, add, new

避免通用的词

tmpretval这样词,除了说明是临时变量和返回值之外,没有任何意义。但是给他加一些有意义的词,就会很明确:

  1. tmp_file = tempfile.NamedTemporaryFile()
  2. ...
  3. SaveData(tmp_file, ...)

不使用retval而使用变量真正代表的意义:

  1. sum_squares += v[i]; // Where's the "square" that we're summing? Bug!

嵌套的for循环中,ij也有同样让人困惑的时候:

  1. for (int i = 0; i < clubs.size(); i++)
  2. for (int j = 0; j < clubs[i].members.size(); j++)
  3. for (int k = 0; k < users.size(); k++) if (clubs[i].members[k] == users[j])
  4. cout << "user[" << j << "] is in club[" << i << "]" << endl;

换一种写法就会清晰很多:

  1. if (clubs[ci].members[mi] == users[ui]) # OK. First letters match.

所以,当使用一些通用的词,要有充分的理由才可以。

使用具体的名字

CanListenOnPort就比ServerCanStart好,can start比较含糊,而listen on port确切的说明了这个方法将要做什么。

--run_locally就不如--extra_logging来的明确。

增加重要的细节,比如变量的单位_ms,对原始字符串加_raw

如果一个变量很重要,那么在名字上多加一些额外的字就会更加易读,比如将string id; // Example: "af84ef845cd8"换成string hex_id;

  1. Start(int delay) --> delay delay_secs
  2. CreateCache(int size) --> size size_mb
  3. ThrottleDownload(float limit) --> limit max_kbps
  4. Rotate(float angle) --> angle degrees_cw

更多例子:

  1. password -> plaintext_password
  2. comment -> unescaped_comment
  3. html -> html_utf8
  4. data -> data_urlenc

对于作用域大的变量使用较长的名字

在比较小的作用域内,可以使用较短的变量名,在较大的作用域内使用的变量,最好用长一点的名字,编辑器的自动补全都可以很好的减少键盘输入。对于一些缩写前缀,尽量选择众所周知的(如str),一个判断标准是,当新成员加入时,是否可以无需他人帮助而明白前缀代表什么。

合理使用_-等符号,比如对私有变量加_前缀。

  1. var x = new DatePicker(); // DatePicker() 是类的"构造"函数,大写开始
  2. var y = pageHeight(); // pageHeight() 是一个普通函数
  3.  
  4. var $all_images = $("img"); // $all_images 是jQuery对象
  5. var height = 250; // height不是
  6.  
  7. //id和class的写法分开
  8. <div id="middle_column" class="main-content"> ...

命名的时候可以先想一下,我要用的这个词是否有别的含义。举个例子:

  1. results = Database.all_objects.filter("year <= 2011")

现在的结果到底是包含2011年之前的呢还是不包含呢?

使用minmax代替limit

  1. CART_TOO_BIG_LIMIT = 10
  2. if shopping_cart.num_items() >= CART_TOO_BIG_LIMIT:
  3. Error("Too many items in cart.")
  4.  
  5. MAX_ITEMS_IN_CART = 10
  6. if shopping_cart.num_items() > MAX_ITEMS_IN_CART:
  7. Error("Too many items in cart.")

对比上例中CART_TOO_BIG_LIMITMAX_ITEMS_IN_CART,想想哪个更好呢?

使用firstlast来表示闭区间

  1. print integer_range(start=2, stop=4)
  2. # Does this print [2,3] or [2,3,4] (or something else)?
  3.  
  4. set.PrintKeys(first="Bart", last="Maggie")

firstlast含义明确,适宜表示闭区间。

使用beiginend表示前闭后开(2,9))区间

  1. PrintEventsInRange("OCT 16 12:00am", "OCT 17 12:00am")
  2.  
  3. PrintEventsInRange("OCT 16 12:00am", "OCT 16 11:59:59.9999pm")

上面一种写法就比下面的舒服多了。

Boolean型变量命名

  1. bool read_password = true;

这是一个很危险的命名,到底是需要读取密码呢,还是密码已经被读取呢,不知道,所以这个变量可以使用user_is_authenticated代替。通常,给Boolean型变量添加ishascanshould可以让含义更清晰,比如:

  1. SpaceLeft() --> hasSpaceLeft()
  2. bool disable_ssl = false --> bool use_ssl = true

符合预期

  1. public class StatisticsCollector {
  2. public void addSample(double x) { ... }
  3. public double getMean() {
  4. // Iterate through all samples and return total / num_samples
  5. }
  6. ...
  7. }

在这个例子中,getMean方法遍历了所有的样本,返回总额,所以并不是普通意义上轻量的get方法,所以应该取名computeMean比较合适。

#p#

漂亮的格式

写出来漂亮的格式,充满美感,读起来自然也会舒服很多,对比下面两个例子:

  1. class StatsKeeper {
  2. public:
  3. // A class for keeping track of a series of doubles
  4. void Add(double d); // and methods for quick statistics about them
  5. private: int count; /* how many so far
  6. */ public:
  7. double Average();
  8. private: double minimum;
  9. list<double>
  10. past_items
  11. ;double maximum;
  12. };

什么是充满美感的呢:

  1. // A class for keeping track of a series of doubles
  2. // and methods for quick statistics about them.
  3. class StatsKeeper {
  4. public:
  5. void Add(double d);
  6. double Average();
  7. private:
  8. list<double> past_items;
  9. int count; // how many so far
  10. double minimum;
  11. double maximum;
  12. };

考虑断行的连续性和简洁

这段代码需要断行,来满足不超过一行80个字符的要求,参数也需要注释说明:

  1. public class PerformanceTester {
  2. public static final TcpConnectionSimulator wifi = new TcpConnectionSimulator(
  3. 500, /* Kbps */
  4. 80, /* millisecs latency */
  5. 200, /* jitter */
  6. 1 /* packet loss % */);
  7.  
  8. public static final TcpConnectionSimulator t3_fiber = new TcpConnectionSimulator(
  9. 45000, /* Kbps */
  10. 10, /* millisecs latency */
  11. 0, /* jitter */
  12. 0 /* packet loss % */);
  13.  
  14. public static final TcpConnectionSimulator cell = new TcpConnectionSimulator(
  15. 100, /* Kbps */
  16. 400, /* millisecs latency */
  17. 250, /* jitter */
  18. 5 /* packet loss % */);
  19. }

考虑到代码的连贯性,先优化成这样:

  1. public class PerformanceTester {
  2. public static final TcpConnectionSimulator wifi =
  3. new TcpConnectionSimulator(
  4. 500, /* Kbps */
  5. 80, /* millisecs latency */ 200, /* jitter */
  6. 1 /* packet loss % */);
  7.  
  8. public static final TcpConnectionSimulator t3_fiber =
  9. new TcpConnectionSimulator(
  10. 45000, /* Kbps */
  11. 10, /* millisecs latency */
  12. 0, /* jitter */
  13. 0 /* packet loss % */);
  14.  
  15. public static final TcpConnectionSimulator cell =
  16. new TcpConnectionSimulator(
  17. 100, /* Kbps */
  18. 400, /* millisecs latency */
  19. 250, /* jitter */
  20. 5 /* packet loss % */);
  21. }

连贯性好一点,但还是太罗嗦,额外占用很多空间:

  1. public class PerformanceTester {
  2. // TcpConnectionSimulator(throughput, latency, jitter, packet_loss)
  3. // [Kbps] [ms] [ms] [percent]
  4. public static final TcpConnectionSimulator wifi =
  5. new TcpConnectionSimulator(500, 80, 200, 1);
  6.  
  7. public static final TcpConnectionSimulator t3_fiber =
  8. new TcpConnectionSimulator(45000, 10, 0, 0);
  9.  
  10. public static final TcpConnectionSimulator cell =
  11. new TcpConnectionSimulator(100, 400, 250, 5);
  12. }
  1. // Turn a partial_name like "Doug Adams" into "Mr. Douglas Adams".
  2. // If not possible, 'error' is filled with an explanation.
  3. string ExpandFullName(DatabaseConnection dc, string partial_name, string* error);
  4.  
  5. DatabaseConnection database_connection;
  6. string error;
  7. assert(ExpandFullName(database_connection, "Doug Adams", &error)
  8. == "Mr. Douglas Adams");
  9. assert(error == "");
  10. assert(ExpandFullName(database_connection, " Jake Brown ", &error)
  11. == "Mr. Jacob Brown III");
  12. assert(error == "");
  13. assert(ExpandFullName(database_connection, "No Such Guy", &error) == "");
  14. assert(error == "no match found");
  15. assert(ExpandFullName(database_connection, "John", &error) == "");
  16. assert(error == "more than one result");

上面这段代码看起来很脏乱,很多重复性的东西,可以用函数封装:

  1. CheckFullName("Doug Adams", "Mr. Douglas Adams", "");
  2. CheckFullName(" Jake Brown ", "Mr. Jake Brown III", "");
  3. CheckFullName("No Such Guy", "", "no match found");
  4. CheckFullName("John", "", "more than one result");
  5.  
  6. void CheckFullName(string partial_name,
  7. string expected_full_name,
  8. string expected_error) {
  9. // database_connection is now a class member
  10. string error;
  11. string full_name = ExpandFullName(database_connection, partial_name, &error);
  12. assert(error == expected_error);
  13. assert(full_name == expected_full_name);
  14. }

列对齐可以让代码段看起来更舒适:

  1. CheckFullName("Doug Adams" , "Mr. Douglas Adams" , "");
  2. CheckFullName(" Jake Brown ", "Mr. Jake Brown III", "");
  3. CheckFullName("No Such Guy" , "" , "no match found");
  4. CheckFullName("John" , "" , "more than one result");
  5.  
  6. commands[] = {
  7. ...
  8. { "timeout" , NULL , cmd_spec_timeout},
  9. { "timestamping" , &opt.timestamping , cmd_boolean},
  10. { "tries" , &opt.ntry , cmd_number_inf},
  11. { "useproxy" , &opt.use_proxy , cmd_boolean},
  12. { "useragent" , NULL , cmd_spec_useragent},
  13. ...
  14. };
  1. class FrontendServer {
  2. public:
  3. FrontendServer();
  4. void ViewProfile(HttpRequest* request);
  5. void OpenDatabase(string location, string user);
  6. void SaveProfile(HttpRequest* request);
  7. string ExtractQueryParam(HttpRequest* request, string param);
  8. void ReplyOK(HttpRequest* request, string html);
  9. void FindFriends(HttpRequest* request);
  10. void ReplyNotFound(HttpRequest* request, string error);
  11. void CloseDatabase(string location);
  12. ~FrontendServer();
  13. };

上面这一段虽然能看,不过还有优化空间:

  1. class FrontendServer {
  2. public:
  3. FrontendServer();
  4. ~FrontendServer();
  5. // Handlers
  6. void ViewProfile(HttpRequest* request);
  7. void SaveProfile(HttpRequest* request);
  8. void FindFriends(HttpRequest* request);
  9.  
  10. // Request/Reply Utilities
  11. string ExtractQueryParam(HttpRequest* request, string param);
  12. void ReplyOK(HttpRequest* request, string html);
  13. void ReplyNotFound(HttpRequest* request, string error);
  14.  
  15. // Database Helpers
  16. void OpenDatabase(string location, string user);
  17. void CloseDatabase(string location);
  18. };

再来看一段代码:

  1. # Import the user's email contacts, and match them to users in our system.
  2. # Then display a list of those users that he/she isn't already friends with.
  3. def suggest_new_friends(user, email_password):
  4. friends = user.friends()
  5. friend_emails = set(f.email for f in friends)
  6. contacts = import_contacts(user.email, email_password)
  7. contact_emails = set(c.email for c in contacts)
  8. non_friend_emails = contact_emails - friend_emails
  9. suggested_friends = User.objects.select(email__in=non_friend_emails)
  10. display['user'] = user
  11. display['friends'] = friends
  12. display['suggested_friends'] = suggested_friends
  13. return render("suggested_friends.html", display)

全都混在一起,视觉压力相当大,按功能化块:

  1. def suggest_new_friends(user, email_password):
  2. # Get the user's friends' email addresses.
  3. friends = user.friends()
  4. friend_emails = set(f.email for f in friends)
  5.  
  6. # Import all email addresses from this user's email account.
  7. contacts = import_contacts(user.email, email_password)
  8. contact_emails = set(c.email for c in contacts)
  9.  
  10. # Find matching users that they aren't already friends with.
  11. non_friend_emails = contact_emails - friend_emails
  12. suggested_friends = User.objects.select(email__in=non_friend_emails)
  13.  
  14. # Display these lists on the page. display['user'] = user
  15. display['friends'] = friends
  16. display['suggested_friends'] = suggested_friends
  17.  
  18. return render("suggested_friends.html", display)

让代码看起来更舒服,需要在写的过程中多注意,培养一些好的习惯,尤其当团队合作的时候,代码风格比如大括号的位置并没有对错,但是不遵循团队规范那就是错的。

#p#

如何写注释

当你写代码的时候,你会思考很多,但是最终呈现给读者的就只剩代码本身了,额外的信息丢失了,所以注释的目的就是让读者了解更多的信息。

不应该注释什么

这样的注释毫无价值:

  1. // The class definition for Account
  2. class Account {
  3. public:
  4. // Constructor
  5. Account();
  6. // Set the profit member to a new value
  7. void SetProfit(double profit);
  8. // Return the profit from this Account
  9. double GetProfit();
  10. };

不要像下面这样为了注释而注释:

  1. // Find a Node with the given 'name' or return NULL.
  2. // If depth <= 0, only 'subtree' is inspected.
  3. // If depth == N, only 'subtree' and N levels below are inspected.
  4. Node* FindNodeInSubtree(Node* subtree, string name, int depth);

不要给烂取名注释

  1. // Enforce limits on the Reply as stated in the Request,
  2. // such as the number of items returned, or total byte size, etc.
  3. void CleanReply(Request request, Reply reply);

注释的大部分都在解释clean是什么意思,那不如换个正确的名字:

  1. // Make sure 'reply' meets the count/byte/etc. limits from the 'request'
  2. void EnforceLimitsFromRequest(Request request, Reply reply);

记录你的想法

我们讨论了不该注释什么,那么应该注释什么呢?注释应该记录你思考代码怎么写的结果,比如像下面这些:

  1. // Surprisingly, a binary tree was 40% faster than a hash table for this data.
  2. // The cost of computing a hash was more than the left/right comparisons.
  3.  
  4. // This heuristic might miss a few words. That's OK; solving this 100% is hard.
  5.  
  6. // This class is getting messy. Maybe we should create a 'ResourceNode' subclass to
  7. // help organize things.

也可以用来记录流程和常量:

  1. // TODO: use a faster algorithm
  2. // TODO(dustin): handle other image formats besides JPEG
  3.  
  4. NUM_THREADS = 8 # as long as it's >= 2 * num_processors, that's good enough.
  5.  
  6. // Impose a reasonable limit - no human can read that much anyway.
  7. const int MAX_RSS_SUBSCRIPTIONS = 1000;

可用的词有:

  1. TODO : Stuff I haven't gotten around to yet
  2. FIXME : Known-broken code here
  3. HACK : Adimittedly inelegant solution to a problem
  4. XXX : Danger! Major problem here

站在读者的角度去思考

当别人读你的代码时,让他们产生疑问的部分,就是你应该注释的地方。

  1. struct Recorder {
  2. vector<float> data;
  3. ...
  4. void Clear() {
  5. vector<float>().swap(data); // Huh? Why not just data.clear()?
  6. }
  7. };

很多C++的程序员啊看到这里,可能会想为什么不用data.clear()来代替vector.swap,所以那个地方应该加上注释:

  1. // Force vector to relinquish its memory (look up "STL swap trick")
  2. vector<float>().swap(data);

说明可能陷阱

你在写代码的过程中,可能用到一些hack,或者有其他需要读代码的人知道的陷阱,这时候就应该注释:

  1. void SendEmail(string to, string subject, string body);

而实际上这个发送邮件的函数是调用别的服务,有超时设置,所以需要注释:

  1. // Calls an external service to deliver email. (Times out after 1 minute.)
  2. void SendEmail(string to, string subject, string body);

全景的注释

有时候为了更清楚说明,需要给整个文件加注释,让读者有个总体的概念:

  1. // This file contains helper functions that provide a more convenient interface to our
  2. // file system. It handles file permissions and other nitty-gritty details.

总结性的注释

即使是在函数内部,也可以有类似文件注释那样的说明注释:

  1. # Find all the items that customers purchased for themselves.
  2. for customer_id in all_customers:
  3. for sale in all_sales[customer_id].sales:
  4. if sale.recipient == customer_id:
  5. ...

或者按照函数的步进,写一些注释:

  1. def GenerateUserReport():
  2. # Acquire a lock for this user
  3. ...
  4. # Read user's info from the database
  5. ...
  6. # Write info to a file
  7. ...
  8. # Release the lock for this user

很多人不愿意写注释,确实,要写好注释也不是一件简单的事情,也可以在文件专门的地方,留个写注释的区域,可以写下你任何想说的东西。

前一个小节讨论了注释应该写什么,这一节来讨论应该怎么写,因为注释很重要,所以要写的精确,注释也占据屏幕空间,所以要简洁。

精简注释

  1. // The int is the CategoryType.
  2. // The first float in the inner pair is the 'score',
  3. // the second is the 'weight'.
  4. typedef hash_map<int, pair<float, float> > ScoreMap;

这样写太罗嗦了,尽量精简压缩成这样:

  1. // CategoryType -> (score, weight)
  2. typedef hash_map<int, pair<float, float> > ScoreMap;

避免有歧义的代词

  1. // Insert the data into the cache, but check if it's too big first.

这里的it's有歧义,不知道所指的是data还是cache,改成如下:

  1. // Insert the data into the cache, but check if the data is too big first.

还有更好的解决办法,这里的it就有明确所指:

  1. // If the data is small enough, insert it into the cache.

语句要精简准确

  1. # Depending on whether we've already crawled this URL before, give it a different priority.

这句话理解起来太费劲,改成如下就好理解很多:

  1. # Give higher priority to URLs we've never crawled before.

精确描述函数的目的

  1. // Return the number of lines in this file.
  2. int CountLines(string filename) { ... }

这样的一个函数,用起来可能会一头雾水,因为他可以有很多歧义:

  • ”” 一个空文件,是0行还是1行?
  • “hello” 只有一行,那么返回值是0还是1?
  • “hello\n” 这种情况返回1还是2?
  • “hello\n world” 返回1还是2?
  • “hello\n\r cruel\n world\r” 返回2、3、4哪一个呢?

所以注释应该这样写:

  1. // Count how many newline bytes ('\n') are in the file.
  2. int CountLines(string filename) { ... }

用实例说明边界情况

  1. // Rearrange 'v' so that elements < pivot come before those >= pivot;
  2. // Then return the largest 'i' for which v[i] < pivot (or -1 if none are < pivot)
  3. int Partition(vector<int>* v, int pivot);

这个描述很精确,但是如果再加入一个例子,就更好了:

  1. // ...
  2. // Example: Partition([8 5 9 8 2], 8) might result in [5 2 | 8 9 8] and return 1
  3. int Partition(vector<int>* v, int pivot);

说明你的代码的真正目的

  1. void DisplayProducts(list<Product> products) {
  2. products.sort(CompareProductByPrice);
  3. // Iterate through the list in reverse order
  4. for (list<Product>::reverse_iterator it = products.rbegin(); it != products.rend();
  5. ++it)
  6. DisplayPrice(it->price);
  7. ...
  8. }

这里的注释说明了倒序排列,单还不够准确,应该改成这样:

  1. // Display each price, from highest to lowest
  2. for (list<Product>::reverse_iterator it = products.rbegin(); ... )

函数调用时的注释

看见这样的一个函数调用,肯定会一头雾水:

  1. Connect(10, false);

如果加上这样的注释,读起来就清楚多了:

  1. def Connect(timeout, use_encryption): ...
  2.  
  3. # Call the function using named parameters
  4. Connect(timeout = 10, use_encryption = False)

使用信息含量丰富的词

  1. // This class contains a number of members that store the same information as in the
  2. // database, but are stored here for speed. When this class is read from later, those
  3. // members are checked first to see if they exist, and if so are returned; otherwise the
  4. // database is read from and that data stored in those fields for next time.

上面这一大段注释,解释的很清楚,如果换一个词来代替,也不会有什么疑惑:

  1. // This class acts as a caching layer to the database.

#p#

简化循环和逻辑

让条件语句、循环以及其他控制流程的代码尽可能自然,让读者在阅读过程中不需要停顿思考或者在回头查找,是这一节的目的。

条件语句中参数的位置

对比下面两种条件的写法:

  1. if (length >= 10)
  2. while (bytes_received < bytes_expected)
  3.  
  4. if (10 <= length)
  5. while (bytes_expected > bytes_received)

到底是应该按照大于小于的顺序来呢,还是有其他的准则?是的,应该按照参数的意义来

  • 运算符左边:通常是需要被检查的变量,也就是会经常变化的
  • 运算符右边:通常是被比对的样本,一定程度上的常量

这就解释了为什么bytes_received < bytes_expected比反过来更好理解。

if/else的顺序

通常,if/else的顺序你可以自由选择,下面这两种都可以:

  1. if (a == b) {
  2. // Case One ...
  3. } else {
  4. // Case Two ...
  5. }
  6.  
  7. if (a != b) {
  8. // Case Two ...
  9. } else {
  10. // Case One ...
  11. }

或许对此你也没有仔细斟酌过,但在有些时候,一种顺序确实好过另一种:

  • 正向的逻辑在前,比如if(debug)就比if(!debug)
  • 简单逻辑的在前,这样ifelse就可以在一个屏幕显示 - 有趣、清晰的逻辑在前

举个例子来看:

  1. if (!url.HasQueryParameter("expand_all")) {
  2. response.Render(items);
  3. ...
  4. } else {
  5. for (int i = 0; i < items.size(); i++) {
  6. items[i].Expand();
  7. }
  8. ...
  9. }

看到if你首先想到的是expand_all,就好像告诉你“不要想大象”,你会忍不住去想它,所以产生了一点点迷惑,最好写成:

  1. if (url.HasQueryParameter("expand_all")) {
  2. for (int i = 0; i < items.size(); i++) {
  3. items[i].Expand();
  4. }
  5. ...
  6. } else {
  7. response.Render(items);
  8. ...
  9. }

三目运算符(?:)

  1. time_str += (hour >= 12) ? "pm" : "am";
  2.  
  3. Avoiding the ternary operator, you might write:
  4. if (hour >= 12) {
  5. time_str += "pm";
  6. } else {
  7. time_str += "am";
  8. }

使用三目运算符可以减少代码行数,上例就是一个很好的例证,但是我们的真正目的是减少读代码的时间,所以下面的情况并不适合用三目运算符:

  1. return exponent >= 0 ? mantissa * (1 << exponent) : mantissa / (1 << -exponent);
  2.  
  3. if (exponent >= 0) {
  4. return mantissa * (1 << exponent);
  5. } else {
  6. return mantissa / (1 << -exponent);
  7. }

所以只在简单表达式的地方用。

避免使用do/while表达式

  1. do {
  2. continue;
  3. } while (false);

这段代码会执行几遍呢,需要时间思考一下,do/while完全可以用别的方法代替,所以应避免使用。

尽早return

  1. public boolean Contains(String str, String substr) {
  2. if (str == null || substr == null) return false;
  3. if (substr.equals("")) return true;
  4. ...
  5. }

函数里面尽早的return,可以让逻辑更加清晰。

减少嵌套

  1. if (user_result == SUCCESS) {
  2. if (permission_result != SUCCESS) {
  3. reply.WriteErrors("error reading permissions");
  4. reply.Done();
  5. return;
  6. }
  7. reply.WriteErrors("");
  8. } else {
  9. reply.WriteErrors(user_result);
  10. }
  11. reply.Done();

这样一段代码,有一层的嵌套,但是看起来也会稍有迷惑,想想自己的代码,有没有类似的情况呢?可以换个思路去考虑这段代码,并且用尽早return的原则修改,看起来就舒服很多:

  1. if (user_result != SUCCESS) {
  2. reply.WriteErrors(user_result);
  3. reply.Done();
  4. return;
  5. }
  6. if (permission_result != SUCCESS) {
  7. reply.WriteErrors(permission_result);
  8. reply.Done();
  9. return;
  10. }
  11. reply.WriteErrors("");
  12. reply.Done();

同样的,对于有嵌套的循环,可以采用同样的办法:

  1. for (int i = 0; i < results.size(); i++) {
  2. if (results[i] != NULL) {
  3. non_null_count++;
  4. if (results[i]->name != "") {
  5. cout << "Considering candidate..." << endl;
  6. ...
  7. }
  8. }
  9. }

换一种写法,尽早return,在循环中就用continue:

  1. for (int i = 0; i < results.size(); i++) {
  2. if (results[i] == NULL) continue;
  3. non_null_count++;
  4.  
  5. if (results[i]->name == "") continue;
  6. cout << "Considering candidate..." << endl;
  7. ...
  8. }

#p#

拆分复杂表达式

很显然的,越复杂的表达式,读起来越费劲,所以应该把那些复杂而庞大的表达式,拆分成一个个易于理解的小式子。

用变量

将复杂表达式拆分最简单的办法,就是增加一个变量:

  1. if line.split(':')[0].strip() == "root":
  2.  
  3. //用变量替换
  4. username = line.split(':')[0].strip()
  5. if username == "root":
  6. ...

或者这个例子:

  1. if (request.user.id == document.owner_id) {
  2. // user can edit this document...
  3. }
  4. ...
  5. if (request.user.id != document.owner_id) {
  6. // document is read-only...
  7. }
  8.  
  9. //用变量替换
  10. final boolean user_owns_document = (request.user.id == document.owner_id);
  11. if (user_owns_document) {
  12. // user can edit this document...
  13. }
  14. ...
  15. if (!user_owns_document) {
  16. // document is read-only...
  17. }

逻辑替换

  • 1) not (a or b or c) <–> (not a) and (not b) and (not c)
  • 2) not (a and b and c) <–> (not a) or (not b) or (not c)

所以,就可以这样写:

  1. if (!(file_exists && !is_protected)) Error("Sorry, could not read file.");
  2.  
  3. //替换
  4. if (!file_exists || is_protected) Error("Sorry, could not read file.");

不要滥用逻辑表达式

  1. assert((!(bucket = FindBucket(key))) || !bucket->IsOccupied());

这样的代码完全可以用下面这个替换,虽然有两行,但是更易懂:

  1. bucket = FindBucket(key);
  2. if (bucket != NULL) assert(!bucket->IsOccupied());

像下面这样的表达式,最好也不要写,因为在有些语言中,x会被赋予第一个为true的变量的值:

  1. x = a || b || c

拆解大表达式

  1. var update_highlight = function (message_num) {
  2. if ($("#vote_value" + message_num).html() === "Up") {
  3. $("#thumbs_up" + message_num).addClass("highlighted");
  4. $("#thumbs_down" + message_num).removeClass("highlighted");
  5. } else if ($("#vote_value" + message_num).html() === "Down") {
  6. $("#thumbs_up" + message_num).removeClass("highlighted");
  7. $("#thumbs_down" + message_num).addClass("highlighted");
  8. } else {
  9. $("#thumbs_up" + message_num).removeClass("highighted");
  10. $("#thumbs_down" + message_num).removeClass("highlighted");
  11. }
  12. };

这里面有很多重复的语句,我们可以用变量还替换简化:

  1. var update_highlight = function (message_num) {
  2. var thumbs_up = $("#thumbs_up" + message_num);
  3. var thumbs_down = $("#thumbs_down" + message_num);
  4. var vote_value = $("#vote_value" + message_num).html();
  5. var hi = "highlighted";
  6.  
  7. if (vote_value === "Up") {
  8. thumbs_up.addClass(hi);
  9. thumbs_down.removeClass(hi);
  10. } else if (vote_value === "Down") {
  11. thumbs_up.removeClass(hi);
  12. thumbs_down.addClass(hi);
  13. } else {
  14. thumbs_up.removeClass(hi);
  15. thumbs_down.removeClass(hi);
  16. }
  17. }

变量与可读性

消除变量

前一节,讲到利用变量来拆解大表达式,这一节来讨论如何消除多余的变量。

没用的临时变量

  1. now = datetime.datetime.now()
  2. root_message.last_view_time = now

这里的now可以去掉,因为:

  • 并非用来拆分复杂的表达式
  • 也没有增加可读性,因为`datetime.datetime.now()`本就清晰
  • 只用了一次

所以完全可以写作:

  1. root_message.last_view_time = datetime.datetime.now()

消除条件控制变量

  1. boolean done = false;
  2. while (/* condition */ && !done) {
  3. ...
  4. if (...) {
  5. done = true;
  6. continue;
  7. }
  8. }

这里的done可以用别的方式更好的完成:

  1. while (/* condition */) {
  2. ...
  3. if (...) {
  4. break;
  5. }
  6. }

这个例子非常容易修改,如果是比较复杂的嵌套,break可能并不够用,这时候就可以把代码封装到函数中。

减少变量的作用域

我们都听过要避免使用全局变量这样的忠告,是的,当变量的作用域越大,就越难追踪,所以要保持变量小的作用域。

  1. class LargeClass {
  2. string str_;
  3. void Method1() {
  4. str_ = ...;
  5. Method2();
  6. }
  7. void Method2() {
  8. // Uses str_
  9. }
  10. // Lots of other methods that don't use str_
  11. ... ;
  12. }

这里的str_的作用域有些大,完全可以换一种方式:

  1. class LargeClass {
  2. void Method1() {
  3. string str = ...;
  4. Method2(str);
  5. }
  6. void Method2(string str) {
  7. // Uses str
  8. }
  9. // Now other methods can't see str.
  10. };

str通过变量函数参数传递,减小了作用域,也更易读。同样的道理也可以用在定义类的时候,将大类拆分成一个个小类。

不要使用嵌套的作用域

  1. # No use of example_value up to this point.
  2. if request:
  3. for value in request.values:
  4. if value > 0:
  5. example_value = value
  6. break
  7.  
  8. for logger in debug.loggers:
  9. logger.log("Example:", example_value)

这个例子在运行时候会报example_value is undefined的错,修改起来不算难:

  1. example_value = None
  2. if request:
  3. for value in request.values:
  4. if value > 0: example_value = value
  5. break
  6.  
  7. if example_value:
  8. for logger in debug.loggers:
  9. logger.log("Example:", example_value)

但是参考前面的消除中间变量准则,还有更好的办法:

  1. def LogExample(value):
  2. for logger in debug.loggers:
  3. logger.log("Example:", value)
  4.  
  5. if request:
  6. for value in request.values:
  7. if value > 0:
  8. LogExample(value) # deal with 'value' immediately
  9. break

用到了再声明

在C语言中,要求将所有的变量事先声明,这样当用到变量较多时候,读者处理这些信息就会有难度,所以一开始没用到的变量,就暂缓声明:

  1. def ViewFilteredReplies(original_id):
  2. filtered_replies = []
  3. root_message = Messages.objects.get(original_id)
  4. all_replies = Messages.objects.select(root_id=original_id)
  5. root_message.view_count += 1
  6. root_message.last_view_time = datetime.datetime.now()
  7. root_message.save()
  8.  
  9. for reply in all_replies:
  10. if reply.spam_votes <= MAX_SPAM_VOTES:
  11. filtered_replies.append(reply)
  12.  
  13. return filtered_replies

读者一次处理变量太多,可以暂缓声明:

  1. def ViewFilteredReplies(original_id):
  2. root_message = Messages.objects.get(original_id)
  3. root_message.view_count += 1
  4. root_message.last_view_time = datetime.datetime.now()
  5. root_message.save()
  6.  
  7. all_replies = Messages.objects.select(root_id=original_id)
  8. filtered_replies = []
  9. for reply in all_replies:
  10. if reply.spam_votes <= MAX_SPAM_VOTES:
  11. filtered_replies.append(reply)
  12.  
  13. return filtered_replies

变量最好只写一次

前面讨论了过多的变量会让读者迷惑,同一个变量,不停的被赋值也会让读者头晕,如果变量变化的次数少一些,代码可读性就更强。

一个例子

假设有一个页面,如下,需要给第一个空的input赋值:

  1. <input type="text" id="input1" value="Dustin">
  2. <input type="text" id="input2" value="Trevor">
  3. <input type="text" id="input3" value="">
  4. <input type="text" id="input4" value="Melissa">
  5. ...
  6. var setFirstEmptyInput = function (new_value) {
  7. var found = false;
  8. var i = 1;
  9. var elem = document.getElementById('input' + i);
  10. while (elem !== null) {
  11. if (elem.value === '') {
  12. found = true;
  13. break;
  14. }
  15. i++;
  16. elem = document.getElementById('input' + i);
  17. }
  18. if (found) elem.value = new_value;
  19. return elem;
  20. };

这段代码能工作,有三个变量,我们逐一去看如何优化,found作为中间变量,完全可以消除:

  1. var setFirstEmptyInput = function (new_value) {
  2. var i = 1;
  3. var elem = document.getElementById('input' + i);
  4. while (elem !== null) {
  5. if (elem.value === '') {
  6. elem.value = new_value;
  7. return elem;
  8. }
  9. i++;
  10. elem = document.getElementById('input' + i);
  11. }
  12. return null;
  13. };

再来看elem变量,只用来做循环,调用了很多次,所以很难跟踪他的值,i也可以用for来修改:

  1. var setFirstEmptyInput = function (new_value) {
  2. for (var i = 1; true; i++) {
  3. var elem = document.getElementById('input' + i);
  4. if (elem === null)
  5. return null; // Search Failed. No empty input found.
  6. if (elem.value === '') {
  7. elem.value = new_value;
  8. return elem;
  9. }
  10. }
  11. };

#p#

重新组织你的代码

工程师就是将大问题分解为一个个小问题,然后逐个解决,这样也易于保证程序的健壮性、可读性。如何分解子问题,下面给出一些准则:

  • 看看这个方法或代码,问问你自己“这段代码的最终目标是什么?”
  • 对于每一行代码,要问“它与目标直接相关,或者是不相关的子问题?”
  • 如果有足够多行的代码是处理与目标不直接相关的问题,那么抽离成子函数

来看一个例子:

  1. ajax_post({
  2. url: 'http://example.com/submit',
  3. data: data,
  4. on_success: function (response_data) {
  5. var str = "{\n";
  6. for (var key in response_data) {
  7. str += " " + key + " = " + response_data[key] + "\n";
  8. }
  9. alert(str + "}");
  10. // Continue handling 'response_data' ...
  11. }
  12. });

这段代码的目标是发送一个ajax请求,所以其中字符串处理的部分就可以抽离出来:

  1. var format_pretty = function (obj) {
  2. var str = "{\n";
  3. for (var key in obj) {
  4. str += " " + key + " = " + obj[key] + "\n";
  5. }
  6. return str + "}";
  7. };

意外收获

有很多理由将format_pretty抽离出来,这些独立的函数可以很容易的添加feature,增强可靠性,处理边界情况,等等。所以这里,可以将format_pretty增强,就会得到一个更强大的函数:

  1. var format_pretty = function (obj, indent) {
  2. // Handle null, undefined, strings, and non-objects.
  3. if (obj === null) return "null";
  4. if (obj === undefined) return "undefined";
  5. if (typeof obj === "string") return '"' + obj + '"';
  6. if (typeof obj !== "object") return String(obj);
  7. if (indent === undefined) indent = "";
  8.  
  9. // Handle (non-null) objects.
  10.  
  11. var str = "{\n";
  12. for (var key in obj) {
  13. str += indent + " " + key + " = ";
  14. str += format_pretty(obj[key], indent + " ") + "\n"; }
  15. return str + indent + "}";
  16. };

这个函数输出:

  1. {
  2. key1 = 1
  3. key2 = true
  4. key3 = undefined
  5. key4 = null
  6. key5 = {
  7. key5a = {
  8. key5a1 = "hello world"
  9. }
  10. }
  11. }

多做这样的事情,就是积累代码的过程,这样的代码可以复用,也可以形成自己的代码库,或者分享给别人。

业务相关的函数

那些与目标不相关函数,抽离出来可以复用,与业务相关的也可以抽出来,保持代码的易读性,例如:

  1. business = Business()
  2. business.name = request.POST["name"]
  3.  
  4. url_path_name = business.name.lower()
  5. url_path_name = re.sub(r"['\.]", "", url_path_name)
  6. url_path_name = re.sub(r"[^a-z0-9]+", "-", url_path_name)
  7. url_path_name = url_path_name.strip("-")
  8. business.url = "/biz/" + url_path_name
  9.  
  10. business.date_created = datetime.datetime.utcnow()
  11. business.save_to_database()

抽离出来,就好看很多:

  1. CHARS_TO_REMOVE = re.compile(r"['\.']+")
  2. CHARS_TO_DASH = re.compile(r"[^a-z0-9]+")
  3.  
  4. def make_url_friendly(text):
  5. text = text.lower()
  6. text = CHARS_TO_REMOVE.sub('', text)
  7. text = CHARS_TO_DASH.sub('-', text)
  8. return text.strip("-")
  9.  
  10. business = Business()
  11. business.name = request.POST["name"]
  12. business.url = "/biz/" + make_url_friendly(business.name)
  13. business.date_created = datetime.datetime.utcnow()
  14. business.save_to_database()

简化现有接口

我们来看一个读写cookie的函数:

  1. var max_results;
  2. var cookies = document.cookie.split(';');
  3. for (var i = 0; i < cookies.length; i++) {
  4. var c = cookies[i];
  5. c = c.replace(/^[ ]+/, ''); // remove leading spaces
  6. if (c.indexOf("max_results=") === 0)
  7. max_results = Number(c.substring(12, c.length));
  8. }

这段代码实在太丑了,理想的接口应该是这样的:

  1. set_cookie(name, value, days_to_expire);
  2. delete_cookie(name);

对于并不理想的接口,你永远可以用自己的函数做封装,让接口更好用。

按自己需要写接口

  1. ser_info = { "username": "...", "password": "..." }
  2. user_str = json.dumps(user_info)
  3. cipher = Cipher("aes_128_cbc", key=PRIVATE_KEY, init_vector=INIT_VECTOR, op=ENCODE)
  4. encrypted_bytes = cipher.update(user_str)
  5. encrypted_bytes += cipher.final() # flush out the current 128 bit block
  6. url = "http://example.com/?user_info=" + base64.urlsafe_b64encode(encrypted_bytes)
  7. ...

虽然终极目的是拼接用户信息的字符,但是代码大部分做的事情是解析python的object,所以:

  1. def url_safe_encrypt(obj):
  2. obj_str = json.dumps(obj)
  3. cipher = Cipher("aes_128_cbc", key=PRIVATE_KEY, init_vector=INIT_VECTOR, op=ENCODE) encrypted_bytes = cipher.update(obj_str)
  4. encrypted_bytes += cipher.final() # flush out the current 128 bit block
  5. return base64.urlsafe_b64encode(encrypted_bytes)

这样在其他地方也可以调用:

  1. user_info = { "username": "...", "password": "..." }
  2. url = "http://example.com/?user_info=" + url_safe_encrypt(user_info)

分离子函数是好习惯,但是也要适度,过度的分离成多个小函数,也会让查找变得困难。

代码应该是一次只完成一个任务

  1. var place = location_info["LocalityName"]; // e.g. "Santa Monica"
  2. if (!place) {
  3. place = location_info["SubAdministrativeAreaName"]; // e.g. "Los Angeles"
  4. }
  5. if (!place) {
  6. place = location_info["AdministrativeAreaName"]; // e.g. "California"
  7. }
  8. if (!place) {
  9. place = "Middle-of-Nowhere";
  10. }
  11. if (location_info["CountryName"]) {
  12. place += ", " + location_info["CountryName"]; // e.g. "USA"
  13. } else {
  14. place += ", Planet Earth";
  15. }
  16.  
  17. return place;

这是一个用来拼地名的函数,有很多的条件判断,读起来非常吃力,有没有办法拆解任务呢?

  1. var town = location_info["LocalityName"]; // e.g. "Santa Monica"
  2. var city = location_info["SubAdministrativeAreaName"]; // e.g. "Los Angeles"
  3. var state = location_info["AdministrativeAreaName"]; // e.g. "CA"
  4. var country = location_info["CountryName"]; // e.g. "USA"

先拆解第一个任务,将各变量分别保存,这样在后面使用中不需要去记忆那些繁长的key值了,第二个任务,解决地址拼接的后半部分:

  1. // Start with the default, and keep overwriting with the most specific value. var second_half = "Planet Earth";
  2. if (country) {
  3. second_half = country;
  4. }
  5. if (state && country === "USA") {
  6. second_half = state;
  7. }

再来解决前半部分:

  1. var first_half = "Middle-of-Nowhere";
  2. if (state && country !== "USA") {
  3. first_half = state;
  4. }
  5. if (city) {
  6. first_half = city;
  7. }
  8. if (town) {
  9. first_half = town;
  10. }

大功告成:

  1. return first_half + ", " + second_half;

如果注意到有USA这个变量的判断的话,也可以这样写:

  1. var first_half, second_half;
  2. if (country === "USA") {
  3. first_half = town || city || "Middle-of-Nowhere";
  4. second_half = state || "USA";
  5. } else {
  6. first_half = town || city || state || "Middle-of-Nowhere";
  7. second_half = country || "Planet Earth";
  8. }
  9. return first_half + ", " + second_half;

要把一个复杂的东西解释给别人,一些细节很容易就让人产生迷惑,所以想象把你的代码用平实的语言解释给别人听,别人是否能懂,有一些准则可以帮助你让代码更清晰:

  • 用最平实的语言描述代码的目的,就像给读者讲述一样
  • 注意描述中关键的字词
  • 让你的代码符合你的描述

下面这段代码用来校验用户的权限:

  1. $is_admin = is_admin_request();
  2. if ($document) {
  3. if (!$is_admin && ($document['username'] != $_SESSION['username'])) {
  4. return not_authorized();
  5. }
  6. } else {
  7. if (!$is_admin) {
  8. return not_authorized();
  9. }
  10. }
  11. // continue rendering the page ...

这一段代码不长,里面的逻辑嵌套倒是复杂,参考前面章节所述,嵌套太多非常影响阅读理解,将这个逻辑用语言描述就是:

  1. 有两种情况有权限:
  2. 1、你是管理员(admin)
  3. 2、你拥有这个文档
  4. 否则就没有权限

根据描述来写代码:

  1. if (is_admin_request()) {
  2. // authorized
  3. } elseif ($document && ($document['username'] == $_SESSION['username'])) {
  4. // authorized
  5. } else {
  6. return not_authorized();
  7. }
  8. // continue rendering the page ...

最易懂的代码就是没有代码!

  • 去掉那些没意义的feature,也不要过度设计
  • 重新考虑需求,解决最简单的问题,也能完成整体的目标
  • 熟悉你常用的库,周期性研究他的API

最后

还有一些与测试相关的章节,留给你自己去研读吧,再次推荐此书:

原文链接:http://beiyuu.com/readable-code/

责任编辑:林师授 来源: BeiYuu 的博客
相关推荐

2012-07-11 10:51:37

编程

2011-04-15 15:16:18

代码编程

2015-08-27 13:11:18

JavaScript代码

2024-02-23 08:00:00

2021-10-09 10:24:53

Java 代码可读性

2023-02-01 08:17:48

GitHub提交信息

2021-04-01 16:43:05

代码可读性开发

2017-10-30 15:22:29

代码可读性技巧

2019-11-08 09:20:57

代码开发工具

2022-08-23 14:57:43

Python技巧函数

2022-08-29 00:37:53

Python技巧代码

2019-12-03 09:32:32

JavaScript代码开发

2022-11-04 11:18:16

代码优化可读性

2024-01-31 08:04:43

PygmentsPython

2014-07-28 10:28:25

程序员

2014-07-29 09:55:33

程序员代码可读性

2022-06-06 12:02:23

代码注释语言

2021-03-17 08:00:59

JS语言Javascript

2016-11-30 18:35:03

JavaScript

2012-12-17 13:51:22

Web前端JavaScriptJS
点赞
收藏

51CTO技术栈公众号