《The Practice of Programming》-Chapter1 Style(Learning Notes)

第一章:风格

It is an old observation that the best writers sometimes disregard the
rules of rhetoric. When they do so, however, the reader will usually
find in the sentence some compensating merit, attained at the cost of
the violation. Unless he is certain of doing so well, he will probably
do best to follow the rules.
William Strunk & E.B.White, The elements of Style

编程风格的原则基于经验指导的共识:

代码应该清晰而简单,straightforward logic, natural expression, conventional
language use, meaningful names, neat formatting, helpful comments.
避免聪明的小把戏和不常见的结构。
一致性非常重要。

  1. Names 变量名

A name should be informative, concise, memorable and pronounceable if
possible.
Use descriptive names for globals, short names for locals.


全局变量

  1. 全局变量名需要具有足够的长度和描述性来提醒读者它们的意义。一句简洁的注释有时候也很必要。
  2. Global functions, classes and structures should also have descriptive names that suggest their role in a program. (不能图快怕麻烦,一个好的命名,对于后期修改代码非常重要)

局部变量

  1. 命名越简短越高效。比如在一个函数中,n已经够用了,npoints 马马虎虎,numberOfPoints就过分了。
    某些使用超级简短变量名的例子:循环里使用i和j, 指针使用p和q, 字符串使用s 和t,等等。

有些程序员会忽略上下文,给变量取很长的名字。这样是不可取的。记住:

Clarity is often achieved through brevity.

有很多命名传统,例如变量名:

  1. 以p开头或者结束,指针nodep;
  2. 首字母为大写;
  3. 所有字母大写;

The longer the program, the more important is the choice of good, descriptive, systematic names.

一致性

  1. Give related things related names that show their relationship and highlight
    their difference.
  2. Only one term should be used for a single concept.

用主动动词给函数命名

Function names should be based on active verbs, perhaps followed by nouns.(octal:八进制)
使用if(isoctal(c))
而不是if(checkoctal(c))

准确性

A name not only labels, it conveys information to the reader. A misleading name can result in mystifying bugs.

  1. 表达与陈述

通过类比来选择名称,有助于读者的理解。
在操作符左右留下空格以提示组别。
格式化有利于可读性。

(这些都是微不足道的,但却很有价值,就好像你保持桌子的整洁以方便自己找东西。不同的是,别人查看你代码的可能性比查看你桌面的可能性更大。)

使用缩进来展示结构

具有一致性的缩进风格可以使得程序具有结构性。

使用表达的自然形式

Write expressions as you might speak them aloud. 你怎么读,就怎么写。

用括号括起来解决歧义

When mixing unrelated operators, though, it’s a good idea to parenthesize.(尤其是当涉及到优先级不同的符号时,使用括号尤其有用)

清楚

编程的目标是写出清楚的代码,而不是聪明的代码。
Clarity is not the same as brevity.
简洁的代码会更短,例如位移的情况;也能更长,例如条件语句中的情况。这个边界的准则是程序的易读性。
(不要过分追求短的代码。越短越好 。优秀的程序不在长短,而在可读性的好坏。)

小心副作用

比如,++有副作用:不仅返回一个值,还会修改这个变量。
可以说, 副作用能带来极大的便捷,也能带来极大的麻烦,因为返回值的操作与更新变量可能不会同时发生。
I/O也有副作用。如果对一个变量r进行修改的时候,程序的其他部分要使用r,那么这段程序就会崩溃。不管使用哪种编程语言,这个问题都是一样的。

  1. 一致性和惯用语法

if the same computation is done the same way every time it appears,
any variation suggests a genuine difference, one worth noting. 如果相同的计算每次出现的形式一样,那么出现变化的时候就是计算真正有差异的地方。

使用一致的缩进和括号风格
缩进展示风格。不管你喜欢哪种风格,都可以。最重要的是你在整个程序中能够保持贯彻这种风格。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值