代码中的表达式越长,它就越难理解。本章看看各种操作和拆分代码以使它们更容易理解的方法。
1. 用做解释的变量
if line.split(':')[0].strip() == "root": -- username 为解释变量 username = line.split(':')[0].strip() if username == "root":
2. 总结变量
1 if (request.user.id == document.owner_id) { 2 // user can edit this document... 3 } 4 if (request.user.id != document.owner_id) { 5 // document is read-only... 6 } 7 8 // user_owns_document 为总结变量,它使得表达更加清楚 9 final boolean user_owns_document = (request.user.id == document.owner_id); 10 if (user_owns_document) { 11 // user can edit this document... 12 } 13 if (!user_owns_document) { 14 // document is read-only... 15 }
3. 使用摩根定理
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.");
4. 不要滥用短路逻辑
1 assert((!(bucket = FindBucket(key))) || !bucket->IsOccupied()); 2 3 // 以下方式更易懂 4 bucket = FindBucket(key); 5 if (bucket != NULL) assert(!bucket->IsOccupied());
5. 找到更优雅的方式
OverlapsWith() 反方向是不重叠
1 bool Range::OverlapsWith(Range other) { 2 if (other.end <= begin) return false; // They end before we begin 3 if (other.begin >= end) return false; // They begin after we end 4 return true; // Only possibility left: they overlap 5 }
6. 简化表达
1 void AddStats(const Stats& add_from, Stats* add_to) { 2 add_to->set_total_memory(add_from.total_memory() + add_to->total_memory()); 3 add_to->set_free_memory(add_from.free_memory() + add_to->free_memory()); 4 add_to->set_swap_memory(add_from.swap_memory() + add_to->swap_memory()); 5 add_to->set_status_string(add_from.status_string() + add_to->status_string()); 6 add_to->set_num_processes(add_from.num_processes() + add_to->num_processes()); 7 //... 8 } 9 10 void AddStats(const Stats& add_from, Stats* add_to) { 11 #define ADD_FIELD(field) add_to->set_##field(add_from.field() + add_to->field()) 12 ADD_FIELD(total_memory); 13 ADD_FIELD(free_memory); 14 ADD_FIELD(swap_memory); 15 ADD_FIELD(status_string); 16 ADD_FIELD(num_processes); 17 //... 18 #undef ADD_FIELD 19 }