当前位置:网站首页>Coding with these 16 naming rules can save you more than half of your comments!
Coding with these 16 naming rules can save you more than half of your comments!
2022-07-28 21:17:00 【InfoQ】
Preface
The rules 1: Keep the naming form consistent
Imageimagepicture- For product level entity objects : The suggestion is front and rear 、 All data tables have unified entity object names ;
- For some specific objects or components of their respective languages , It is suggested that the development team unify the naming rules of entity objects .
- Don't create new terms ! Maybe you can understand , But it doesn't mean others can understand .
- ** Don't use Pinyin , Don't use pinyin abbreviations !** When translating Chinese into English , Pick words that are easy to understand .
// The correct sample
pageCount // A field representing the number of pages
updatePageCount() // And pageCount Keep the names the same
toSomething() // And Iterable Of toList() It's written in the same way
asSomething() // And List Of toMap() In the same way
Point // User idioms
// The wrong sample
renumberPages() // And pageCount The names are not consistent
convertToSomething() // With the usual toX() atypism
wrappedAsSomething() // With the usual asX() atypism
Cartesian // Not a user idiom
The rules 2: Avoid abbreviations
// The correct sample
pageCount
buildRectangles
IOStream
HttpRequest
// The wrong sample
numPages // num Abbreviations are not appropriate
buildRects // Rects Abbreviations are hard to match Rectangles Corresponding
InputOutputStream // No easy to understand abbreviations
HypertextTransferProtocolRequest // No easy to understand abbreviations
The rules 3: Put the most accurate noun to describe things at the end
// The correct sample
pageCount // Number of pages (count)
ConversionSink // For conversion sink
ChunkedConversionSink // One chunked Of Conversation Sink
CssFontFaceRule // CSS Font rules in (rule)
// The wrong sample
numPages // Not at all pages Set
CanvasRenderingContext2D // Not at all 2D object
RuleFontFaceCss // Not at all CSS
The rules 4: Make the code as coherent as a statement
// The correct sample
if (errors.isEmpty) ...
subscription.cancel();
monsters.where((monster) => monster.hasClaws);
// It's emptying error Or inventory errors Is it empty ?
if (errors.empty) ...
// Reverse what ? What is the state after reversal ?
subscription.toggle();
// Whether to filter the included or not ?
monsters.filter((monster) => monster.hasClaws);
// The wrong sample
if (theCollectionOfErrors.isEmpty) ...
monsters.producesANewSequenceWhereEach((monster) => monster.hasClaws);
The rules 5: Use nouns for non Boolean attributes or variables
// The correct sample
list.length
context.lineWidth
quest.rampagingSwampBeast
sortedList
// The wrong sample
list.deleteItems
sortList
The rules 6: For Boolean attributes that represent certain types of operations that can be performed , Give priority to active words
// The correct sample
if (widget.canUpdate) ...
if (window.canClose) ...
if (container.hasElements) ...
if (request.shouldResume) ...
// The wrong sample
if (widget.updatable) ...
if (window.closeable) ...
if (container.withElements) ...
if (request.resumable) ...
The rules 7: For boolean type parameters , Don't use verbs
// The correct sample
Isolate.spawn(entryPoint, message, paused: false);
var copy = List.from(elements, growable: true);
var regExp = RegExp(pattern, caseSensitive: false);
The rules 8: For Boolean attributes and variables , Positive names should be used
isNotEmpty = true
// The correct sample
bool isEmpty;
// The wrong sample
bool isNotEmpty;

// The wrong sample
bool isAdult;
if (! isAdult) {
return 'Not Allowed for Non Adults'.
}
// The correct sample
bool isNotAdult;
if (isNotAdult) {
return 'Not Allowed for Non Adults'.
}
The rules 10: Use imperative verbs to name functions or methods that produce other effects
// The correct sample
list.add('element');
queue.removeFirst();
controller.forward();
refreshController.loadMore();
The rules 11: For functions whose main purpose is to return a value, nouns or non imperative verbs are preferred
// The correct sample
var element = list.elementAt(3);
var first = list.firstWhere(test);
var char = string.codeUnitAt(4);
The rules 12: Do not start the method name with get
getgetBreakfastOrdergetterbreakfastOrder- The caller of the relationship returns the value if , Then it can be removed directly get, Use nouns as method nouns , for example
breakfastOrder(), Or use rules 11.
- If you call this method, you care what the method does , Then you can use a more precise description of Verbs , for example create、download、fetch、calculate、request wait .
The rules 13: If the method is to copy an object into another representation , So use toX() form
toJsontoStringtoSettoLocalThe rules 14: If you return a different representation of the original object , So use asX() form
if ((object as String) == 'a') {
...
}
var map = table.asMap();
var list = bytes.asFloat32List();
var future = subscription.asFuture();
The rules 15: Do not repeat the parameter name on the method name
// The correct sample
list.add(element);
map.remove(key);
// The wrong sample
list.addElement(element)
map.removeKey(key)
// The correct sample
map.containsKey(key);
map.containsValue(value);
The rules 16: For generics , Follow the general mnemonic
- E: Represents the generic parameter of the collection class , for example :
class IterableBase<E> {}
class List<E> {}
class HashSet<E> {}
class RedBlackTree<E> {}
- K and V Express key and value The generic parameter , for example :
class Map<K, V> {}
class Multimap<K, V> {}
class MapEntry<K, V> {}
- R A generic parameter that represents a return value , for example :
abstract class ExpressionVisitor<R> {
R visitBinary(BinaryExpression node);
R visitLiteral(LiteralExpression node);
R visitUnary(UnaryExpression node);
}
- Other situations , Usually use T、S and U To identify generics , In practice, if it can help to understand , You can also use the word ( title case ) As a generic parameter , Below 3 There are no problems .
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 = [];
}
summary
边栏推荐
- Moco V2: further upgrade of Moco series
- C # detailed steps for connecting to MySQL database
- C#连接MySql数据库详细步骤
- Bug of Dom4j
- Is it necessary to disconnect all connections before deleting the PostgreSQL database?
- MobileViT:挑战MobileNet端侧霸主
- mfc wpf winform(工业用mfc还是qt)
- Introduction to singleton mode
- Observer mode, object pool
- How to modify the ID of NetApp expansion enclosure disk shelf
猜你喜欢

Moco V3: visual self supervision ushers in transformer

Redis cache avalanche, cache penetration, cache breakdown

How does lazada store make up orders efficiently? (detailed technical explanation of evaluation self-supporting number)

Unity3d tutorial notes - unity initial 04

Nacos principle

Backup and recovery of SQL Server database

DELTA热金属检测器维修V5G-JC-R1激光测量传感器/检测仪原理分析

【云原生】什么是 CI/CD ? | 摆平交付障碍的 CI/CD

Cobal Strike的学习与使用

Maxwell is an easy-to-use software for capturing MySQL data in real time
随机推荐
2 enjoy yuan mode
ICML2022 | 时序自监督视频transformer
SQL server中提示对象名无效
微服务架构下的系统集成
上市1个月接连发生两起安全事故,理想L9还理想吗?
mysql还有哪些自带的函数呢?别到处找了,看这个就够了。
Jiuxin intelligence officially joined opengauss community
1945. 字符串转化后的各位数字之和
ntp服务器 时间(查看服务器时间)
什么是 CI/CD? | 实现更快更好的软件交付
分页功能(板子)
Efficientformer: lightweight vit backbone
C language function program example (super complete)
MoCo V1:视觉领域也能自监督啦
The EMC vnx5200 fault light is on, but there is no hardware fault prompt
4.1 Member的各种调用方式
It is not only convenient, safe + intelligent, but also beautiful. Fluorite releases the Big Dipper face lock dl30f and Aurora face video lock y3000fv
Go并发编程基础
【题目】两数相加
Link with Bracket Sequence I(状态基多维dp)