1,尽快结束if语句
例如下面这个JavaScript语句,看起来就很恐怖:
function findShape(flags, point, attribute, list) {
if(!findShapePoints(flags, point, attribute)) {
if(!doFindShapePoints(flags, point, attribute)) {
if(!findInShape(flags, point, attribute)) {
if(!findFromGuide(flags,point) {
; if(list.count() > 0 && flags == 1) {
doSomething();
; }
}
}
; }
}
}
但如果这么写就好看得多:
function findShape(flags, point, attribute, list) {
if(findShapePoints(flags, point, attribute)) {
return;
}
if(doFindShapePoints(flags, point, attribute)) {
return;
}
if(findInShape(flags, point, attribute)) {
; return;
}
if(findFromGuide(flags,point) {
return;
}
if (!(list.count() > 0 && flags == 1)) {
return;
}
doSomething();
}
你可能会很不喜欢第二种的表述方式,但它反映出了迅速返回if值的思想,也可以理解为:避免不必要的else陈述.
2.如果只是简单的布尔运算(逻辑运算),不要使用if语句.
例如:
function isStringEmpty(str){
if(str === "") {
return true;
}else {
return false;
}
}
可以写为:
function isStringEmpty(str){
return (str === "");
}
3.合理利用空行
例如:
function getSomeAngle() {
radAngle1 = Math.atan(slope(center, point1));
radAngle2 = Math.atan(slope(center, point2));
firstAngle = getStartAngle(radAngle1, point1, center);
secondAngle = getStartAngle(radAngle2, point2, center);
radAngle1 = degreesToRadians(firstAngle);
radAngle2 = degreesToRadians(secondAngle);
baseRadius = distance(point, center);
radius = baseRadius + (lines * y);
p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
}
很多开发者不愿意使用空白,就好像这要收费一样。我在此并非刻意地添加空白,粗鲁地打断代码的连贯性。
在实际编写代码的过程中,会很容易地发现在什么地方加入空白,这不但美观而且让读者易懂,如下:
function getSomeAngle() {
radAngle1 = Math.atan(slope(center, point1));
radAngle2 = Math.atan(slope(center, point2));
firstAngle = getStartAngle(radAngle1, point1, center);
secondAngle = getStartAngle(radAngle2, point2, center);
radAngle1 = degreesToRadians(firstAngle);
radAngle2 = degreesToRadians(secondAngle);
baseRadius = distance(point, center);
radius = baseRadius + (lines * y);
p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
}
4.不要在源文件中留下已经删除的代码,哪怕你标注了.
如果你使用了版本控制,那么你就可以轻松地找回前一个版本的代码。
如果别人大费周折地读了你的代码,却发现是要删除的代码,这实在太气人了。
//function thisReallyHandyFunction() {
// someMagic();
// someMoreMagic();
// magicNumber = evenMoreMagic();
// return magicNumber;
//}
5,不要写没有意义的注释.
为程序编写注释固然是个好习惯,但没有必要的注释 就非常令人厌恶。
function existsStudent(id, list) {
for(i = 0; i < list.length; i++) {
; student = list[i];
; //获取student的id
; thisId = student.getId();
; if(thisId === id) {
return true;
; }
}
return false;
}
如上代码所示,每个人都知道下面那句话是获取 student 的id。
6, 尽量不要有太长的代码.
原创文章如转载请注明:转载自心诺设计风尚 xvdesign.com 欢迎订阅心诺设计风尚
本文链接:http://xvdesign.com/post/72.html [复制链接]
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。