当你写code久了,会发现到底该怎么进步呢? 其中一点就是遵守官方的Coding Style,如此这般,未来你在跟其他团队或者跟国际团队在合作的时候,你们才比较有统一的撰写风格,通常大一点的公司也许都会有自己的Coding style guide line,但学习或遵循官方的Coding Style会是一个最快的方式,大致上可以看到有Google的与Kotlin官方的两个版本,今天我们先用Android官方的版本来挑几个例子来说明一下,由于内容非常长但很丰富值得定期来update,个人是非常建议不定时都要来看一下
https://developer.android.com/kotlin/style-guide
Naming 档案命名
在变数命名中是一个很基本的,首字大写,大多应该都会用名词作为开头
If a source file contains only a single top-level class, the file name should reflect the case-sensitive name plus the .kt extension. Otherwise, if a source file contains multiple top-level declarations, choose a name that describes the contents of the file, apply PascalCase (camelCase is acceptable if the filename is plural), and append the .kt extension.
并且可以看到官方说到,会使用驼峰式命名为主
Formatting 格式化
https://developer.android.com/kotlin/style-guide#formatting
Function
https://developer.android.com/kotlin/style-guide#functions
当function参数过多无法塞入所谓的一行中,建议可以在每一个参数宣告处换行,譬如这样,一方面也可以很清楚的看到参数宣告
fun <T> Iterable<T>.joinToString( separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = ""): String { // …}
我们回头来看如果不透过这样的方式格式化的话会是这样
fun <T> Iterable<T>.joinToString(separator: CharSequence = ", ",prefix: CharSequence = "",postfix: CharSequence = ""): String { // …}
可以看到这样比较杂乱不好阅读,增加程式码阅读性也是开发人员的职责之一,但这样撰写其实也是允许的,不过通常我个人也会建议超过一行时候都可以透过工具直接进行换行,在Android Studio中也可以轻鬆地透过IDE进行自动换行
TODO ..增加说明
Expression functions 描述性函式
https://developer.android.com/kotlin/style-guide#expression_functions
如果你的function不多行,像是这样
override fun toString(): String { return "Hey"}
通常我个人也会建议让他变成expression functions,也就是这样
override fun toString(): String = "Hey"
不仅清楚,而且可以节省两行,当程式码多的时候,可以让你的整个程式码更乾净一些
Properties 属性
https://developer.android.com/kotlin/style-guide#properties
也就是变数宣告,如果当一行超过的时候,建议可以再 =
后面进行换行
private val defaultCharset: Charset? = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(file)
变成
private val defaultCharset: Charset? = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(file)
如果你后面透过所谓的custom getter / setter ,建议会透过缩排的方式进行格式化
var directory: File? = null set(value) { // … }
但如果你式read-only的 properites的话,就可以儘在一行中进行显示
val defaultExtension: String get() = "kt"
Whitespace 关于空白
https://developer.android.com/kotlin/style-guide#whitespace
Separating any reserved word, such as if, for, or catch from an open parenthesis (() that follows it on that line.
对于保留字的后面(譬如if
/ for
等等),都建议要空上一格,譬如下面这样,if
后面可以黏着(
,但官方会建议你要进行空格,又或者如果你们团队的习惯就是会黏着写,那你所有的程式码都需要遵循同样的规则,但官方这边会建议保留字
都要进行空格
遵循一样的撰写风格与排版,这样程式码看起来才会比较一致,
Separating any reserved word, such as else or catch, from a closing curly brace (}) that precedes it on that line.
然而如果你的保留字
遇到括号
,同样也要保持一个空白的规则,目前就先更新到这边,未来有机会再持续针对其他规则说明