- 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.
推薦閱讀
- 程序設計與實踐(VB.NET)
- Instant Typeahead.js
- C語言程序設計
- Quarkus實踐指南:構建新一代的Kubernetes原生Java微服務
- OpenShift在企業中的實踐:PaaS DevOps微服務(第2版)
- Ext JS 4 Web Application Development Cookbook
- 深入理解Elasticsearch(原書第3版)
- 利用Python進行數據分析
- Advanced Express Web Application Development
- Mastering Backbone.js
- JavaScript腳本特效編程給力起飛
- Mastering AWS Security
- Cocos2d-x Game Development Blueprints
- 移動增值應用開發技術導論
- 零基礎學Python編程(少兒趣味版)