將子問題抽離,讓function專注在處理問題本身上面,首先要先了解這個function的"目的",接著抽離與"目的"無關的子問題,將這些子問題一一寫成獨立的function,如:(簡單說就主程式專注在邏輯上,細節部分就一一寫成sub 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; }; 抽離後的code var 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) * }; 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; };抽離這些子問題的另一個好處容易優化,比如有更好的方式去運算spherical_distance()或是變更findClosestLocation()的運算邏輯。建立通用的function也是一個很好也很重要的習慣,當你開發一個新的program時,就可以運用這些通用function,快速建立一個prototype。
Simplifying an Existing Interface & Reshaping an Interface to Your Needs
如果既有的API不好用,那就包裝他或改寫他吧,我在A Wrap for service/thread也包裝了一些API,讓自己易於開發,有必要也會進行Reshaping/Re-factor等等步驟。- 參考資料:
- The Art of Readable Code
沒有留言:
張貼留言