《編寫可讀程式碼的藝術》第4章 審美
阿新 • • 發佈:2020-12-31
1. 為什麼審美這麼重要?
讓人愉悅的程式碼更易讀,因此更容易使用。
2. 重新安排換行來保持一致和緊湊
下面的程式碼有著優雅一致的風格,並且很容易從頭看到尾快速瀏覽。
但是缺憾在於用了更多的縱向空間,並且註釋重複了三遍。
1 public class PerformanceTester { 2 public static final TcpConnectionSimulator wifi = 3 new TcpConnectionSimulator( 4 500, /* Kbps */ 5 80, /*millisecs latency */ 6 200, /* jitter */ 7 1 /* packet loss % */); 8 9 public static final TcpConnectionSimulator t3_fiber = 10 new TcpConnectionSimulator( 11 45000, /* Kbps */ 12 10, /* millisecs latency */ 13 0, /*jitter */ 14 0 /* packet loss % */); 15 16 public static final TcpConnectionSimulator cell = 17 new TcpConnectionSimulator( 18 100, /* Kbps */ 19 400, /* millisecs latency */ 20 250, /* jitter */ 21 5 /* packet loss %*/); 22 }
更緊湊的書寫方式如下:
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 public static final TcpConnectionSimulator t3_fiber = 7 new TcpConnectionSimulator(45000, 10, 0, 0); 8 public static final TcpConnectionSimulator cell = 9 new TcpConnectionSimulator(100, 400, 250, 5); 10 }
3. 用方法(函式)整理不規則的東西
下面這段程式碼沒有什麼美感可言。
1 DatabaseConnection database_connection; 2 string error; 3 assert(ExpandFullName(database_connection, "Doug Adams", &error) 4 == "Mr. Douglas Adams"); 5 assert(error == ""); 6 assert(ExpandFullName(database_connection, " Jake Brown ", &error) 7 == "Mr. Jacob Brown III"); 8 assert(error == ""); 9 assert(ExpandFullName(database_connection, "No Such Guy", &error) == ""); 10 assert(error == "no match found"); 11 assert(ExpandFullName(database_connection, "John", &error) == ""); 12 assert(error == "more than one result");
需要一個輔助函式來改進。
1 void CheckFullName(string partial_name, 2 string expected_full_name, 3 string expected_error) { 4 // database_connection is now a class member 5 string error; 6 string full_name = ExpandFullName(database_connection, partial_name, &error); 7 assert(error == expected_error); 8 assert(full_name == expected_full_name); 9 } 10 11 CheckFullName("Doug Adams", "Mr. Douglas Adams", ""); 12 CheckFullName(" Jake Brown ", "Mr. Jake Brown III", ""); 13 CheckFullName("No Such Guy", "", "no match found"); 14 CheckFullName("John", "", "more than one result");
儘管目的僅僅是讓程式碼更有美感,但是還產生了幾個附帶的效果
(1)消除了程式碼中的重複,使之變得更緊湊
(2)每個測試用例重要的部分都變得更直白
(3)新增新的測試更加簡單