erlang各种有用的函数包括一些有用nif封装,还有一些性能测试case。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1159 regels
36 KiB

5 jaren geleden
  1. Erlang 编码标准指引
  2. ====================================
  3. Table of Contents:
  4. * [约定 & 规则](#约定--规则)
  5. * [源码布局](#源码布局)
  6. * [用空格代替制表符(tab)](#用空格代替制表符(tab))
  7. * [使用你的空格键](#使用你的空格键)
  8. * [行尾不要留空格](#行尾不要留空格)
  9. * [每行100列](#每行100列)
  10. * [保持现有风格](#保持现有风格)
  11. * [避免多层嵌套](#避免多层嵌套)
  12. * [更多, 小函数比 case 表达式好用](#更多-小函数比-case-表达式好用)
  13. * [函数按逻辑功能分组](#函数按逻辑功能分组)
  14. * [集中你的 types](#集中你的-types)
  15. * [不要上帝模块](#不要上帝模块)
  16. * [Honor DRY](#抽象重复代码)
  17. * [避免动态调用](#避免动态调用)
  18. * [语法](#语法)
  19. * [避免使用 if 表达式](#避免使用-if-表达式)
  20. * [避免嵌套 try...catches](#避免嵌套try...catches)
  21. * [命名](#命名)
  22. * [在命名概念时保持一致](#在命名概念时保持一致)
  23. * [Don't use _Ignored variables](#不要使用匿名变量)
  24. * [避免用布尔类型作为函数参数](#避免用布尔类型原子作为函数参数)
  25. * [原子(atoms)请用小写](#原子(atoms)请用小写)
  26. * [函数名](#函数名)
  27. * [变量名](#变量名)
  28. * [](#宏)
  29. * [宏的应用场景](#宏的应用场景)
  30. * [宏名要大写](#宏名要大写)
  31. * [记录(Records)](#记录(Records))
  32. * [记录命名](#记录命名)
  33. * [在 specs 里避免出现记录(record)](#在specs里避免出现记录)
  34. * [给记录添加类型Types](#给记录添加类型Types)
  35. * [其它](#其它)
  36. * [给函数添加-spec函数规范定义](#给函数添加-spec函数规范定义)
  37. * [模块中不要用import](#模块中不要用import)
  38. * [Don't Use Case Catch](#Don't Use Case Catch)
  39. * [好的建议和方法](#好的建议和方法)
  40. * [优先使用高级函数而不是手写的递归方法](#优先使用高级函数而不是手写的递归方法)
  41. * [驼峰式命名,下划线命名](#驼峰式命名,下划线命名)
  42. * [更短 (但仍保持有意义的) 的变量名称](#更短(但仍保持有意义的)的变量名称 )
  43. * [注释等级](#注释等级)
  44. * [保持函数精简](#保持函数精简)
  45. * [避免不必要调用length/1](#避免不必要调用length/1 )
  46. ### 约定--规则
  47. ### 源码布局
  48. #### 用空格代替制表符(tab)
  49. > 用空格代替制表符(tab),使用两个空格符作为缩进.
  50. *Examples*: [indent](src/indent.erl)
  51. ```erlang
  52. %% @doc 不一致
  53. bad() ->
  54. try
  55. ThisBlock = is:indented(with, two, spaces),
  56. that:is_good(ThisBlock) %% 这一部分的代码缩进用两个空格,没啥毛病
  57. catch
  58. _:_ ->
  59. this_block:is_indented(with, four, spaces) %% 但是这一部分的却用了4个空格,看起来不统一,很糟糕
  60. end.
  61. %% @doc 一致,但是使用4个空格
  62. better() ->
  63. receive
  64. {this, block} -> is:indented(with, four, spaces);
  65. _That -> is:not_good() %% 这一部分的代码缩进用四个空格,不太好
  66. after 100 ->
  67. but:at_least(it, is, consistent) %% 但起码全部是使用一致的风格
  68. end.
  69. %% @doc 不错
  70. good() ->
  71. case indentation:block() of
  72. {2, spaces} -> me:gusta();
  73. {_, _} -> not_sure:if_gusta()
  74. end.
  75. ```
  76. *原因*: 这并不意味着允许代码中存在多层嵌套的结构.如果代码足够干净,2个空格就足够了,代码看起来更加简洁,同时在同一行中也能容纳更多的字符.
  77. ***
  78. #### 使用你的空格键
  79. > 使用空格来分割开运算符和逗号.
  80. *Examples*: [spaces](src/spaces.erl)
  81. ```erlang
  82. % @doc 没有空格
  83. bad(_My,_Space,_Bar)->[is,'not',working].
  84. % @doc 带空格!!
  85. good(_Hey, _Now, _It) -> ["works " ++ "again, " | [hooray]].
  86. ```
  87. *原因*: 同上,主要是为了代码易于读写,等等. 在这里顺便提醒一下erlang宏展开的时候会自动在两边增加分隔符
  88. *Examples*: -define(plus,+).
  89. t(A,B) -> A?plus+B.
  90. 结果会是这样的:
  91. t(A,B) -> A + + B.
  92. 而不是这样的:
  93. t(A,B) -> A ++ B.
  94. ***
  95. #### 行尾不要留空格
  96. > 检查你的没一行代码的最后,不要有空格.
  97. *Examples*: [trailing_whitespace](src/trailing_whitespace.erl)
  98. ```erlang
  99. bad() -> "这行尾部有空格".
  100. good() -> "这行没有".
  101. ```
  102. *原因*: 这是提交噪音. 可以看看[长篇论据](https://programmers.stackexchange.com/questions/121555/why-is-trailing-whitespace-a-big-deal).
  103. #### 每行100列
  104. > 每行最多100个字符.
  105. *Examples*: [col_width](src/col_width.erl)
  106. ```erlang
  107. %$ @doc 太宽
  108. bad([#rec{field1 = FF1, field2 = FF2,
  109. field3 = FF3}, #rec{field1 = BF1, field2 = BF2, field3 = BF3} | Rest], Arg2) ->
  110. other_module:bad(FF1, FF2, FF3, BF1, BF2, BF3, bad(Rest, Arg2)).
  111. %% @doc 不错 (< 100 字符)
  112. good([Foo, Bar | Rest], Arg2) ->
  113. #rec{field1 = FF1, field2 = FF2, field3 = FF3} = Foo,
  114. #rec{field1 = BF1, field2 = BF2, field3 = BF3} = Bar,
  115. other_module:good(FF1, FF2, FF3, BF1, BF2, BF3, good(Rest, Arg2)).
  116. ```
  117. *原因*:太长的行在处理的时候是相当痛苦的: 要么在编辑的时候不停水平滚动, 要么就是忍受自动断行造成布局错乱.
  118. 100个字符的限制不仅仅让每一行保持简短, 另外也能让你可以毫无压力地在标准的手提电脑屏幕上并排同时打开两个文件, 或者三个 1080p 显示器上.
  119. ***
  120. #### 保持现有风格
  121. > 当你维护别人的模块时, 请坚持按前人的编码风格样式维护. 如果项目有整体的风格样式, 那么在编写新的模块是也要坚持按项目的整体风格进行.
  122. *Examples*: [existing_style](src/existing_style.erl)
  123. ```erlang
  124. bad() ->
  125. % 之前的代码
  126. List = [ {elem1, 1}
  127. , {elem2, 2}
  128. % 新代码 (不按之前的格式来编码)
  129. , {elem3, 3}, {elem4, 4},
  130. {elem5, 5}
  131. ],
  132. other_module:call(List).
  133. good() ->
  134. % 之前的代码
  135. List = [ {elem1, 1}
  136. , {elem2, 2}
  137. % 新代码 (按之前的格式来编码)
  138. , {elem3, 3}
  139. , {elem4, 4}
  140. , {elem5, 5}
  141. ],
  142. other_module:call(List).
  143. ```
  144. *原因*: 在维护别人的代码的时候,如果你不喜欢他的编码规范,这仅仅是你个人不喜欢而已,但是如果你不按他之前写的编码样式继续编写,
  145. 那这个模块就有两种编码样式了,这样你本人看起来这些代码很丑陋,别人看你的代码也觉得很丑陋,这样会让代码更加不容易维护.
  146. ***
  147. #### 避免多层嵌套
  148. > 尽量不要出现超过三个层级嵌套的代码样式
  149. *Examples*: [nesting](src/nesting.erl)
  150. ```erlang
  151. bad() ->
  152. case this:function() of
  153. has ->
  154. try too:much() of
  155. nested ->
  156. receive
  157. structures ->
  158. it:should_be(refactored);
  159. into ->
  160. several:other(functions)
  161. end
  162. catch
  163. _:_ ->
  164. dont:you("think?")
  165. end;
  166. _ ->
  167. i:do()
  168. end.
  169. good() ->
  170. case this:function() of
  171. calls ->
  172. other:functions();
  173. that ->
  174. try do:the(internal, parts) of
  175. what ->
  176. was:done(in)
  177. catch
  178. _:the ->
  179. previous:example()
  180. end
  181. end.
  182. %% 译者注: 上面部分代码的意思:通过将嵌套部分的代码封装成一些新的函数,可以减少嵌套的结构.
  183. ```
  184. *原因*: 嵌套级别表示函数中的逻辑比较复杂,过多地将需要执行和完成的决策放在单个函数中. 这不仅阻碍了可读性,而且阻碍了可维护性,如果嵌套过多梳理逻辑
  185. 分支代码也很容易看错拆分成相应的函数可读性更好,逻辑也会更清晰,也便于调试以及编写单元测试的进行,
  186. ***
  187. #### 更多-小函数比-case-表达式好用
  188. > 使用模式匹配的函数子句代替 case 表达式. 特别是当 case 在:
  189. > - 函数的开头(下面代码第一个bad函数)
  190. > - case分支比较多的时候
  191. *Examples*: [smaller_functions](src/smaller_functions.erl)
  192. ```erlang
  193. %% @doc 这个函数仅仅使用的是 case 表达式
  194. bad(Arg) ->
  195. case Arg of
  196. this_one -> should:be(a, function, clause); %% 这一句应该用一个函数子句代替
  197. and_this_one -> should:be(another, function, clause) %% 这一句应该用另一个函数子句代替
  198. end.
  199. %% @doc 使用模式匹配
  200. good(this_one) -> is:a(function, clause); %% 这是一个函数子句
  201. good(and_this_one) -> is:another(function, clause). %% 这是另一个函数子句
  202. %% @doc case 表达式在函数内部
  203. bad() ->
  204. InitialArg = some:initial_arg(),
  205. InternalResult =
  206. case InitialArg of
  207. this_one -> should:be(a, function, clause);
  208. and_this_one -> should:be(another, function, clause)
  209. end,
  210. some:modification(InternalResult).
  211. %% @doc 使用多个函数字句代替内部 case 表达式
  212. good() ->
  213. InitialArg = some:initial_arg(),
  214. InternalResult = good(InitialArg),
  215. some:modification(InternalResult).
  216. ```
  217. *原因:* 一般而言,函数体中的一个case代表某种决定,同时函数应尽可能的简单. 如果决策结果的每个分支作为一个函数子句而不是一个case子句来实现,
  218. 同时函数子句的函数名也可以让代码容易读懂. 换言之, 这个 case 在此扮演的是 '匿名函数', 除非它们在高阶函数的上下文中被使用,而只是模糊的含义.
  219. ***
  220. #### 函数按逻辑功能分组
  221. > 始终保持区分导出函数和未导出的函数, 并将导出的放在前面, 除非还有其他方法更加有助于可读性和代码发现的.
  222. *Examples*: [grouping_functions](src/grouping_functions)
  223. `bad.erl`:
  224. ```erlang
  225. %%% @doc 私有和公用函数随意摆放
  226. -module(bad).
  227. -export([public1/0, public2/0]).
  228. public1() -> private3(atom1).
  229. private1() -> atom2.
  230. public2() -> private2(private1()).
  231. private2(Atom) -> private3(Atom).
  232. private3(Atom) -> Atom.
  233. ```
  234. `better.erl`:
  235. ```erlang
  236. %%% @doc 按函数相关程度区分组
  237. -module(better).
  238. -export([public1/0, public2/0]).
  239. public1() ->
  240. case application:get_env(atom_for_public_1) of
  241. {ok, X} -> public1(X);
  242. _ -> throw(cant_do)
  243. end.
  244. %% @doc 这是一个仅仅与上面函数相关的私有函数
  245. public1(X) -> private3(X).
  246. public2() -> private2(private1()).
  247. private1() -> atom2.
  248. private2(Atom) -> private3(Atom).
  249. private3(Atom) -> Atom.
  250. ```
  251. `good.erl`:
  252. ```erlang
  253. -module(good).
  254. -export([public1/0, public2/0]).
  255. public1() ->
  256. case application:get_env(atom_for_public_1) of
  257. {ok, X} -> private3(X);
  258. _ -> throw(cant_do)
  259. end.
  260. public2() -> private2(private1()).
  261. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PRIVATE FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  262. private1() -> atom2.
  263. private2(Atom) -> private3(Atom).
  264. private3(Atom) -> Atom.
  265. ```
  266. *原因*: 好的代码结构易于读/理解/修改,很多时候在写erlang代码的时候写着写着发现需要添加一些额外的分支匹配函数,
  267. 有时候这种分支匹配函数就为了某种情况下使用,有可能就用一次,这时候我的习惯就是把这个分支匹配函数写在要用这个函数的函数前面
  268. ***
  269. #### 集中你的 types
  270. > 将 types 都放在文件开头的地方
  271. *Examples*: [type_placement](src/type_placement.erl)
  272. ```erlang
  273. -type good_type() :: 1..3.
  274. -spec good() -> good_type().
  275. good() -> 2.
  276. -type bad_type() :: 1..3.
  277. -spec bad() -> bad_type().
  278. bad() -> 2.
  279. ```
  280. *原因*: Types 定义的数据结构极有可能被用于多个函数,所以他们的定义不能只与其中一个有关.
  281. 另外将他们在代码中放在一起并像文档一样展示他们就像edoc 也是将 types 放在每个文档的开头一样.
  282. ***
  283. #### 不要上帝模块
  284. > 不要让你的系统使用上帝模块 (模块中包含了很多函数 和/或 函数与函数之间处理的事情并不相关)
  285. *Examples*: [god](src/god.erl)
  286. ```erlang
  287. %%% @doc all of your db operations belong to us!
  288. -module(god).
  289. -export([create_user/1, create_user/2, create_user/3]).
  290. -export([update_user/2, update_user/3]).
  291. -export([delete_user/1]).
  292. -export([create_post/1, create_post/2, create_post/3]).
  293. -export([update_post/2, update_post/3]).
  294. -export([delete_post/1]).
  295. -export([create_comment/2, create_comment/3]).
  296. -export([update_comment/3, update_comment/4]).
  297. -export([delete_comment/2]).
  298. create_user(Name) -> create_user(Name, undefined).
  299. create_user(Name, Email) -> create_user(Name, Email, undefined).
  300. create_user(Name, Email, Phone) ->
  301. some_db:insert(users, [{name, Name}, {email, Email}, {phone, Phone}]).
  302. update_user(Name, Changes) ->
  303. some_db:update(users, [{name, Name}], Changes).
  304. update_user(Name, Key, Value) ->
  305. update_user(Name, [{Key, Value}]).
  306. delete_user(Name) ->
  307. some_db:delete(users, [{name, Name}]).
  308. create_post(Text) -> create_post(Text, undefined).
  309. create_post(Text, Title) -> create_post(Text, Title, undefined).
  310. create_post(Text, Title, Image) ->
  311. some_db:insert(posts, [{text, Text}, {title, Title}, {image, Image}]).
  312. update_post(Text, Changes) ->
  313. some_db:update(posts, [{text, Text}], Changes).
  314. update_post(Text, Key, Value) ->
  315. update_post(Text, [{Key, Value}]).
  316. delete_post(Text) ->
  317. some_db:delete(posts, [{text, Text}]).
  318. create_comment(PostId, Text) -> create_comment(PostId, Text, undefined).
  319. create_comment(PostId, Text, Image) ->
  320. some_db:insert(comments, [{post_id, PostId}, {text, Text}, {image, Image}]).
  321. update_comment(PostId, CommentId, Changes) ->
  322. some_db:update(comments, [{post_id, PostId}, {id, CommentId}], Changes).
  323. update_comment(PostId, CommentId, Key, Value) ->
  324. update_comment(PostId, CommentId, [{Key, Value}]).
  325. delete_comment(PostId, CommentId) ->
  326. some_db:delete(comments, [{post_id, PostId}, {id, CommentId}]).
  327. ```
  328. *原因*: 上帝模块, 类似上帝对象, 了解过多或者负责过多的模块. 上帝模块通常是因为不断的增加功能函数演变出来的.
  329. A beautiful, to-the-point module with one job, one responsibility done well, gains a function. Then another, which does the same thing but with different parameters.
  330. 总有一天, 你会写出一个包含500多个函数并且高达6000多行代码的模块 .因此,让模块(和功能)只做一件事情就可以很容易地探索和理解代码,从而维护它.
  331. 这个的意思就是按功能拆分模块,不同功能让放到不同模块实现,A模块做A功能相关的事情,B模块做B模块相关的事情,不要把不相关的功能放到一个模块去,特别是作为较底层的模块
  332. ***
  333. #### 抽象重复代码
  334. > 不要在多个地方使用相同的代码,请用函数或者变量去代替。
  335. 1 把重复的代码抽象成函数
  336. 2 把同个作用域同个函数(参数也一样)的结果用变量保存,替换后面再次调到该函数的地方
  337. *Examples*: [dry](src/dry.erl)
  338. ```erlang
  339. %% @doc this is a very very trivial example, DRY has a much wider scope but it's
  340. %% provided just as an example
  341. bad() ->
  342. case somthing:from(other, place) of
  343. {show, _} ->
  344. display:nicely(somthing:from(other, place));
  345. nothing ->
  346. display:nothing()
  347. end.
  348. good() ->
  349. case somthing:from(other, place) of
  350. {show, _} = ThingToShow ->
  351. display:nicely(ThingToShow);
  352. dont_show_me ->
  353. display:nothing()
  354. end.
  355. ```
  356. *原因*: 这是一条特别的规约,因为这样子审查人员就可以拒绝接受那些好几个地方都包含相同代码的提交(PRs)了,或者接受那些在某个地方已完成的可复用新实现。
  357. ***
  358. #### 避免动态调用
  359. > If there is no specific need for it, don't use dynamic function calling.
  360. *Examples*: [dyn_calls](src/dyn_calls.erl)
  361. ```erlang
  362. bad(Arg) ->
  363. Mods = [module_1, module_2, module_3],
  364. Fun = my_function,
  365. lists:foreach(
  366. fun(Mod) ->
  367. Mod:Fun(Arg)
  368. end, Mods).
  369. good(Arg) ->
  370. mdoule_1:my_function(Arg),
  371. module_2:my_function(Arg),
  372. module_3:my_function(Arg).
  373. ```
  374. *原因*: Dynamic calls can't be checked by [``xref``](http://erlang.org/doc/apps/tools/xref_chapter.html),
  375. one of the most useful tools in the Erlang world. ``xref`` is a cross reference checking/observing tool.
  376. Xref是一个交叉引用工具,可用于查找函数,模块,应用程序和发行版之间的依赖关系。它通过分析定义的函数和函数调用来实现
  377. *原因*: 不要写面条式代码很难阅读, 理解和修改. The function callgraph for your program should strive to be a directed acyclic graph.
  378. ### 语法
  379. Erlang语法很可怕, 我说得对吗? 所以你也可以充分利用它, 对吗? _对_?
  380. ***
  381. #### 避免使用 if 表达式
  382. > Don't use `if`.
  383. *Examples*: [no_if](src/no_if.erl)
  384. ```erlang
  385. bad(Connection) ->
  386. {Transport, Version} = other_place:get_http_params(),
  387. if
  388. Transport =/= cowboy_spdy, Version =:= 'HTTP/1.1' ->
  389. [{<<"connection">>, utils:atom_to_connection(Connection)}];
  390. true ->
  391. []
  392. end.
  393. better(Connection) ->
  394. {Transport, Version} = other_place:get_http_params(),
  395. case {Transport, Version} of
  396. {cowboy_spdy, 'HTTP/1.1'} ->
  397. [{<<"connection">>, utils:atom_to_connection(Connection)}];
  398. {_, _} ->
  399. []
  400. end.
  401. good(Connection) ->
  402. {Transport, Version} = other_place:get_http_params(),
  403. connection_headers(Transport, Version, Connection).
  404. connection_headers(cowboy_spdy, 'HTTP/1.1', Connection) ->
  405. [{<<"connection">>, utils:atom_to_connection(Connection)}];
  406. connection_headers(_, _, _) ->
  407. [].
  408. ```
  409. *原因*: 在某些情况下,`if`会在代码中引入静态布尔逻辑,从而降低代码的灵活性。在其他情况下,
  410. `case`或在其子句中具有模式匹配的函数调用是更具说明性。 对于新手(已经学会在其他语言中使用`if`),
  411. Erlang的“if”可能难以理解或容易被滥用。
  412. *更多相关的讨论看下面*:
  413. - [From OOP world](http://antiifcampaign.com/)
  414. - [In this repo](issues/14)
  415. - [In erlang-questions](http://erlang.org/pipermail/erlang-questions/2014-September/080827.html)
  416. ***
  417. #### 避免嵌套try...catches
  418. > Don't nest `try…catch` clauses
  419. *Examples*: [nested_try_catch](src/nested_try_catch.erl)
  420. ```erlang
  421. bad() ->
  422. try
  423. maybe:throw(exception1),
  424. try
  425. maybe:throw(exception2),
  426. "We are safe!"
  427. catch
  428. _:exception2 ->
  429. "Oh, no! Exception #2"
  430. end
  431. catch
  432. _:exception1 -> "Bummer! Exception #1"
  433. end.
  434. good1() ->
  435. try
  436. maybe:throw(exception1),
  437. maybe:throw(exception2),
  438. "We are safe!"
  439. catch
  440. _:exception1 ->
  441. "Bummer! Exception #1";
  442. _:exception2 ->
  443. "Oh, no! Exception #2"
  444. end.
  445. good2() ->
  446. try
  447. maybe:throw(exception1),
  448. a_function:that_deals(with, exception2),
  449. "We are safe!"
  450. catch
  451. _:exception1 ->
  452. "Bummer! Exception #1"
  453. end.
  454. ```
  455. *原因*: 嵌套`try ... catch`块会破坏它们的整个目的,即将处理错误的代码与处理预期执行路径的代码隔离开来。
  456. ### 命名
  457. ***
  458. #### 在命名概念时保持一致
  459. > 对于相同的概念,在任何地方都使用相同的变量名 (即使在不同的模块当中).
  460. *Examples*: [consistency](src/consistency.erl)
  461. ```erlang
  462. bad(UserId) -> internal_bad(UserId).
  463. internal_bad(User_Id) -> internal_bad2(User_Id).
  464. internal_bad2(Usr) -> db:get_by_id(Usr).
  465. good(UserId) -> internal_good(UserId).
  466. internal_good(UserId) -> internal_good2(UserId).
  467. internal_good2(UserId) -> db:get_by_id(UserId).
  468. ```
  469. *原因*: 当要找出所有用到``OrgID`` 的代码 (例如 我们想把变量从 ``string`` 转为 ``binary``),
  470. 我们只要搜索名为 ``OrgID``的变量,而不需要查找所有有可能关于 ``OrgID``的命名变量.
  471. 对于这个还是要注意 相同的概念 这个限定 比如我们经常用到的等级 玩家等级 装备等级 技能等级 公会等级 虽然都是等级,但是最好前缀..level
  472. 类似还有一些同类型枚举定义加个前缀,字典原子名定义可以加个 pd_ 前缀
  473. ***
  474. #### 不要使用匿名变量
  475. > 以_开头的变量仍然是变量,并且是匹配和绑定的,_开头的变量只是在不使用它的时候避免编译器产生警告信息。如果将_添加到变量的名称,请不要使用它。
  476. 同时即使下划线开头的变量,在后面代码中不使用,但是应该还是需要把下线线后面的变量名写成好,一是为了可读性,二 当修改需要使用该比变量的时候直接去掉下划线
  477. 三 即使是_划线开始 ,但是这个变量名还是被绑定了的 同个函数内不能和其他下划线开头的变量一样
  478. *Examples*: [ignored_vars](src/ignored_vars.erl)
  479. ```erlang
  480. bad(_Number) -> 2 * _Number.
  481. good(Number) -> 2 * Number.
  482. ```
  483. *原因*: They are **not** supposed to be used.
  484. ***
  485. #### 避免用布尔类型原子作为函数参数
  486. > Don't use boolean parameters (i.e. `true` and `false`) to control clause selection.
  487. *Examples*: [boolean_params](src/boolean_params.erl)
  488. ```erlang
  489. bad(EdgeLength) -> bad_draw_square(EdgeLength, true).
  490. bad_draw_square(EdgeLength, true) ->
  491. square:fill(square:draw(EdgeLength));
  492. bad_draw_square(EdgeLength, false) ->
  493. square:draw(EdgeLength).
  494. good(EdgeLength) -> good_draw_square(EdgeLength, full).
  495. good_draw_square(EdgeLength, full) ->
  496. square:fill(square:draw(EdgeLength));
  497. good_draw_square(EdgeLength, empty) ->
  498. square:draw(EdgeLength).
  499. ```
  500. *原因*: 主要目的在于,使用其他原子做匹配时意图清晰,不要求读者检查功能定义以了解其功能。
  501. ***
  502. #### 原子(atoms)请用小写
  503. > 原子命名只能使用小写字母. 当一个原子含有多个单词时
  504. ,单词之间用 `_` 隔开. 特殊情况可以允许用大写 (例如 `'GET'`, `'POST'`, 等等)
  505. 但是尽量还是控制在一定使用量.
  506. *Examples*: [atoms](src/atoms.erl)
  507. ```erlang
  508. bad() -> ['BAD', alsoBad, bad_AS_well].
  509. good() -> [good, also_good, 'good@its.mail'].
  510. ```
  511. *原因*: 坚持一个约定使得更容易在代码周围没有“重复”原子。 此外,不使用大写字母或特殊字符减少了对原子周围的需求。
  512. ***
  513. #### 函数名
  514. > 函数名称只能使用小写字符或数字。 函数名中的单词必须用`_`分隔。
  515. *Examples*: [function_names](src/function_names.erl)
  516. ```erlang
  517. badFunction() -> {not_allowed, camel_case}.
  518. 'BAD_FUNCTION'() -> {not_allowed, upper_case}.
  519. good_function() -> ok.
  520. base64_encode() -> ok.
  521. ```
  522. *原因*: 函数名称是原子,它们应遵循适用于它们的相同规则。
  523. ***
  524. #### 变量名
  525. > 使用驼峰式命名变量. 单词之间不要用下划线分割.
  526. *Examples*: [variable_names](src/variable_names.erl)
  527. ```erlang
  528. bad(Variablename, Another_Variable_Name) ->
  529. [Variablename, Another_Variable_Name].
  530. good(Variable, VariableName) ->
  531. [Variable, VariableName].
  532. ```
  533. *原因*:遵循一个约定可以更容易地在代码周围没有“重复”变量。 Camel-case使变量名称在视觉上与原子更加明显,并且符合OTP标准。
  534. 大部分从其他语言转过来可能都习惯了驼峰命名法,可能对函数名 原子也喜欢用,
  535. 但是看很多erlang的开源项目,包括OTP自身的代码命名风格的话都是遵循上面这些规则
  536. ### 宏
  537. ***
  538. #### 宏的应用场景
  539. > 除了包含以下使用方式的情况外,不要使用宏
  540. > * 预定义部分: ``?MODULE``, ``?MODULE_STRING`` and ``?LINE``
  541. > * 魔术数字: ``?DEFAULT_TIMEOUT``
  542. *Examples*: [macros](src/macros.erl)
  543. ```erlang
  544. -module(macros).
  545. -define(OTHER_MODULE, other_module).
  546. -define(LOG_ERROR(Error),
  547. error_logger:error_msg(
  548. "~p:~p >> Error: ~p~n\tStack: ~p",
  549. [?MODULE, ?LINE, Error, erlang:get_stacktrace()])).
  550. -define(HTTP_CREATED, 201).
  551. -export([bad/0, good/0]).
  552. bad() ->
  553. try
  554. ?OTHER_MODULE:some_function(that, may, fail, 201)
  555. catch
  556. _:Error ->
  557. ?LOG_ERROR(Error)
  558. end.
  559. good() ->
  560. try
  561. other_module:some_function(that, may, fail, ?HTTP_CREATED)
  562. catch
  563. _:Error ->
  564. log_error(?LINE, Error)
  565. end.
  566. log_error(Line, Error) ->
  567. error_logger:error_msg(
  568. "~p:~p >> Error: ~p~n\tStack: ~p",
  569. [?MODULE, Line, Error, erlang:get_stacktrace()]).
  570. ```
  571. *原因*: 宏的使用不利于调试工作的进行. 如果你尝试用它们来避免重复的代码块,可以使用以下函数去实现。
  572. 具体看 [related blog post](https://medium.com/@erszcz/when-not-to-use-macros-in-erlang-1d3f10d377f#.xc9b4bsl9) by [@erszcz](https://github.com/erszcz).
  573. ***
  574. #### 宏名要大写
  575. > 宏名应以大写字母命名:
  576. *Examples*: [macro_names](src/macro_names.erl)
  577. ```erlang
  578. -module(macro_names).
  579. -define(bad, 1).
  580. -define(BADMACRONAME, 2).
  581. -define(Bad_Macro_Name, 3).
  582. -define(Bad_L33t_M@Cr0, 4).
  583. -define(GOOD, 5).
  584. -define(GOOD_MACRO_NAME, 6).
  585. ```
  586. *原因*: 这样做可以区分开普通变量和宏,在使用`grep`等工具查找这个宏时不会出现重复宏名,让查找变得更加容易等好处
  587. ### 记录(Records)
  588. ***
  589. #### 记录命名
  590. > 记录(`record`)命名只能使用小写字母. 单词之间用 `_`分隔. 这个规则同样适用于`record`的字段名
  591. *Examples*: [record_names](src/record_names.erl)
  592. ```erlang
  593. -module(record_names).
  594. -export([records/0]).
  595. -record(badName, {}).
  596. -record(bad_field_name, {badFieldName :: any()}).
  597. -record('UPPERCASE', {'THIS_IS_BAD' :: any()}).
  598. -record(good_name, {good_field_name :: any()}).
  599. records() -> [#badName{}, #bad_field_name{}, #'UPPERCASE'{}, #good_name{}].
  600. ```
  601. *原因*: `record`和其字段名都是原子(`atom`), 因此跟原子的命名规则是一样的.
  602. #### 在specs里避免出现记录
  603. > 在 specs 里应该尽可能用 `types` 代替 记录(`records`).
  604. *Examples*: [record_spec](src/record_spec.erl)
  605. ```erlang
  606. -module(record_spec).
  607. -record(state, {field1:: any(), field2:: any()}).
  608. -opaque state() :: #state{}.
  609. -export_type([state/0]).
  610. -export([bad/1, good/1]).
  611. -spec bad(#state{}) -> {any(), #state{}}.
  612. bad(State) -> {State#state.field1, State}.
  613. -spec good(state()) -> {any(), state()}.
  614. good(State) -> {State#state.field1, State}.
  615. ```
  616. *原因*: 类型可以导出使用,同时也有助于文档化, 使用 ``opaque`` 可以对记录进行封装和抽象.
  617. ***
  618. #### 给记录添加类型Types
  619. > 保持给记录(`record`)的每个字段添加类型定义的习惯
  620. *Examples*: [record_types](src/record_types.erl)
  621. ```erlang
  622. -module(record_types).
  623. -export([records/0]).
  624. -record(bad, {no_type}).
  625. -record(good, {with_type :: string(), with_value_type = 1 :: non_neg_integer()}).
  626. records() -> [#bad{}, #good{}].
  627. ```
  628. *原因*: 记录(`record`)定义的是数据结构, 而其中最重要的部分之一就是记录组成部分的类型定义.
  629. ### 其它
  630. ***
  631. #### 给函数添加-spec函数规范定义
  632. *Examples*: [specs](src/specs.erl)
  633. *原因*: 1 便于Dialyzer分析
  634. 2 更容易知道函数的参数类型和返回以及用法
  635. ***
  636. #### 模块中不要用import
  637. > Do not use the `-import` directive
  638. *Examples*: [import](src/import.erl)
  639. *原因*:从其他模块导入函数会使代码更难以读取和调试,因为您无法直接区分本地函数和外部函数。
  640. ***
  641. ***
  642. #### Don't Use Case Catch
  643. > 不要用`case catch` 捕获匹配异常, 使用 `try ... of ... catch` 代替 `case catch`.
  644. *Examples*: [case-catch](src/case_catch.erl)
  645. *原因*: `case catch ...` 把正确的的结果与异常一起处理令人困惑。
  646. `try ... of ... catch` 把正确的的结果与异常分开处理。
  647. ## 好的建议和方法
  648. 当我们写代码时,应该考虑以下一些注意事项,但是不要引发PR拒绝,或者含糊到无法连贯执行。
  649. ***
  650. ### 优先使用高级函数而不是手写的递归方法
  651. > 有时实现函数最好的方式是编写递归函数, 但是比较经常的写法是使用 fold函数 或者 列表推导式 会更加安全和可读性更高.
  652. *Examples*: [alternatives to recursion](src/recursion.erl)
  653. ```erlang
  654. -module(recursion).
  655. -export([recurse/1, fold/1, map/1, comprehension/1]).
  656. %%
  657. %% 例子:
  658. %% 不同的方法实现大写字符串
  659. %%
  660. %% 差的: 使用不必要的人工手写递归
  661. recurse(S) ->
  662. lists:reverse(recurse(S, [])).
  663. recurse([], Acc) ->
  664. Acc;
  665. recurse([H | T], Acc) ->
  666. NewAcc = [string:to_upper(H) | Acc],
  667. recurse(T, NewAcc).
  668. %% 好的: 使用fold函数实现同样的结果,更加安全,更少的代码行数
  669. fold(S) ->
  670. Result = lists:foldl(fun fold_fun/2, [], S),
  671. lists:reverse(Result).
  672. fold_fun(C, Acc) ->
  673. [string:to_upper(C) | Acc].
  674. %% 更佳的: 使用map函数代替fold函数,更简单的实现方法,因为在这种情况下,fold函数大材小用了。
  675. map(S) ->
  676. lists:map(fun string:to_upper/1, S).
  677. %% 最好的: 在这种情况下,列表推导式最简单的实现方法(假设忽略string:to_upper也能直接对string使用的事实)
  678. comprehension(S) ->
  679. [string:to_upper(C) || C <- S].
  680. ```
  681. *原因*: 人工手写的递归容易出错, 并且代价昂贵。在有错误的情况下,一个错误的递归函数会失去它的基本功能,
  682. 如螺旋般地失去控制,导致整个erlang节点挂掉,抵消了erlang最主要的好处之一: 进程的死亡不会导致整个节点的崩溃。
  683. 另外,对于一个有经验的erlang开发者而言,folds 和 列表推导式比复杂的递归函数更容易理解。
  684. 显而易见的是:它们能为列表中的每个元素执行操作,递归也许同样能够实现,但是它经常需要仔细的检查,以验证控制流在实践中实际执行的路径。
  685. ***
  686. ### 驼峰式命名,下划线命名
  687. > 符号命名:使用驼峰式命名变量,原子,函数和模块则使用下划线命名
  688. > *Examples*: [camel_case](src/camel_case.erl)
  689. ```erlang
  690. -module(camel_case).
  691. -export([bad/0, good/0]).
  692. %% 差的
  693. bad() ->
  694. Variable_Name = moduleName:functionName(atomConstant),
  695. another_ModuleName:another_Function_Name(Variable_Name).
  696. %% 好的
  697. good() ->
  698. VariableName = module_name:function_name(atom_constant),
  699. another_module_name:another_function_name(VariableName).
  700. ```
  701. *小节结论*:本节对下面一个问题很有帮助。
  702. ***
  703. ### 更短(但仍保持有意义的)的变量名称
  704. > 只要易于阅读和理解,保持变量名称简短。
  705. *Examples*: [var_names](src/var_names.erl)
  706. ```erlang
  707. -module(var_names).
  708. -export([bad/1, good/1]).
  709. %% 差的
  710. bad(OrganizationToken) ->
  711. OID = organization:get_id(OrganizationToken),
  712. OID.
  713. %% 好的
  714. good(OrgToken) ->
  715. OrgID = organization:get_id(OrgToken),
  716. OrgID.
  717. ```
  718. *小节结论*: 它有助于减少每行的长度,这也是上面描述的。
  719. ***
  720. ### 注释等级
  721. > 模块注释用 **%%%**, 函数注释用 **%%**, 代码注释用 **%**.
  722. *Examples*: [comment_levels](src/comment_levels.erl)
  723. ```erlang
  724. % 这样的注释坏到家了
  725. %%% @doc 这样的注释不错
  726. -module(comment_levels).
  727. -export([bad/0, good/0]).
  728. % @doc 这样的注释不好
  729. %%% @doc 这的注释也不好
  730. bad() ->
  731. R = 1 + 2, %%% 这样的注释不好(not good)
  732. R. %% 这样的注释依然不好(bad again)
  733. %% @doc 这种注释我喜欢
  734. good() ->
  735. % 这个注释得到国际注释协会的一致认可
  736. % 还有 Chuck Norris的认可
  737. R = 1 + 2,
  738. R. % This comment (megusta) 这个注释我喜欢(megusta 西班牙语:我喜欢)
  739. ```
  740. *小节结论*: 清晰的陈述了注释是什么, 并且寻找特定的注释比如:"%% @"等 是非常有用的。
  741. 注释的位置应与被描述的代码相邻,可以放在代码的上方或右方,不可放在下方。
  742. 修改代码同时修改相应的注释,以保证注释与代码的一致性。不再有用的注释要删除。
  743. 注释应当准确、易懂,防止注释有二义性。错误的注释不但无益反而有害。
  744. 当代码比较长,特别是有多重嵌套时,应当在一些段落的结束处加注释,便于阅读。
  745. ***
  746. ### 保持函数精简
  747. > 只做一件事,尝试着用少量表达式来写函数. 除了集成测试外,每个函数理想的表达式数量是不超过**12**个.
  748. *Examples*: [small_funs](src/small_funs.erl)
  749. *小结*: 从3个方面:
  750. - 简洁的函数有助于是可读性和组装性。可读性又有助于维护。这一点强调的足够多了,你的代码越简洁,就越容易修复和更改。
  751. - 简洁的函数目的清晰明了,因此您只需要了解执行操作的其中一小部分的子集,这使得验证它是否正确地工作变得非常简单。
  752. - 强有力的论据:
  753. + 一个函数只干一件事情,如果函数太冗长你可能更适合改为以多个函数实现
  754. + 很明显,简单的,简洁的函数更容易理解
  755. + 重用性,保持函数的精简有利于后续使用(特别是erlang)
  756. + 屏幕尺寸:出于如何原因如果通过ssh连接服务器或者,你希望能够看到整个函数
  757. *提示*:
  758. 本指导, 联合 **[避免多层嵌套](#avoid-deep-nesting)** and
  759. **[在case表达式中使用更多更小的函数](#more-smaller-functions-over-case-expressions)**
  760. 两个指导, 可以很好的利用来构建函数,如下所示:
  761. ```erlang
  762. some_fun(#state{name=foo} = State) ->
  763. do_foo_thing(),
  764. continue_some_fun(State);
  765. some_fun(#state{name=bar} = State) ->
  766. do_bar_thing(),
  767. continue_some_fun(State).
  768. continue_some_fun(State) ->
  769. ...,
  770. ok.
  771. ```
  772. 记住这些:
  773. - 像这样在函数结尾调用函数是没有代价的
  774. - 这种模式高效、紧凑、清晰
  775. - 这样重置缩进,因此代码不会游离于屏幕右边边缘地带
  776. 最重要的:
  777. - 测试起来简单,因为函数描绘了测试节点.
  778. - 提供更多的跟踪切入面,因此我们能够找到哪里的代码计算运行导致脱轨,而嵌套case写法在运行时是不可跟踪的。
  779. ***
  780. ### 避免不必要调用length/1
  781. > 许多用`length/1`作为`case`条件都可以被模式匹配替代掉,尤其在检查列表是否至少有一个元素时很管用。
  782. (要遍历列表,时间长度不定)
  783. *Examples*: [pattern matching](src/pattern_matching.erl)
  784. ```erlang
  785. -module(pattern_matching).
  786. -export([bad/1, good/1]).
  787. bad(L) ->
  788. case length(L) of
  789. 0 -> error;
  790. _ -> ok
  791. end.
  792. good([]) ->
  793. error;
  794. good(_L) ->
  795. ok.
  796. ```
  797. *小结*:模式匹配是`Erlang`的核心内容之一,并且它的性能和可读性都很好。模式匹配也更加灵活,因此它使得代码逻辑变得更加简单。
  798. 防坑指南----------------------------------------------------------------------------------------
  799. '--' 运算与 '++'运算
  800. > [1,2,3,4] -- [1] -- [2].
  801. [2,3,4]
  802. 这是从后面算起的,先算 [1] -- [2] ,得到 [1] 后被 [1,2,3,4] --,最后得到 [2,3,4]
  803. '++'运算也是一样的,也是从后面开始算起。
  804. > [1,2,3,4] -- [1] ++ [2,3,4].
  805. []
  806. ++只是lists:append/2的一个别名:如果要用一定要确定 ShortList++LongList
  807. erlang:list_to_binary()
  808. 如果参数是多层嵌套结构,就会被扁平化掉,使用 binary_to_list 不能转成原来的数据,也就是不可逆的。
  809. 6> list_to_binary([1,2,[3,4],5]) .
  810. <<1,2,3,4,5>>
  811. 如果想可逆,可以使用 erlang:term_to_binary
  812. 7> binary_to_term(term_to_binary([1,2,[3,4],5])).
  813. [1,2,[3,4],5]
  814. ets:tablist/2在数据比较大的时候尽量少用
  815. erlang 不同数据类型比较
  816. number < atom < reference < fun < port < pid < tuple < list < bit string
  817. Erlang中整数值没有上限值,最大值只是受限于硬件(内存有多大) 但是erlang的浮点数是有上限的遵循 IEEE754
  818. 在 guard 模式下,原本会抛出异常的代码就不会报错了,而是结束当前计算并返回false。
  819. 在 guard 模式下,erlang是有两种表达方法的:
  820. 1. , 和 ;
  821. 2. andalso 和 orelse
  822. 然而,这两种表述是有区别的:
  823. 首先,假如条件语句是这样的 X >= N; N >= 0,
  824. 当前半句出现异常时候,后面半句还是会执行,而且结果可能回是true;
  825. 然后,假如条件语句是这样的 X >= N orelse N >= 0,
  826. 当前半句出现异常时候,后面半句是会被跳过的,返回的结果就是异常
  827. 而其实两种都有各自的优缺点,所以,很多情况下都是把他们两种混合起来使用,达到业务需求
  828. 最后补充下,when 之后是不允许使用自定义function的,会产生副作用,所以只能是跟整数比较或者是内部的函数,如:is_integer/1,is_atom/1.
  829. 顺带讲一下 and andalso or orelse
  830. and 和 or 两边参与运算的必须是true或者是false才行 返回值也必然是true或者false 但是andalso orelse跟这个是短路求值 是有点差别的 比如下面
  831. (A > 1 orelse io:format("this is run ~n")).
  832. (A > 1 andalso io:format("this is run ~n").
  833. (true andalso io:format("this is run ~n") andalso io:format("this is run2 ~n")).
  834. (true andalso io:format("this is run ~n") andalso io:format("this is run2 ~n")).
  835. true andalso false andalso fdfd .
  836. true andalso false andalso io:format("this is run ~n") orelse io:format("this is run2 ~n").
  837. true andalso false andalso io:format("this is run ~n") andalso io:format("this is run2 ~n").
  838. true andalso false orelse io:format("this is run ~n") andalso io:format("this is run2 ~n").
  839. 其他的更多的
  840. [那些经历过的Erlang小坑1-10](https://www.cnblogs.com/zhongwencool/p/3712909.html)
  841. [那些经历过的Erlang小坑11-20](http://www.bubuko.com/infodetail-249770.html)
  842. [那些经历过的Erlang小坑21-30](https://www.cnblogs.com/zhongwencool/p/erlang_tip_21_30.html)