2019.02.13 Types of Classes: Immutable, Mutable Builder, and Mutable Writer. - GlenKPeterson/One-off_Examples GitHub Wiki

I'm a great fan of immutability and love Kotlin's data classes. But there are at least 2 other kinds of mutable classes that I commonly use or develop: Builders and Writers.

The ideal Builder typically has one or more required immutable properties and several mutable properties, each mutable property having a "setter" which returns the mutated-in-place builder object. Sometimes the "setters" are backed by lists or (sorted)sets and can be called multiple times, remembering all the values (or all the non-null values) they have been called with. For instance:

class ActualInput(
        private val name: String
) {
    private var autofocus = false
    fun autofocus(b: Boolean): ActualInput {
        autofocus = b
        return this
    }

    private var value: TaintedS? = null
    fun value(ts: TaintedS?): ActualInput {
        value = ts
        return this
    }

    private var id: String? = null
    fun id(s: String): ActualInput {
        id = s
        return this
    }

    fun toInput(): HtmlStringable {
        val o = HtmlB()
        o.p("<input type=\"text\" name=\"").p(name).p("\" value=\"")
                .pHtml(value).p("\"")
        if (id != null) {
            o.p(" id=\"").p(id).p("\"")
        }
        if (autofocus) {
            o.p(" autofocus")
        }
        o.p(" />")
        return o
    }
}

A handy side-effect of using a builder instead of exposing a public constructor is that you can control object creation. Common objects can be cached and reused. If the objects are immutable, this can be a big savings.

TODO: Re-read builder example from Josh Bloch and incorporate.

Writers are like Java's BufferedWriter, or FileWriter and pipe data to some underlying sink like a file or network connection.

There are probably many sub-categories, and maybe some additional top-level categories to go with these three, but these are the ones I work with daily. Kotlin does a lot to make immutable objects simple. Writers are equally easy/difficult to make in either Kotlin or Java. But neither language does anything to make Builders easy to write.