Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The Art Of Readable Code

13,530 views

Published on

The Art Of Readable Code

  1. 1. The Art of Readable Code Simple and Practical Techniques for Writing Better Code
  2. 2. Code Should Be Easy to Understand
  3. 3. for (Node* node = list->head; 
 node != NULL; 
 node = node->next) {
 Print(node->data);
 } Node* node = list->head; if (node == NULL) return; while (node->next != NULL) { Print(node->data); node = node->next; } if (node != NULL) { Print(node->data); }
  4. 4. (_=[_=[]][(_+!![])[$=(!!_/!!_)]+(!!$+_)[-~-~$]+'v'+(! (_/_)+[])[-~-~$]+(!([]/($))+[])[$]+([]+!_)[-~-~$]+(!! {}+[])[-~-~$]])()[(!({}+_)+_)[$]+(!({}+[])+[])[-~$]+ ((''+!![]+''))[-~-~$]+(!![]+'')[$]+((!!_+[]))[$-$]]($/ $); alert(1)
  5. 5. Key Idea • Code should be easy to understand. • Minimize the time it would take for someone else to understand it.
  6. 6. Is Smaller Always Better?
  7. 7. Conflict with Other Goals? Easy to Test Well-Architected Code Efficient Highly Maintainable …
  8. 8. Three Levels • Surface Level • Loops & Logic • Reorganizing
  9. 9. Surface-Level
  10. 10. Packing Information into Names
  11. 11. • Specific • Avoid Generic Names • Prefer Concrete Names • Extra Information • Length vs Meaning • Formatting
  12. 12. Word Alternative send deliver, dispatch, announce, distribute, route find search, extract, locate, recover start launch, create, begin, open make create, set up, build, generate, compose, add, new
  13. 13. Naming Conventions • Noun for variable name, object name, class name, property name, arguments name • Verb for function name, method name
  14. 14. Case maptypeCtrl.streetMapMgr(true); A Better One maptypeCtrl.showStreetMap();
  15. 15. Length • Shorter names for shorter scopes • Longer names for larger scopes
  16. 16. Names That Can’t Be Misconstrued
  17. 17. Key Idea • Asking yourself, “What other meanings could someone interpret from this name?”
  18. 18. • Prefer min and max for(inclusive) limits • Naming booleans • Matching expectations of Users
  19. 19. Case var read_password = true; A Better One var need_password = true; var user_authenticated = true;
  20. 20. Case map.getBestMap(points); A Better One map.setViewport(points);
  21. 21. Aesthetic
  22. 22. Aesthetic • Use consistent layout. • Make similar code look similar. • Group related lines of code into blocks.
  23. 23. Knowing What to Comment
  24. 24. Key Idea • The purpose of commenting is to help the reader know as much as the writer did.
  25. 25. What NOT to Comment • KEY IDEA:Don’t comment on the facts that can be derived quickly from the code itself
  26. 26. Case ! // 延时关闭信息窗⼝口 setTimeout(function(){ map.closeInfoWindow(); }, 100);
  27. 27. Case ! // 添加为全局对象;
 window.mapSubway = me;
  28. 28. Recording Your Thoughts • Include “Director Commentary” • Comment the Flaws in Your Code • Comment on Your Constants
  29. 29. Put Yourself in the Reader’s Shoes • Anticipating Likely Questions • Advertising Likely Pitfalls • “Big Picture” • Summary
  30. 30. Precise & Compact Comments
  31. 31. • Keep Comments Compact • Describe Function Behavior Precisely • Use Examples • State the Intent
  32. 32. Case // 返回⽂文件⾏行数
 int CountLines(string filename) {...} A Better One // 计算换⾏行符'n'的个数
 int CountLines(string filename) {...}
  33. 33. Case if (mode == var a = b = minutes "bustime") {
 minutes % 10, 
 parseInt(minutes / 10);
 = a != 0 ? 
 (a > 5 ? 
 (++b * 10) : b ?
 (b * 10) : 5): 
 minutes; Need Examples!
  34. 34. Loops & Logic
  35. 35. Making Control Flow Easy to Read
  36. 36. KEY IDEA • Make your logic as “natural” as possible
  37. 37. Case if (length >= 10) if (10 <= length) while (bytes_received < bytes_expected) while (bytes_expected > bytes_received)
  38. 38. Order of if/else Blocks • Positive First • Simpler First • Interesting First
  39. 39. ?: Conditional Expression • Often Less Readable
  40. 40. KEY IDEA • Minimize the time needed for someone to understand it instead of minimizing the number of lines.
  41. 41. ADVICE • Use ternary ?: only for the simplest cases.
  42. 42. • Avoid do/while Loops • Returning Early form a Function • Minimize Nesting • Flow of Execution
  43. 43. Breaking Down Giant Expressions
  44. 44. • Explaining Variables • Summary Variables • Use De Morgan’s Laws • Break Down Giant Statements
  45. 45. Case if (line.split(':')[0] == 'admin') var userName = line.split(':')[0];
 if (userName == 'admin')
  46. 46. Case if (navigator.userAgent.indexOf('UC') > -1) if (navigator.userAgent.indexOf('UC') == -1) var isUC = navigator.userAgent.indexOf('UC') > -1; if (isUC) if (!isUC)
  47. 47. Case var update_highlight = function (message_num) { if ($("#vote_value" + message_num).html() === "Up") { $("#thumbs_up" + message_num).addClass("highlighted"); $("#thumbs_down" + message_num).removeClass("highlighted"); } else if ($("#vote_value" + message_num).html() === "Down") { $("#thumbs_up" + message_num).removeClass("highlighted"); $("#thumbs_down" + message_num).addClass("highlighted"); } else { $("#thumbs_up" + message_num).removeClass("highighted"); $("#thumbs_down" + message_num).removeClass("highlighted"); } };
  48. 48. var update_highlight = function (message_num) { var thumbs_up = $("#thumbs_up" + message_num); var thumbs_down = $("#thumbs_down" + message_num); var vote_value = $("#vote_value" + message_num).html(); var hi = "highlighted"; 
 if (vote_value === "Up") { thumbs_up.addClass(hi); thumbs_down.removeClass(hi); } else if (vote_value === "Down") { thumbs_up.removeClass(hi); thumbs_down.addClass(hi); } else { thumbs_up.removeClass(hi); thumbs_down.removeClass(hi); } };
  49. 49. Variables
  50. 50. Problems • More variables, harder to keep track of them • Bigger variable’s scope, longer you have to keep track of them • More often variable changes, harder to keep track of its current value
  51. 51. Eliminating Variables • Useless Temporary Variables • Eliminating Intermediate Results • Eliminating Control Flow Variables
  52. 52. Case var remove_one = function(array, value_to_remove) {
 var index_to_remove = null;
 for (var i = 0; i < array.length; i ++) {
 if (array[i] === value_to_remove) {
 index_to_remove = i;
 break;
 }
 }
 if (index_to_remove !== null) {
 array.slice(index_to_remove, 1);
 }
 }
  53. 53. Case var remove_one = function(array, value_to_remove) {
 for (var i = 0; i < array.length; i ++) {
 if (array[i] === value_to_remove) {
 array.slice(i, 1);
 return;
 }
 }
 }
  54. 54. Shrink the Scope • Make variable visible by as few lines of code as possible.
  55. 55. Prefer write-once variables • KEY IDEA: The more places a variable is manipulated, the harder it is to reason about its current value.
  56. 56. Reorganizing
  57. 57. Extracting Unrelated Subproblems
  58. 58. Case function findClosestLocation(latLng, latLngs) {
 var closest;
 var closest_dist = Number.MAX_VALUE;
 
 for each latlng in latLngs, calculate the
 distance, if new distance is shorter than 
 current, set closest to the new latlng
 
 
 return closest;
 }
  59. 59. What is the unrelated subproblem? Compute the spherical distance
  60. 60. • Pure Utility Code • General-Purpose Code • Project-Specific Functionality • Simplifying an Existing Interface
  61. 61. Case Cookie setCookie(key, value); getCookie(key); deleteCookie(key); hasCookie(key);
  62. 62. Further Reading
  63. 63. One Task at a Time
  64. 64. KEY IDEA • Code should be organized so that it’s doing only one task at a time.
  65. 65. Turning Thoughts into Code
  66. 66. • Describe what code needs to do, in plain English(we should use Chinese) • Pay attention to key words and phrases • Write your code to match description
  67. 67. Case $is_admin = is_admin_request();
 if ($document) {
 if (!$is_admin 
 && ($document['username']) != $_SESSION['username'])){
 return not_authorized();
 }
 } else {
 if (!$is_admin) {
 return not_authorized();
 }
 }
 
 // continue rendering the page ...
  68. 68. Case if (is_admin_request()) {
 // authorized
 } elseif ($document 
 && $document['username']) != 
 $_SESSION['username'])) {
 // authorized 
 } else {
 return not_authorized();
 }
 
 // continue rendering the page ...
  69. 69. Writing Less Code
  70. 70. KEY IDEA • The most readable code is NO CODE AT ALL
  71. 71. Case • Calculating Distance Between Two Locations
  72. 72. • Don’t implement code that you won’t need • Simplify requirements • Keep your codebase small • Be familiar with Libraries around you
  73. 73. Further Reading
  74. 74. Further Reading
  75. 75. Further Reading
  76. 76. Q&A

×