分享 Github 开放了自己的编程风格指南

xqunix · 2012年03月22日 · 最后由 blackanger 回复于 2012年04月11日 · 6264 次阅读

包含 Ruby、CSS、HTML 以及 JavaScript

https://github.com/styleguide/ruby

心情有点烦,不想看英文了,这是一篇很好的 wiki,话说有木有人来翻译一下。

Great stuff.

发现三点自己没实行: Indent when as deep as case. Use empty lines between defs and to break up a method into logical paragraphs. Use TomDoc to the best of your ability. It's pretty sweet: 其它还基本符合....

and you guys?

公司培训的时候有这里的一些要求。 Don't use ||= to initialize boolean variables. (Consider what would happen if the current value happened to be false.) 很多时候都是用||=,囧

# bad
unless success?
  puts 'failure'
else
  puts 'success'
end

# good
if success?
  puts 'success'
else
  puts 'failure'
end

我就喜欢 bad,先处理错误~

说到风格。。。其实应该是编码规范吧? 但是上次爆出被 hack 事件,足见其规范不是严谨

#2 楼 @poshboytl 既然是风格,就没有绝对的对错。 我觉得不必像best-practice一样。 风格只是团队内部的编码规范而已。不必完全遵守,关键在制定。

我反而看到 可以出个 github 的 bootstrap. :)

#6 楼 @camel 我有谈论到对错?:) 我只是在谈我符合他们哪些,不符合他们哪些...

我觉得这个 guide 和 wiki 中 github 上的那个没有什么区别,基本上是一样的

先收藏,回頭看

我就喜欢这一类文章,话说那些前辈总结的东西,总是应该借鉴。但是也仅仅是借鉴。

其实我觉得这些东西都是白看,通常会记住的东西都是从教训中来了,出过一次事了,记忆就深刻了,所以还是多写代码,多重构吧。

#4 楼 @mimosa 他这里的重点应该是 unless 就不要跟 else 一起用.... 如果你要先处理错的 也应该是

if !success?
  puts 'failure'
else
  puts 'success' 
end

这个和本站 wiki 里放出的规范差不多 http://ruby-china.org/wiki/coding-style

除了新 hash 不想用,其他跟了

Don't use parentheses around the condition of an if/unless/while, unless the condition contains an assignment (see "Using the return value of =" below).

一直没搞明白为什么啊

Use one expression per branch in a ternary operator. 这个我好像嵌套过几次?:

Avoid do...end when chaining. 这个我肯定写过,以后要改。 另外我喜欢在 private 关键字上下都空一行,而不是只有上边空一行。其他基本符合。

#16 楼 @huobazi 我自己是这么看的,圆括号在简单的语句中,看起来会显得多余。通常,我只用它来提高表达式中一部分的优先级,或者在一行中有多个方法调用时使用括号。

link_to "Home", root_path
link_to content_tag(:span, "Home"), root_path
Post.published.page(params[:page]).per(params[:per])

#13 楼 @poshboytl 亲,我恰恰是不喜欢使用!作为不等于,喜欢 unless~~

#19 楼 @mimosa 我也是,!在代码中 太不明显了,很容易看走眼,无论什么编程语言,我都不喜欢用!,所以我很喜欢 ruby 的 unless,当然 unless也不能滥用。

要保持自己的

Use _ for unused block parameters.

# bad
result = hash.map { |k, v| v + 1 }

# good
result = hash.map { |_, v| v + 1 }

这个学习了

#19 楼 @mimosa 用 unless 避免 ! 自然可以,不过 Github Style Guide 里头这个例子,是想说 unless 与 else 不要一块用,因为英文里头没有这个语法,代码读起来不通顺

你们有没有注意到,它推荐新的 js 都用 CoffeeScript 来写

他们 js 不用 semicolons... 这个非主流啊~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号