[翻译]Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

原文:Effective Java in Kotlin, item 2: Consider a builder when faced with many constructor parameters

Reminder from the book

在Java中,通常的解决可选构造参数的方式是使用可伸缩构造器(telescoping constructor)。当使用可伸缩构造器时,需要为每种不同的参数集合定义构造方法,比如:

// 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的例子是how we define custom views

尽管可伸缩构造器在JVM世界很流行,Effective Java 认为对于较大较复杂的类应该使用构建者模式(Builder pattern)。构建者模式首先以一种可读性较强的方式收集参数,然后对参数进行校验,最后实例化对象:

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可以作为工厂方法使用

Named optional parameters

具名可选参数在大多数情况下是一个更好的选择,相对于构建者模式,具名可选参数的声明和使用都更为简洁,表达能力更强:

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")
复制代码

使用具名可选参数的构造器拥有构建者模式的大多数优点:

  • 参数很清晰,使用者在设置参数时可以看到每个参数的名字
  • 可以以任何顺序设置参数
  • 修改起来相对可伸缩构造器更为容易(甚至比构建者模式更容易)

但是如果我们希望参数不同时创建不同的变种呢?比如当参数集合不同时创建不同的dialog

构建者模式:

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")
复制代码

同样在这个例子中,我们可以看到具名可选参数相对构建者的优点:

  • 更短--构造器或工厂方法要比构建者更容易实现。不需要声明属性的名字4次(分别在属性、方法、参数、构造器中);不需要声明属性的类型3次(分别在属性、参数、构造器中)。这是很重要的一点,因为当我们需要修改时,只需修改一处就可以了
  • 更干净--当你想要知道实例是如何被构建的,只需要查看一个方法即可,而不是整个Builder类。实例被如何持有?如何交互?这些问题在Builder较大时并没有那么明显
  • 不会出现并发问题--这是一个比较少见的问题,Kotlin中函数参数时immutable的,而Builder类中的属性是mut的,因此使用构建者模式更难实现线程安全

一个使用构建者模式的优点是,设置完参数的Builder可以作为工厂使用,但由于这种情况使用比较少,所有该优点不是很突出。

另外一个关于构建者模式的讨论是,可以对Builder设置部分参数,然后将Builder传递出去。这种情况下我们就可以定义方法创建不完全设置的Builder,交由方法的调用者继续设置。如果想要使用构造器或工厂方法达到相似的效果,我们需要使用自动柯里化(Auto-currying),这在Kotlin中是有可能实现的。

大部分情况下,你应该优先考虑使用具名可选参数而不是构建者模式。

DSL for object construction

如果我们想要设置具有多个处理函数(handler)的监听者(listener)。经典的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 ->
       // ...
    }
)
复制代码

Simple DSL when we already have builder

假设我们使用一个由库提供的dialog,库为dialog提供了一个Builder作为创建方法:

val dialog1 = Dialog.Builder("Some title")
        .setText("Great dialog")
        .setOnAccept { toast("I was clicked") }
        .build()
复制代码

我们可以实现非常简单的DSL Builder:

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") }
}
复制代码

(我们可以像设置属性一样设置text,前提是Builder使用Java定义的)

这种方式下我们利用的DSL的优势同时保留的较为简洁的定义。同时展示了DSL和构建者模式具有很多共同之处。

Summary

Effectiva Java中的观点在Kotlin中依旧有效。但是在Kotlin中我们拥有更有效的方式--具名可选参数。

转载于:https://juejin.im/post/5c68eaacf265da2d8a55a20a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值