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