- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 332字
- 2021-06-25 20:49:30
Creating an email – the Kotlin way – second attempt
Let's try a fluent setter approach, instead. We'll have only mandatory fields in our constructor, and all of the others will become setters. So to create a new email, we no longer need to do the following:
val mail = Mail("manager@company.com") mail.title("Ping") mail.cc(listOf<String>())
Instead, we will do the following:
Mail("manager@company.com").title("Ping").cc(listOf<String>())
Fluent setters allow us to chain one set call to another.
That's a lot nicer for a couple of reasons:
- The order of fields can now be arbitrary, unlike the order used with the constructor.
- It's clearer which field is being set; no more need for comments.
- Optional fields don't need to be set at all. As an example, the CC field is set while the BCC field is omitted.
Let's look at one way of implementing this approach. There are other convenient ways to do this, which we'll discuss in Chapter 10, Idioms and Anti-Patterns:
data class Mail(// Stays the same private var _message: String = "", // ...) { fun message(message: String) : Mail { _message = message return this } // Pattern repeats for every other variable }
Using underscores for private variables is a common convention in Kotlin. It allows us to avoid repeating the phrase this.message = message and mistakes, such as message = message.
This is nice and is very similar to what we may achieve in Java, although we did have to make our message mutable.
We can also implement a full-blown builder design pattern, of course:
class MailBuilder(val to: String) { private var mail: Mail = Mail(to) fun title(title: String): MailBuilder { mail.title = title return this }
// Repeated for other properties fun build(): Mail { return mail } }
You can use it to create your email in the following way:
val email = MailBuilder("hello@hello.com").title("What's up?").build()
But Kotlin provides two other ways that you may find even more useful.
- C++程序設計(第3版)
- The Android Game Developer's Handbook
- Programming ArcGIS 10.1 with Python Cookbook
- Bulma必知必會
- 深度學習:算法入門與Keras編程實踐
- Python面向?qū)ο缶幊蹋簶嫿ㄓ螒蚝虶UI
- Learning Salesforce Einstein
- 小學生C++創(chuàng)意編程(視頻教學版)
- 零基礎學單片機C語言程序設計
- Java EE企業(yè)級應用開發(fā)教程(Spring+Spring MVC+MyBatis)
- Monitoring Docker
- Python數(shù)據(jù)預處理技術與實踐
- 計算機程序的構造和解釋(JavaScript版)
- Web開發(fā)新體驗
- Java服務端研發(fā)知識圖譜