[翻译]Effective Java in Kotlin:2.

2019-02-17  本文已影响0人  超凶的土拨鼠

原文: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()

尽管构建者模式的声明和使用都较为繁琐,但该模式存在如下优点:

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")

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

一个使用构建者模式的优点是,设置完参数的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中我们拥有更有效的方式--具名可选参数。

上一篇下一篇

猜你喜欢

热点阅读