关闭

写出漂亮代码的七种方法

发表于:2008-12-17 15:01

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:CSDN

  首先我想说明我本文阐述的是纯粹从美学的角度来写出代码,而非技术、逻辑等。以下为写出漂亮代码的七种方法:

  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陈述。

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号