优秀代码命名法
有人说过写代码就像弹棉花(^_^),不好意思,说错了,是弹piano。我觉得写代码就像写文章,文章写出来是要给人看的(不排除自lian型),词不达意,肯定不是好文章。能做到信达雅,那都是高高手。“金山银山就是绿水青山”,抬头看看这高度!
只有好文章才能被收录(like upstream Linux kernel),rt? 再看看老外金句:
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
In the beginning was the Word, and the Word was with God, and the Word was God.
The Gospel According to John
言论:
A good name paints a picture in the mind of the reader.
Names are the structure we impose on the formless sea of bits that is computing.
When I’m designing software, I spend a lot of time thinking about names. For me, thinking about names is inseparable from the process of design.
OK,指南开始:
一. 忽略那些变量类型词汇或参数类型词汇 (for static typeing)
In Static Typing, type checking is performed during compile time. It means that the type of a variable is known at compile time. For some languages, the programmer must specify what type each variable is (e.g C, C++, Java)
比如变量:
/* Bad */ |
对于收集类描述,可以用复数取代单数:
/* Bad */ |
如果关心收集的内容,命名应该反映出来,e.g.:
erofs: clean up `enum z_erofs_collectmode' |
函数的命名有提到:
The method name doesn’t need to describe its parameters or their types—the parameter list does that for you.
也要看情况,比如Kernel/VFS:
int (*read_folio)(struct file *, struct folio *); |
二. 忽略那些无关或歧义词汇
the name is an identifier: it points you to where it’s defined. It’s not an exhaustive catalog of everything the reader could want to know about the object.
如果太短有冲突,可以增加qualifiers。
/* Bad */ |
三. 忽略那些上下文已知词汇
A method or field occurs in the context of a class
A variable occurs in the context of a method (or function)
int load_cluster_from_disk(param) |
四. 忽略那些没有意义的词汇
通常有嫌疑的:
data, state, amount, value, manager, engine, object, entity, and instance
多问问自己:
“Would this identifier mean the same thing if I removed the word?”
如果是的,那这个词就没意义。
五. 只有把业务想清楚了,才能说得简单准确
比如 kmap_local()
的出现,linus 的一段答复:
On Sat, Sep 19, 2020 at 2:50 AM Thomas Gleixner tglx@linutronix.de wrote:
>
> this provides a preemptible variant of kmap_atomic & related
> interfaces. This is achieved by:Ack. This looks really nice, even apart from the new capability.
The only thing I really reacted to is that the name doesn’t make sense
to me: “kmap_temporary()” seems a bit odd.Particularly for an interface that really is basically meant as a
better replacement of “kmap_atomic()” (but is perhaps also a better
replacement for “kmap()”).I think I understand how the name came about: I think the “temporary”
is there as a distinction from the “longterm” regular kmap(). So I
think it makes some sense from an internal implementation angle, but I
don’t think it makes a lot of sense from an interface name.I don’t know what might be a better name, but if we want to emphasize
that it’s thread-private and a one-off, maybe “local” would be a
better naming, and make it distinct from the “global” nature of the
old kmap() interface?
我们再加上英语不是母语。。。
BTW: 命名不够具体的,用象征(metaphor)代替,并保持一致。
/* Bad */ |
Refer
版权声明:本站所有文章均采用 CC BY-NC-SA 4.0 CN 许可协议。转载请注明原文链接!