携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的20天,点击查看活动详情
什么是清洁代码?
干净代码作者鲍勃曾经说过,“干净的代码是可读的。它讲述了一个故事。”敏捷开发者原则的作者说,“你向读者清楚地表达了你的意图,不可读的代码是不聪明的。”
那么我们如何衡量干净的代码呢?
非正式地说,它是以每分钟多少次WTF喊叫来衡量的。如果 wtf/min 低,则有一个快乐的开发团队,如果 wtf/min 高,则有一个不太满意的团队。这里的重点是 WTF (what a terrible feature)是“多么糟糕的功能”的缩写 ^^ 不要误会我的意思。
有意义的名字和表达
但是你如何编写干净的代码呢?以下是一些适用的规则。
当我们创建包、类、函数和变量时,我们编写代码。他们有名字,我们必须选择一个表达这个组件意图的名字。即使它只是一个变量或类名。
当我们搜索可读代码时,我们会问三个问题。
- 它为什么存在?
- 它有什么作用?
- 它是如何使用的?
| 类型 | 名称 |
|---|---|
| 类、对象 | Person、Student |
| 方法 | doPerson、doStudent |
| 解决域名 | PersonHelper |
| 问题域名 | churnPerMonth |
让我们把它分为两种类型,干净的代码和不干净的代码。
例子
- 拆分文件路径,获取最新文件及其目录
“不洁”
data class GetFile(val d: String, val n: String)
val pattern = Regex("(.+)/([^/]*)")
fun files(ph: String): PathParts {
val match = pattern.matchEntire(ph) ?: return PathParts("". ph)
return PathParts(match.groupValues[1], match.groupValues[2])
}
“干净的”
data class PathParts(val directory: String, val fileName: String)
val pattern = Regex("(.+)/([^/]*)")
fun splitPath(path: String) =
PathParts(
path.substringBeforeLast("/", ""),
path.substringAfterLast("/"))
- 当避免“if-null”检查并使用 evils(?:) with throw
“不洁”
class Book(val title: String?, val publishYear: Int?)
fun displayBookDetails(book: Book) {
val title = book.title
if (title == null)
throw IllegalArgumentException("Title required")
val publishYear = book.publishYear
if (publishYear == null) return
println("$title: $publishYear")
}
“干净的”
class Book(val title: String?, val publishYear: Int?)
fun displayBookDetails(book: Book) {
val title = book.title ?:
throw IllegalArgumentException("Title required")
val publishYear = book.publishYear ?: return
println("$title: $publishYear")
}