- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 219字
- 2021-06-25 20:49:30
Creating an email – second attempt
Let's try a fluent setter approach instead. We'll have only mandatory fields in our constructor, and all others will become setters, so the creation of a new email would look something like this:
Mail("manager@company.com").title("Ping").cc(listOf<String>())
That's a lot nicer for many reasons:
- The order of fields can now be arbitrary, unlike with the constructor.
- It's clearer which field is being set, no need for comments anymore.
- 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 see one way of implementing this approach. There are other convenient ways to do it, 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 this.message = message and mistakes such as message = message.
This is nice, and very similar to what we may achieve in Java. Although we did have to make our message mutable now. But Kotlin provides two other ways that you may find even more useful.
推薦閱讀
- Java程序設計與開發
- Vue.js快速入門與深入實戰
- Instant Typeahead.js
- Python自然語言處理(微課版)
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- Android底層接口與驅動開發技術詳解
- Mastering JavaScript Design Patterns(Second Edition)
- OpenMP核心技術指南
- Java Web應用開發項目教程
- Cocos2d-x by Example:Beginner's Guide(Second Edition)
- 超簡單:Photoshop+JavaScript+Python智能修圖與圖像自動化處理
- 人人都能開發RPA機器人:UiPath從入門到實戰
- 每個人的Python:數學、算法和游戲編程訓練營
- VBA Automation for Excel 2019 Cookbook
- Test-Driven Java Development(Second Edition)