- 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.
- Redis入門指南(第3版)
- 差分進化算法及其高維多目標優化應用
- 編譯系統透視:圖解編譯原理
- Hands-On Microservices with Kotlin
- 利用Python進行數據分析(原書第3版)
- Hands-On Reinforcement Learning with Python
- C語言程序設計
- Django 3.0入門與實踐
- Visual Basic程序設計習題與上機實踐
- Spring Boot+MVC實戰指南
- Learning Splunk Web Framework
- 創意UI Photoshop玩轉移動UI設計
- Python預測分析實戰
- INSTANT Premium Drupal Themes
- 計算機系統解密:從理解計算機到編寫高效代碼