Skip to content

Instantly share code, notes, and snippets.

@rinotc
Created May 20, 2022 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rinotc/37dc90e5f937e2374481f1a356587679 to your computer and use it in GitHub Desktop.
Save rinotc/37dc90e5f937e2374481f1a356587679 to your computer and use it in GitHub Desktop.
class Person private (val firstName: String, val lastName: String, val age: Int)
object Person {
class Builder {
var firstName: String = ""
var lastName: String = ""
var age: Int = 0
private var hasFirstName: Boolean = false
private var hasLastName: Boolean = false
def setFirstName(firstName: String): Builder = {
this.firstName = firstName
this.hasFirstName = true
this
}
def setLastName(lastName: String): Builder = {
if (!hasFirstName) {
throw new IllegalStateException("先にfirstNameをセットしなければならない")
}
this.lastName = lastName
this.hasLastName = true
this
}
def setAge(age: Int): Builder = {
this.age = age
this
}
def build: Person = {
if (!hasLastName) {
throw new IllegalStateException("先にlastNameをセットしなければならない")
}
new Person(firstName, lastName, age)
}
}
}
@rinotc
Copy link
Author

rinotc commented May 20, 2022

下記の type-safe builder パターンをクラスの内部状態で表現するこのようになる。
type-safe builderでは、型パラメータによって呼び出し状態を判定していたが、これはこのように呼び出したかどうかをもつフラグを持ち、そのフラグ状態によって事前条件違反をとして例外を投げる実装になる。
この場合は判定が実行時になる。
https://gist.github.com/rinotc/3e56f67a7ee938f4744025733ce1923c#file-typesafebuildersample-scala

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment