写出漂亮代码的七种方法

本文从美学角度探讨如何编写优雅简洁的代码,提供了七个实用技巧,包括简化if语句、避免无用注释及合理使用空白等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先我想说明我本文阐述的是纯粹从美学的角度来写出代码,而非技术、逻辑等。以下为写出漂亮代码的七种方法:
  h- N' w+ u: j: [3 L
! _& v" J1 K- t5 h5 a* C: C1, 尽快结束 if语句7 k% q! A( d7 d4 i6 r* x
( L1 K8 Y0 T6 t# W) R7 Z* v8 I
例如下面这个JavaScript语句,看起来就很恐怖:; x0 A$ j. @7 h- w/ g$ s

' D; x4 q0 v/ ~1 G8 ]5 m3 x% I1 function findShape(flags, point, attribute, list) {$ _+ P) t: r/ Q% n- E! L
2    if(!findShapePoints(flags, point, attribute)) {
9 I' |: |4 n7 N% n& L5 B3        if(!doFindShapePoints(flags, point, attribute)) {
& ?2 x5 e) S$ f7 n4            if(!findInShape(flags, point, attribute)) {
$ D1 W( D: [9 p8 C5                if(!findFromGuide(flags,point) {$ @7 a! w; f* j! n) o0 b& ^# t1 h
6                    if(list.count() > 0 && flags == 1) {" M) z3 j! N! q- _
7                          doSomething();: q/ U; _7 h7 G8 V
8                    }
# Z- _( /6 b$ q- f, k- e$ Y2 }9                }
3 g0 ]) K" P( O2 Z7 v0 f10            }$ o! c  D! p, p: C+ T
11       }" u; K3 {, U  [, S2 `* x5 _& A
12    }  , /# e' b# P4 E$ ?, D
13  }
* L1 J: ?6 G3 h" O. i- M
- R, Q! y  |- `5 M  r但如果这么写就好看得多:
* S0 M! k. _$ A* w8 i1 function findShape(flags, point, attribute, list) {4 Y- n3 G9 l; b, s5 k
2    if(findShapePoints(flags, point, attribute)) {. l6 D6 g5 K, Y, ~( V) ~
3        return;+ Z$ P% e. [9 O3 }" p
4    }3 K- f: L# P4 A: G2 t
57 J$ {5 O. W9 B" z% v  W' ^' G
6    if(doFindShapePoints(flags, point, attribute)) {$ K* l; g9 L! k! O. C
7        return;
+ f' N0 `' _  |3 _# X2 V8    }, C; F: L( v! r+ [8 m
9' u% E! S& z8 /7 P
10    if(findInShape(flags, point, attribute)) {
, j: z7 r) /7 v$ @1 o3 k; F) n0 I: ^11        return;
& k; W: `+ a/ `! ^12    }2 /5 l8 _+ X7 _  H* }! x  S) A
13
! |; ~  i" u0 K0 ]5 _0 }14    if(findFromGuide(flags,point) {! s+ v9 Q$ _  z/ y4 |& [3 Y, ], S
15        return;
# d) z/ U, N8 ?+ Q16    }
) ^* }* h2 q$ Z% x1 S9 I8 u2 s171 t$ k: f: c+ y7 W2 g0 o
18    if (!(list.count() > 0 && flags == 1)) {; S* a* x3 B* [' i% |* A
19        return;
: C. d5 Q, t; t! D6 U20    }
8 k- c6 O9 l1 w3 D" P- z1 l21  {2 [" {  C% H
22    doSomething();2 A* _( }/ n/ S  ]  P- ^* ^
23
/ s" V% p" [, H2 K- ^: l24 }8 a7 l4 }( ~7 H0 F# i

- U+ x6 i* [8 P  A. X! G你可能会很不喜欢第二种的表述方式,但反映出了迅速返回if值的思想,也可以理解为:避免不必要的else陈述。
  f; q4 I( u3 H! z
% H; F6 [& I5 X( D2, 如果只是简单的布尔运算(逻辑运算),不要使用if语句
, x6 `. G, ~! ]" C' K) v3 g7 u
, f) _, t' i: p1 _5 i例如:% o8 U3 N# {6 R
1 function isStringEmpty(str){+ _4 g2 C( o! ], Z: H# j
2    if(str === "") {5 G7 f6 F+ O0 l. a9 H$ /
3        return true;; /2 l6 X  ?* L$ q0 X
4    }
, w  V* l5 G- d. k& |* }5    else {, I: U1 c0 a% L# X" ~! m: T
6        return false;: ^7 b5 r0 D" X* Q. m! {0 S
7    }
( n% S. Y7 n4 D8 }
% t& g/ M% s9 k/ J- ^
4 C. L1 G. o6 p6 H( Q, X2 t* a" Q可以写为:
. {# k, g& t- /( D' C5 B1 function isStringEmpty(str){
% @" P' z# b- o1 W3 Y. Q8 v2    return (str === "");- m! i" A" ^) Q3 G/ B3 H
3 }. ?" R) y# k) _/ ?+ i/ R
# @) R, H7 X$ A0 U' c
3, 使用空白,这是免费的' |7 i9 D5 Y, ]# K0 l% _; ~" k& [
例如:4 U& U4 {& T- h5 h; ?* x+ j  K
1 function getSomeAngle() {* @+ W( Z/ ~* R  c& z
2    // Some code here then
- a6 ^% _# t# q9 Q+ X# h! b% ~3    radAngle1 = Math.atan(slope(center, point1));; I0 t  A1 s6 R- O* U
4    radAngle2 = Math.atan(slope(center, point2));. {1 F. c# V9 l& a" d7 Q" [/ L
5    firstAngle = getStartAngle(radAngle1, point1, center);- f" j$ o6 s5 _* [# i5 V
6    secondAngle = getStartAngle(radAngle2, point2, center);
3 }# n7 L$ ]" C+ d! |7    radAngle1 = degreesToRadians(firstAngle);- f" o  _# g9 o: g1 q
8    radAngle2 = degreesToRadians(secondAngle);  n% `, {3 w3 ~4 S# j6 D
9    baseRadius = distance(point, center);- x2 U0 m: R+ g$ v) @! M
10    radius = baseRadius + (lines * y);: M: ?$ D3 b7 Q; {# I: ^1 [
11    p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);& {/ h. R5 e2 d' F0 g: I6 R
12    p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
1 h  ~: C* C* ?% x13    pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);  h6 v" o" X5 I8 a
14    pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
" b" _- N" Z- V& ?$ e; G' b15    // Now some more code
4 r: j& k4 R9 |( N  _16 }3 M. w7 L( `9 R& W. x& |+ c

# B1 m; q1 q3 p5 t; t* e; e3 _很多开发者不愿意使用空白,就好像这要收费一样。我在此并非刻意地添加空白,粗鲁地打断代码的连贯性。在实际编写代码的过程中,会很容易地发现在什么地方加入空白,这不但美观而且让读者易懂,如下:
7 j, x5 ^; e( @, J# G# C1 function getSomeAngle() {
4 y8 H5 v4 P6 P# _/ Z0 s7 y2    // Some code here then* U; Z7 }7 m5 l: U
3    radAngle1 = Math.atan(slope(center, point1));
0 G/ m" o1 V7 V" Q4    radAngle2 = Math.atan(slope(center, point2));
3 N' t, y; x1 @, R+ J  Q2 s5
# ~- ]1 A5 b  g( ~6    firstAngle = getStartAngle(radAngle1, point1, center);' b! x: o; _" _: Q0 J$ _6 {, V
7    secondAngle = getStartAngle(radAngle2, point2, center);! W% j8 V. o: N& {
8
4 M4 A/ Z) a7 r" h9 D5 m9    radAngle1 = degreesToRadians(firstAngle);$ p0 G% G$ t: r! w
10    radAngle2 = degreesToRadians(secondAngle);
1 j: g4 V4 b$ L2 g, Q2 H11
6 h' S/ V% y4 `12    baseRadius = distance(point, center);
* ?8 ^" B2 N. a0 b0 ?13    radius = baseRadius + (lines * y);8 f$ }- I2 {4 s' V
14
  e: q  X6 v: f5 O15    p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
  x' `* T  {( j5 F4 B16    p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
4 F$ w& H4 I/ d17
& d5 O) a$ Y: q/ d8 V  m18    pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);& z6 }4 O) s3 q* b8 L9 }
19    pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");& M8 N+ `6 v  M6 /5 I3 i
20    // Now some more code# b# F1 K5 }9 ~" I7 }3 c8 o! d
21 }5 j' F3 h+ d1 C. W- m. _
. G5 ~5 }; t$ v  Q
4, 不要使用无谓的注释
! w, k( k7 t0 E* h' _+ q) H无谓的注释让人费神,这实在很讨厌。不要标出很明显的注释。在以下的例子中,每个人都知道代码表达的是“students id”,因而没必要标出。- S' G3 ^# ~/ @6 t" K
1 function existsStudent(id, list) {/ i' |5 F6 `9 U/ K+ a
2    for(i = 0; i < list.length; i++) {
: b- `# @. t5 f  C: Q. v" r: ?- c6 |# C3       student = list[i];( T- V* o9 ^$ I% h& z( {( k4 F) A
4% z  w0 Z# O. g
5       // Get the student's id
7 w6 K' /' H. _: P, s6       thisId = student.getId();6 v6 h& g" N" l. o4 S
76 U' ?% y! W' Z* P* C
8       if(thisId === id) {
: N6 s% b& [4 m1 t9           return true;
: P9 o& Y# C" n7 f- |* p- p6 T9 j$ E10       }6 ^' T0 f8 G3 x9 /
11    }" m- `6 t; t* s
12    return false;  
% R6 P5 l4 B; m( n4 ^0 S13 }
( b/ a  e+ `$ r: Y6 I+ F; c  g; a, ]4 e+ t- N" T8 i" ]) }& ?+ t
5, 不要在源文件中留下已经删除的代码,哪怕你标注了8 U+ z3 t; W2 |$ U
如果你使用了版本控制,那么你就可以轻松地找回前一个版本的代码。如果别人大费周折地读了你的代码,却发现是要删除的代码,这实在太恨人了。; g" O, h4 y; w* [
9 /0 u3 c3 m3 o. ]3 u! f2 X
//function thisReallyHandyFunction() {
% i( V9 h% j+ d& |. H$ b, z//      someMagic();9 /) _4 d+ f, Z1 q7 J
//      someMoreMagic();
5 B' Q6 K4 N( u//      magicNumber = evenMoreMagic();! P# A- i% N7 u- K/ r
//      return magicNumber;
# e4 y6 @9 D6 ~8 ]* e//}3 r: b1 B# c2 @  N' Q

4 j. B3 p5 c. H: y6,不要有太长的代码& a7 s5 u: c% |; L) /" _

2 K! y  u, J) e. c1 D/ ?; _看太长的代码实在太费劲,尤其是代码本身的功能又很小。如下:
5 P+ t& l: M5 V& ?. Q1 T2 H, M+ }# U0 v' J: S
1 public static EnumMap<Category, IntPair> getGroupCategoryDistribution(EnumMap<Category, Integer> sizes, int groups) {
8 n4 {" a' I# m2 |8 @2        EnumMap<Category, IntPair> categoryGroupCounts = new EnumMap<Category,IntPair>(Category.class);7 V" f5 Q$ U: ~
3
* L% J! F2 V# @2 ?# P3 l4        for(Category cat : Category.values()) {
* P. t) N2 `# Y* ~3 n" n5            categoryGroupCounts.put(cat, getCategoryDistribution(sizes.get(cat), groups));
1 P. v  ?  Y) a% o# k& t. ]6        }- h2 J0 t/ Q/ v% D4 ]
* ^' `8 K, z  g
#' p& h: h0 p( L

. o$ f. {% R5 U7 W. V  F5 z! S我并不是说非要坚持70个字符以内,但是一个比较理想的长度是控制在120个字符内。如果你把代码发布在互联网上,用户读起来就很困难。
- P: g8 b# u$ h( @7 t1 W8 G7,不要在一个功能(或者函数内)有太多代码行' X! |- j: L1 {, S/ z; C
我的一个老同事曾经说Visual C++很臭,因为它不允许你在一个函数内拥有超过10,000行代码。我记不清代码行数的上限,不知道他说的是否正确,但我很不赞成他的观点。如果一个函 数超过了50行,看起来有多费劲你知道么,还有没完没了的if循环,而且你还的滚动鼠标前后对照这段代码。对我而言,超过35行的代码理解起来就很困难 了。我的建议是超过这个数字就把一个函数代码分割成两个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值