正文

[转]国际:写出漂亮代码的七种方法2008-12-17 12:51:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/lym51/39953.html

分享到:

首先我想说明我本文阐述的是纯粹从美学的角度来写出代码,而非技术、逻辑等。以下为写出漂亮代码的七种方法: 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 then 3    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 code 16 } 很多开发者不愿意使用空白,就好像这要收费一样。我在此并非刻意地添加空白,粗鲁地打断代码的连贯性。在实际编写代码的过程中,会很容易地发现在什么地方加入空白,这不但美观而且让读者易懂,如下: 1 function getSomeAngle() { 2    // Some code here then 3    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 code 21 } 4, 不要使用无谓的注释 无谓的注释让人费神,这实在很讨厌。不要标出很明显的注释。在以下的例子中,每个人都知道代码表达的是“students id”,因而没必要标出。 1 function existsStudent(id, list) { 2    for(i = 0; i < list.length; i++) { 3       student = list[i]; 4 5       // Get the student's id 6       thisId = student.getId(); 7 8       if(thisId === id) { 9           return true; 10       } 11    } 12    return false;   13 } 5, 不要在源文件中留下已经删除的代码,哪怕你标注了 如果你使用了版本控制,那么你就可以轻松地找回前一个版本的代码。如果别人大费周折地读了你的代码后却发现是要删除的代码,这实在太恨人了。 //function thisReallyHandyFunction() { //      someMagic(); //      someMoreMagic(); //      magicNumber = evenMoreMagic(); //      return magicNumber; //} 6,不要有太长的代码 看太长的代码实在太费劲,尤其是代码本身的功能又很小。如下: 1 public static EnumMap<Category, IntPair> getGroupCategoryDistribution(EnumMap<Category, Integer> sizes, int groups) { 2        EnumMap<Category, IntPair> categoryGroupCounts = new EnumMap<Category,IntPair>(Category.class); 3 4        for(Category cat : Category.values()) { 5            categoryGroupCounts.put(cat, getCategoryDistribution(sizes.get(cat), groups)); 6        } # 我并不是说非要坚持70个字符以内,但是一个比较理想的长度是控制在120个字符内。如果你把代码发布在互联网上,用户读起来就很困难。 7,不要在一个功能(或者函数内)有太多代码行 我的一个老同事曾经说Visual C++很臭,因为它不允许你在一个函数内拥有超过10,000行代码。我记不清代码行数的上限,不知道他说的是否正确,但我很不赞成他的观点。如果一个函数超过了50行,看起来有多费劲你知道么,还有没完没了的if循环,而且你还的滚动鼠标前后对照这段代码。对我而言,超过35行的代码理解起来就很困难了。我的建议是超过这个数字就把一个函数代码分割成两个。

阅读(1598) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册