当前位置: 主页> 官网活动>

写出好看代码的七种办法

时间:2012-02-06 14:18 点击:

结尾我想申明我本文说明的是纯朴从美学的角度来写出代码,而非技艺、逻辑等。以下为写出好看代码的七种想法: 1, 尽快终结 if语句 比如下面这个JavaScript语句,看起来就很可骇:1 function findShape(flags, point, attribute, list) {2 if(!findShapePoints(flags, point, attribute)) {3 if(!doFindShapePoints(flags, point, attribute)) {4 if(!findInShape(flags, point, attribute)) {5 if(!findFromGuide(flags,point) {6 if(list.count() > 0 && flags == 1) {7 doSomething();8 }9 }10 }11 }12 } 13 } 但假使这么写就悦目得多:1 function findShape(flags, point, attribute, list) {2 if(findShapePoints(flags, point, attribute)) {3 return;4 }5 6 if(doFindShapePoints(flags, point, attribute)) {7 return;8 }9 10 if(findInShape(flags, point, attribute)) { 11 return;12 }13 14 if(findFromGuide(flags,point) {15 return;16 }17 18 if (!(list.count() > 0 && flags == 1)) {19 return;20 }21 22 doSomething();23 24 } 你大概会很不喜欢第二种的表述格式,但相应出了快速返回if值的思想,也可以理解为:制止不须要的else论述。 2, 倘使不外粗略的布尔运算(逻辑运算),不要应用if语句 譬喻:1 function isStringEmpty(str){2 if(str === "") { 3 return true;4 }5 else {6 return false;7 }8 }可以写为:1 function isStringEmpty(str){2 return (str === "");3 } 3, 应用空缺,这是免费的 譬喻:1 function getSomeAngle() {2 // Some code here then3 radAngle1 = Math.atan(slope(center, point1));4 radAngle2 = Math.atan(slope(center, point2));5 firstAngle = getStartAngle(radAngle1, point1, center);6 secondAngle = getStartAngle(radAngle2, point2, center);7 radAngle1 = degreesToRadians(firstAngle);8 radAngle2 = degreesToRadians(secondAngle);9 baseRadius = distance(point, center);10 radius = baseRadius + (lines * y);11 p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);12 p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);13 pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);14 pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");15 // Now some more code16 } 很多开垦者不情愿利用空缺,就宛如这要收费一律。我在此并非克意地增添空缺,鲁莽地打断代码的连贯性。在现实编写代码的经过中,会很方便地发目前什么场地参加空缺,这不但都雅而且让读者易懂,如下: 1 function getSomeAngle() {2 // Some code here then3 radAngle1 = Math.atan(slope(center, point1));4 radAngle2 = Math.atan(slope(center, point2));5 6 firstAngle = getStartAngle(radAngle1, point1, center);7 secondAngle = getStartAngle(radAngle2, point2, center);8 9 radAngle1 = degreesToRadians(firstAngle);10 radAngle2 = degreesToRadians(secondAngle);11 12 baseRadius = distance(point, center);13 radius = baseRadius + (lines * y);14 15 p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);16 p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);17 18 pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);19 pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");20 // Now some more code21 }


(转载请注明出处:http://www.125521.net/guanwanghuodong/20120206/2349.html)
------分隔线----------------------------
推荐内容