翻译说明:java
原标题: Effective Java in Kotlin, item 2: Consider a builder when faced with many constructor parametersandroid
原文地址: blog.kotlin-academy.com/effective-j…git
原文做者: Marcin Moskala程序员
这篇文章对Java程序员将会有很大的影响。当咱们在处理各类各样的对象建立的操做是,这是一个很常见的场景。Effective Java中提出的很好的论据建议开发人员使用Builder构建器而不是伸缩构造函数模式。虽然Kotlin改变了不少 - 它给了咱们更好的可能性。咱们很快就会看到它github
这是Effective Java edition 2的第二条规则:安全
面对许多构造函数时使用BUILDERS
并发
让咱们来探索吧。app
在Java中,一般方式是使用可选的构造函数参数的可伸缩构造器模式去定义一个对象。当咱们使用可伸缩构造器模式时,能够为每一个使用的集合或参数定义一个单独的构造器。如下是Kotlin的一个例子:框架
class Dialog constructor(
val title: String,
val text: String?,
val onAccept: (() -> Unit)?
) {
constructor(title: String, text: String)
: this(title, text, null)
constructor(title: String)
: this(title, "")
}
// Usage
val dialog1 = Dialog("Some title", "Great dialog", { toast("I was clicked") })
val dialog2 = Dialog("Another dialog","I have no buttons")
val dialog3 = Dialog("Dialog with just a title")
复制代码
在Android中很是常见的例子就是咱们如何实现一个自定义View。 尽管这种模式在JVM世界中很流行,可是Effective Java认为对于更大或更复杂的对象,咱们应该使用Builder模式。Builder模式首先以可读和紧凑的方式获取参数列表,而后验证并实例化对象。这是一个例子:ide
class Dialog private constructor(
val title: String,
val text: String?,
val onAccept: (() -> Unit)?
) {
class Builder(val title: String) {
var text: String? = null
var onAccept: (() -> Unit)? = null
fun setText(text: String?): Builder {
this.text = text
return this
}
fun setOnAccept(onAccept: (() -> Unit)?): Builder {
this.onAccept = onAccept
return this
}
fun build() = Dialog(title, text, onAccept)
}
}
// Usage
val dialog1 = Dialog.Builder("Some title")
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build()
val dialog2 = Dialog.Builder("Another dialog")
.setText("I have no buttons")
.build()
val dialog3 = Dialog.Builder("Dialog with just a title").build()
复制代码
在可伸缩的构造器模式中,声明和用法都显得比较强大,可是builder模式有着更为重要的优势:
当咱们须要设置可选参数时,这个特性使构建器模式对大多数类更加明确,有弹性而且更好。
本章最受欢迎的部分,来自Effective Java的第二版,以下:
Builder模式模拟Ada和Python语言中的命名可选参数。
很棒的是,在Kotlin中,咱们不须要模拟命名的可选参数,由于咱们能够直接使用它们。在大多数状况下,可选参数比Builder构建器要更好。只需比较上面的构建器模式和下面命名的可选参数便可,就会发现声明和使用都更清晰,更短,更具表现力:
class Dialog(
val title: String,
val text: String? = null,
val onAccept: (() -> Unit)? = null
)
// Usage
val dialog1 = Dialog(
title = "Some title",
text = "Great dialog",
onAccept = { toast("I was clicked") }
)
val dialog2 = Dialog(
title = "Another dialog",
text = "I have no buttons"
)
val dialog3 = Dialog(title = "Dialog with just a title")
复制代码
具备命名可选参数的构造函数具备Builder构建器模式的大部分优势
在这个简单的示例中,具备命名可选参数的构造函数看起来更好,可是,若是咱们须要针对不一样参数的不一样建立变体呢?假设咱们为不一样的参数集建立不一样类型的对话框。咱们能够在Builder构建器中轻松地解决该问题:
interface Dialog {
fun show()
class Builder(val title: String) {
var text: String? = null
var onAccept: (() -> Unit)? = null
fun setText(text: String?): Builder {
this.text = text
return this
}
fun setOnAccept(onAccept: (() -> Unit)?): Builder {
this.onAccept = onAccept
return this
}
fun build(): Dialog = when {
text != null && onAccept != null ->
TitleTextAcceptationDialog(title, text!!, onAccept!!)
text != null ->
TitleTextDialog(title, text!!)
onAccept != null ->
TitleAcceptationDialog(title, onAccept!!)
else -> TitleDialog(title)
}
}
}
// Usage
val dialog1 = Dialog.Builder("Some title")
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build()
val dialog2 = Dialog.Builder("Another dialog")
.setText("I have no buttons")
.build()
val dialog3 = Dialog.Builder("Dialog with just a title").build()
复制代码
那咱们可使用命名的可选参数来解决该类问题吗?是的,咱们可使用不一样的构造函数或使用工厂方法来实现相同的功能!如下是针对上述问题示例的解决方案:
interface Dialog {
fun show()
}
fun makeDialog( title: String, text: String? = null, onAccept: (() -> Unit)?
): Dialog = when {
text != null && onAccept != null ->
TitleTextAcceptationDialog(title, text, onAccept)
text != null ->
TitleTextDialog(title, text)
onAccept != null ->
TitleAcceptationDialog(title, onAccept)
else ->
TitleDialog(title)
}
// Usage
val dialog1 = makeDialog(
title = "Some title",
text = "Great dialog",
onAccept = { toast("I was clicked") }
)
val dialog2 = makeDialog(
title = "Another dialog",
text = "I have no buttons"
)
val dialog3 = makeDialog(title = "Dialog with just a title")
复制代码
这是咱们的另外一个例子,咱们再次看到命名参数优于builder模式的地方:
Builder构建器模式的一个优势在于具备填充参数特性可用做工厂模式。虽然这种状况不多见,但这种优点微乎其微。
Builder构建器模式的另外一个讨论点是咱们能够部分填充构建器并进一步传递它。这样咱们就能够定义建立部分填充构建器的方法,而且能够修改它们(好比咱们的应用程序的默认对话框)。为了有相似的构造函数或工厂方法的可能性,咱们须要自动的柯里化(这在Kotlin中是可能的,但不是没有名称和默认参数丢失)。虽然这种对象建立方式不是很是常见,但一般也不是优选的。若是咱们要为应用程序定义默认对话框,可使用函数来建立它并将全部自定义元素做为可选参数传递。这种方法能够更好地控制对话框Dialog的建立。
通常规则是,在大多数状况下,命名可选参数应优先于构建器模式。尽管这不是Kotlin给咱们的Builder建造者模式的惟一新选择。另外一个很是受欢迎的是用于对象构建的DSL。咱们来描述一下。
假设咱们须要设置具备多个处理程序的监听器。相似于Java的经典方法是使用对象表达式:
taskNameView.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// ...
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// ...
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// no-op
}
})
复制代码
这种方法不是很方便,可使用命名的可选参数轻松替换为更简洁的工厂方法:
fun makeTextWatcher( afterTextChanged: ((s: Editable?) -> Unit)? = null,
beforeTextChanged: ((s: CharSequence?, start: Int, count: Int, after: Int) -> Unit)? = null,
onTextChanged: ((s: CharSequence?, start: Int, before: Int, count: Int) -> Unit)? = null
) = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
afterTextChanged?.invoke(s)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
beforeTextChanged?.invoke(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged?.invoke(s, start, before, count)
}
}
// Usage
taskNameView.addTextChangedListener(makeTextWatcher(
afterTextChanged = { s ->
// ..
},
beforeTextChanged = { s, start, count, after ->
// ...
}
))
复制代码
请注意,咱们能够轻松地把进一步改形成TextView的扩展函数:
taskNameView.addTextChangedListener(
afterTextChanged = { s ->
// ..
},
beforeTextChanged = { s, start, count, after ->
// ...
}
)
复制代码
这是DSL的一个简单示例。支持这种表示法的函数能够在相似Anko或Android-ktx这样的流行Kotlin库中找到。例如,这是咱们如何在Anko中定义和显示warning对话框:
alert("Hi, I'm Roy", "Have you tried turning it off and on again?"){
yesButton { toast("Oh…") }
noButton {}
}.show()
复制代码
问题在于这种表示方法须要写不少支持它们的声明,例如这是咱们如何定义上面的TextView的addOnTextChangedListener扩展方法:
fun TextView.addOnTextChangedListener( config: TextWatcherConfiguration.() -> Unit
) {
val listener = TextWatcherConfiguration().apply { config() }
addTextChangedListener(listener)
}
class TextWatcherConfiguration : TextWatcher {
private var beforeTextChangedCallback: (BeforeTextChangedFunction)? = null
private var onTextChangedCallback: (OnTextChangedFunction)? = null
private var afterTextChangedCallback: (AfterTextChangedFunction)? = null
fun beforeTextChanged(callback: BeforeTextChangedFunction) {
beforeTextChangedCallback = callback
}
fun onTextChanged(callback: OnTextChangedFunction) {
onTextChangedCallback = callback
}
fun afterTextChanged(callback: AfterTextChangedFunction) {
afterTextChangedCallback = callback
}
override fun beforeTextChanged( s: CharSequence, start: Int, count: Int, after: Int ) {
beforeTextChangedCallback?.invoke(s.toString(), start, count, after)
}
override fun onTextChanged( s: CharSequence, start: Int, before: Int, count: Int ) {
onTextChangedCallback?.invoke(s.toString(), start, before, count)
}
override fun afterTextChanged(s: Editable) {
afterTextChangedCallback?.invoke(s)
}
}
private typealias BeforeTextChangedFunction =
(text: String, start: Int, count: Int, after: Int) -> Unit
private typealias OnTextChangedFunction =
(text: String, start: Int, before: Int, count: Int) -> Unit
private typealias AfterTextChangedFunction =
(s: Editable) -> Unit
复制代码
对单个甚至两个用法进行此类声明是不合理的。另外一方面,当咱们开发一个库时,这不是问题。这就是为何在大多数状况下咱们使用库中定义的DSL的缘由。当咱们定义它们时,它们很是强大。请注意,在DSL内部,包括使用控制循环语句结构(if
for
,等等),定义变量等。这是一个为Kot.Academy官网生成的HTML使用DSL的例子。
private fun RDOMBuilder<DIV>.authorDiv( author: String?, authorUrl: String? ) {
author ?: return
div(classes = "main-text multiline space-top") {
+"Author: "
if (authorUrl.isNullOrBlank()) {
+author
} else {
a(href = authorUrl) { +author }
}
}
}
复制代码
除了声明以外,咱们也指定了如何定义这个元素的逻辑。这样的DSL一般比具备命名可选参数的构造函数或工厂方法强大得多。固然它也更复杂,更难定义。
在一些Android项目中能够观察到有趣的解决方案,其中开发人员实现了使用切除构建器的简化DSL。
假设咱们使用来自库(或框架)的对话框Dialog,它提供构建器做为建立方法(假设它是用Java实现的):
val dialog1 = Dialog.Builder("Some title")
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build()
复制代码
这就是如何实现和使用很是简单的DSL构建器:
fun Dialog(title: String, init: Dialog.Builder.()->Unit) =
Dialog.Builder(title).apply(init).build()
// Usage
val dialog1 = Dialog("Some title") {
text = "Great dialog"
setOnAccept { toast("I was clicked") }
}
复制代码
(只有在Java中定义了此方法时,咱们才能将text
设置为属性) 这样咱们就拥有了DSL的最大优势和很是简单的声明。这也代表了DSL和Builder构建器模式的共同点。他们有相似的理念,但DSL更像是下一代的建造者模式。
Effective Java的参数在Kotlin中仍然有效,而构建器模式比以前的Java替代方案更合理。尽管 Kotlin介绍了按名称指定参数并提供默认参数。多亏了这一点,咱们能够更好地替代构建器模式。Kotlin还提供了容许DSL使用的功能。定义良好的DSL甚至是更好的替代方案,由于它提供了更大的灵活性并容许在对象定义实现逻辑。
去断定对象建立到底有多复杂不是一个简单的问题,并且每每须要必定的经验。Kotlin给咱们带来很是重要的可能性,此外它们对Kotlin的发展也产生了积极的影响。
首先,回答下为何要翻译这篇文章,这篇文章是Effective Kotlin系列的第二篇,这篇讲的是咱们熟悉的Builder建造者模式,当咱们遇到构造器中有不少参数的时,我都会考虑使用Builder模式来替代它。固然这只是Java中常见操做,可是Kotlin是否是得循序渐进照着Java来呢?显然不是,Kotlin中有着更为优雅和强大的实现方式构造器+默认值参数。若是不了解本篇文章初学者,估计就会拿着Kotlin语言生搬硬套成Java的Builder实现方式,殊不知Kotlin中有更为优雅的实现方案。
其实,本篇文章继续体现Effective Kotlin一个宗旨: 经过对比Effective Java高效编码准则,在Kotlin中去寻找更为优雅实现方式和替代解决方案,而不是带着Java思惟写着Kotlin代码来翻译实现。从而进一步体验Kotlin与Java不一样以及各自优缺点。
欢迎关注Kotlin开发者联盟,这里有最新Kotlin技术文章,每周会不按期翻译一篇Kotlin国外技术文章。若是你也喜欢Kotlin,欢迎加入咱们~~~