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

175 阅读9分钟
原文链接: mp.weixin.qq.com

码个蛋(codeegg) 第 859 次推文

作者:超凶的土拨鼠

链接:https://www.jianshu.com/p/24391815cea3

码妞看世界

Reminder from the book

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

// Kotlinclass 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, "")}// Usageval 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(https://www.intertech.com/Blog/android-custom-view-tutorial-part-1-combining-existing-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)    }}// Usageval 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)// Usageval 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)        }    }}// Usageval 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)}// Usageval 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)    }}// UsagetaskNameView.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()// Usageval dialog1 = Dialog("Some title") {     text = "Great dialog"     setOnAccept { toast("I was clicked") }}

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

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

Summary

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

相关文章:

今日问题:

看完今天你内容,你觉得什么是构建者?

专属升级社区:《这件事情,我终于想明白了》