How do I reorganize my code to improve readability? (function plane, part 3)
1. Extracting code unrelated to the main problem
2. Reorganize your code so that you do one thing at a time
3. Describe the function first and then implement the function so that it is clearer
How to extract problems unrelated to the problem? (Chap 10)
0. Consideration of irrelevant issues
-See a function or a block of code and ask yourself, "What is the high-level role of this code (high-level Gloal)"
-For each line of code, think "is it a direct solution to this goal", or "solve a sub-problem to achieve the goal of resolution"
-If you are solving a sub-problem and the number of lines of code is sufficient, then you can extract a separate function
Return which element of ' array ' is closest to the given latitude/longitude.//Models the Earth as a perfect sphere.var Findclosestlocation = function (lat, LNG, array) {var closest; var closest_dist = Number.MAX_VALUE; for (var i = 0; i < array.length; i + = 1) {//Convert both points to radians. var Lat_rad = radians (LAT); var Lng_rad = radians (LNG); var Lat2_rad = radians (array[i].latitude); var Lng2_rad = radians (array[i].longitude); Use the ' spherical law of cosines ' formula. var dist = Math.acos (Math.sin (Lat_rad) * Math.sin (Lat2_rad) + math.cos (lat_rad) * MATH.COS (Lat2_rad) * Math.Cos (Lng2_rad-lng_rad)); if (Dist < closest_dist) {closest = Array[i]; Closest_dist = dist; }} return closest;};/ /Good:clear, easy-to-test spherical_distance in Isolationvar spherical_distance = function (LAT1, lng1, LAT2, lng2) { var Lat1_rad = radians (lAT1); var Lng1_rad = radians (lng1); var Lat2_rad = radians (LAT2); var Lng2_rad = radians (lng2); Use the ' spherical law of cosines ' formula. Return Math.acos (Math.sin (Lat1_rad) * Math.sin (Lat2_rad) + math.cos (lat1_rad) * MATH.COS (Lat2_rad) * Math.Cos (Lng2_rad-lng1_rad));}; var findclosestlocation = function (lat, LNG, array) {var closest; var closest_dist = Number.MAX_VALUE; for (var i = 0; i < array.length; i + = 1) {var dist = spherical_distance (lat, LNG, Array[i].latitude, Array[i]. longitude); if (Dist < closest_dist) {closest = Array[i]; Closest_dist = dist; }} return closest;};
* Pure Utility code (such as Operation string, hash table, read-write file)
Such code is best encapsulated in a separate Util class or function, (readfiletostring ())
* Other common code
Ajax_post ({url: ' http://example.com/submit ', Data:data, On_success:function (response_data) {var str = "{\ n"; for (var key in response_data) {str + = "+ key +" = "+ Response_data[key] +" \ n "; } alert (str + "}"); });} Continue handling ' response_data ' ...//good: function name easier to locate, easier to maintain var format_pretty = function (obj) {var str = "{\ n"; for (var key in obj) {str + = "+ key +" = "+ Obj[key] +" \ n "; } return str + "}";};/ /Better: more powerful var format_pretty = function (obj, indent) {//Handle null, Undefined, strings, and non-objects. if (obj = = = null) return "NULL"; if (obj = = = undefined) return "undefined"; if (typeof obj = = = = "string") return ' "' + obj + '"; if (typeof obj!== "Object") return String (obj); if (indent = = = undefined) indent = ""; Handle (Non-null) objects. var str = "{\ n"; for (var key in obj) {str + = indent + "+ key +" = "; str + = Format_pretty (Obj[key], indent + "") + "\ n"; } return str + indent + "}";};
* code that creates more common functionality
, like the previous readfiletostring (), Format_pretty () can boast that the project uses their
* Engineering-specific features (even so, You can still consider creating a Util class/function that is used within the project
* Simplify the existing interface (use a third-party library, its interface is not good, you can consider encapsulating it)
-Simplifying an existing interface
-Reshaping an interface to your needs
-don't take things too far (do not divide a function implementation into too many small functions, control granularity)
strong> only one thing at a time (chap, one task at a)
0. A code snippet that only does a single thing (blank line style code snippet)
Example 1
Bad:two things doing together (Parsevalue, computescore) var vote_changed = function (Old_vote, new_vote) { var sc Ore = Get_score (); if (new_vote!== old_vote) { if (new_vote = = = ' up ') { score + = (Old_vote = = = ' Down '? 2:1); } else if (New_v OTE = = = ' Down ') { score-= (Old_vote = = = ' Up '? 2:1); } else if (new_vote = = = ") { score + = (Old_vote = = =) Up '? -1:1); } } Set_score (score);};/ /good:clear to Understandvar Vote_value = function (vote) { if (vote = = = ' up ') { return +1; } if (vote = = = ' Down ') { return-1; } return 0;}; var vote_changed = function (Old_vote, new_vote) { var score = Get_score (); Score-= Vote_value (old_vote); Remove the old vote score + = Vote_value (new_vote);//Add the new vote Set_score (score);};
Example 2
Bad: Inconvenient to expand var place = location_info["Localityname"]; e.g. "Santa Monica" if (!place) {place = location_info["Subadministrativeareaname"];//e.g. "Los Angeles"}if (!plac E) {place = location_info["Administrativeareaname"],//e.g. "California"}if (!place) {place = "middle-of-nowhere" ;} if (location_info["CountryName"]) {place + = "," + location_info["CountryName"]; e.g. "USA"} else {place + = ", Planet Earth";} Return place;//Goodvar town = location_info["Localityname"]; e.g. "Santa Monica" var city = location_info["Subadministrativeareaname"]; e.g. "Los Angeles" var state = location_info["Administrativeareaname"]; e.g. "CA" var country = location_info["CountryName"]; e.g. "USA"//Start with the default, and keep overwriting with the most specific value.var second_half = "Planet Earth"; if (cou ntry) {second_half = country;} if (state && country = = = "USA") {second_half = state;} var first_half = "Middle-of-nowhere"; if (state && Country!== "USA") {first_half = state;} if (city) {first_half = city;} if (town) {first_half = town;} return first_half + "," + second_half;//Better: a| with JS syntax | b| | C's characteristic var first_half, second_half;if (country = = = "USA") {first_half = Town | | | | | "Middle-of-nowhere"; Second_half = State | | "USA";} else {first_half = Town | | "Middle-of-nowhere"; Second_half = Country | | "Planet Earth";} return first_half + "," + second_half;
Reading notes of the Art of readable Code Part 3