当前位置:网站首页>编码用这16个命名规则能让你少写一半以上的注释!
编码用这16个命名规则能让你少写一半以上的注释!
2022-07-28 19:26:00 【InfoQ】
前言
规则1:保持命名形式的一致性
Imageimagepicture- 对于产品层面的实体对象:建议是前后端、数据表都统一实体对象名称;
- 对于各自语言的一些特定的对象或组件,建议开发团队统一实体对象命名规则。
- 不要创造新名词!也许你看得懂,但不代表别人看得懂。
- **不要使用拼音,更不要使用拼音缩写!**中文翻译成英文的时候,挑简单易懂的词汇。
// 正确示例
pageCount // 表示页数的字段
updatePageCount() // 与 pageCount 名称保持一致
toSomething() // 与 Iterable 的 toList() 的写法一致
asSomething() // 与 List 的 toMap() 写法一致
Point // 用户习惯用语
// 错误示例
renumberPages() // 与 pageCount 名称没有一致
convertToSomething() // 与通常的 toX()不一致
wrappedAsSomething() // 与通常的 asX() 不一致
Cartesian // 不是用户的习惯用语
规则2:避免缩写
// 正确示例
pageCount
buildRectangles
IOStream
HttpRequest
// 错误示例
numPages // num 缩写不合适
buildRects // Rects 缩写很难和 Rectangles 对应
InputOutputStream // 没有使用简单易懂的缩写
HypertextTransferProtocolRequest // 没有使用简单易懂的缩写
规则3:将描述事物最准确的名词放在最后
// 正确示例
pageCount // 页码的数量(count)
ConversionSink // 用于转换的 sink
ChunkedConversionSink // 一个chunked 的 Conversation Sink
CssFontFaceRule // CSS 中字体规则(rule)
// 错误示例
numPages // 并不是 pages 的集合
CanvasRenderingContext2D // 并不是 2D 对象
RuleFontFaceCss // 并不是 CSS
规则4:让代码像语句一样连贯
// 正确示例
if (errors.isEmpty) ...
subscription.cancel();
monsters.where((monster) => monster.hasClaws);
// 是清空 error 还是盘点 errors 是不是空?
if (errors.empty) ...
// 反转什么?反转后是什么状态?
subscription.toggle();
// 是过滤包含的还是不包含满足条件的?
monsters.filter((monster) => monster.hasClaws);
// 错误示例
if (theCollectionOfErrors.isEmpty) ...
monsters.producesANewSequenceWhereEach((monster) => monster.hasClaws);
规则5:对于非布尔类型的属性或变量使用名词
// 正确示例
list.length
context.lineWidth
quest.rampagingSwampBeast
sortedList
// 错误示例
list.deleteItems
sortList
规则6:对于代表可执行某类操作布尔属性,优先使用能动词
// 正确示例
if (widget.canUpdate) ...
if (window.canClose) ...
if (container.hasElements) ...
if (request.shouldResume) ...
// 错误示例
if (widget.updatable) ...
if (window.closeable) ...
if (container.withElements) ...
if (request.resumable) ...
规则7:对于布尔类型的参数,不要使用动词
// 正确示例
Isolate.spawn(entryPoint, message, paused: false);
var copy = List.from(elements, growable: true);
var regExp = RegExp(pattern, caseSensitive: false);
规则8:对于布尔型属性和变量,应该使用正向名称
isNotEmpty = true
// 正确示例
bool isEmpty;
// 错误示例
bool isNotEmpty;

// 错误示例
bool isAdult;
if (! isAdult) {
return 'Not Allowed for Non Adults'.
}
// 正确示例
bool isNotAdult;
if (isNotAdult) {
return 'Not Allowed for Non Adults'.
}
规则10:使用祈使动词来命名函数或那些产生其他效果的方法
// 正确示例
list.add('element');
queue.removeFirst();
controller.forward();
refreshController.loadMore();
规则11:对于主要目的是返回一个值的函数优先使用名词或非祈使动词
// 正确示例
var element = list.elementAt(3);
var first = list.firstWhere(test);
var char = string.codeUnitAt(4);
规则12:不要在方法名称开头加 get
getgetBreakfastOrdergetterbreakfastOrder- 如果调用者更关系返回值,那么可以直接去掉 get,使用名词作为方法名词,例如
breakfastOrder(),或者使用规则11。
- 如果调用这关心这个方法做什么事情,那么可以用更精确的描述动词,例如 create、download、fetch、calculate、request 等等。
规则13:如果方法是将一个对象复制成为另一种表现形式,那么使用 toX() 形式
toJsontoStringtoSettoLocal规则14:如果返回的是原对象的不同的表现形式,那么使用 asX() 形式
if ((object as String) == 'a') {
...
}
var map = table.asMap();
var list = bytes.asFloat32List();
var future = subscription.asFuture();
规则15:不要在方法名称上重复参数名
// 正确示例
list.add(element);
map.remove(key);
// 错误示例
list.addElement(element)
map.removeKey(key)
// 正确示例
map.containsKey(key);
map.containsValue(value);
规则16:对于泛型,遵循通用的助记符
- E:表示集合类的泛型参数,例如:
class IterableBase<E> {}
class List<E> {}
class HashSet<E> {}
class RedBlackTree<E> {}
- K和 V表示 key 和 value 泛型参数,例如:
class Map<K, V> {}
class Multimap<K, V> {}
class MapEntry<K, V> {}
- R 表示返回值泛型参数,例如:
abstract class ExpressionVisitor<R> {
R visitBinary(BinaryExpression node);
R visitLiteral(LiteralExpression node);
R visitUnary(UnaryExpression node);
}
- 其他情况,通常使用 T、S 和 U 来标识泛型,实际中如果能够有助于理解,也可以使用单词(首字母大写)作为泛型参数,下面的3个例子都是没问题的。
class Future<T> {
Future<S> then<S>(FutureOr<S> onValue(T value)) => ...
}
class Graph<N, E> {
final List<N> nodes = [];
final List<E> edges = [];
}
class Graph<Node, Edge> {
final List<Node> nodes = [];
final List<Edge> edges = [];
}
总结
边栏推荐
- How does lazada store make up orders efficiently? (detailed technical explanation of evaluation self-supporting number)
- Baklib | why do enterprises need to pay attention to customer experience?
- C language function program example (super complete)
- Redis缓存雪崩、缓存穿透、缓存击穿
- EfficientFormer:轻量化ViT Backbone
- 承载银行关键应用的容器云平台如何选型及建设?
- 小程序容器技术,让移动研发效率提升500%
- ctfshow 做题 web模块 web11~web14
- 1945. 字符串转化后的各位数字之和
- Maxwell 一款简单易上手的实时抓取Mysql数据的软件
猜你喜欢

Reading and writing basic data types in protobuf

C language function program example (super complete)

quii cordova-plugin-telerik-imagepicker插件多图上传乱序
![[cloud native] what is ci/cd| Ci/cd to smooth delivery obstacles](/img/4f/e7806d75cd719e181d8455e4fdc1e7.jpg)
[cloud native] what is ci/cd| Ci/cd to smooth delivery obstacles

MobileViT:挑战MobileNet端侧霸主

(转)冒泡排序及优化详解

EfficientFormer:轻量化ViT Backbone

Interesting pictures and words

【周周有奖】云原生编程挑战赛“边缘容器”赛道邀你来战!

DeiT:注意力Attention也能蒸馏
随机推荐
蓝队入门之效率工具篇
智能家居行业发展,密切关注边缘计算和小程序容器技术
DeiT:注意力Attention也能蒸馏
A 58 year old native of Anhui Province, he has become the largest IPO investor in Switzerland this year
【周周有奖】云原生编程挑战赛“边缘容器”赛道邀你来战!
What is low code? Which platforms are suitable for business personnel? Is it reliable to develop the system?
uniapp的进度条自定义
MoCo V2:MoCo系列再升级
source insight 使用快捷键
Unity - Fundamentals of 3D mathematics
protobuf 中基础数据类型的读写
查询oracle视图创建语句及如何向视图中插入数据[通俗易懂]
什么是低代码?哪些平台适合业务人员?用来开发系统靠不靠谱?
Maxwell is an easy-to-use software for capturing MySQL data in real time
1 Introduction to command mode
dll反编译(反编译加密dll)
Confusing knowledge points of software designer examination
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
Unity - script lifecycle
C # basic 3-value type and reference type, packing and unpacking