これは何よりも設計上の問題です...
私は Scala のケース クラスがとても好きで、頻繁に使用しています。Options
ただし、多くの場合、 (Lift の) でパラメーターをラップし、Boxes
既定値を設定して、柔軟性を確保し、ユーザーがすべてのパラメーターを常に指定するとは限らないことを考慮しています。からこの慣習を採用したと思います。
私の質問は、これは合理的なアプローチですか? すべてがオプションである可能性があることを考えると、多くのボイラープレートとチェックがある可能性がありMap[String, Any]
ますMap
。
実際の例を挙げましょう。ここでは、送金をモデル化しています。
case class Amount(amount: Double, currency: Box[Currency] = Empty)
trait TransactionSide
case class From(amount: Box[Amount] = Empty, currency: Box[Currency] = Empty, country: Box[Country] = Empty) extends TransactionSide
case class To(amount: Box[Amount] = Empty, currency: Box[Currency] = Empty, country: Box[Country] = Empty) extends TransactionSide
case class Transaction(from: From, to: To)
比較的簡単に理解できると思います。この最も単純な例では、次のTransaction
ように宣言できます。
val t = Transaction(From(amount=Full(Amount(100.0)), To(country=Full(US)))
冗長だと思っていることはすでに想像できます。そして、すべてを指定すると:
val t2 = Transaction(From(Full(Amount(100.0, Full(EUR))), Full(EUR), Full(Netherlands)), To(Full(Amount(150.0, Full(USD))), Full(USD), Full(US)))
一方で、Full
どこにでも散らばらなければならないにもかかわらず、いくつかの優れたパターン マッチングを行うことができます。
t2 match {
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(country_from)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(country_to))) if country_from == country_to => Failure("You're trying to transfer to the same country!")
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(US)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(North_Korea))) => Failure("Transfers from the US to North Korea are not allowed!")
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(country_from)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(country_to))) => Full([something])
case _ => Empty
}
これは合理的なアプローチですか?を使用したほうがよいでしょうMap
か? または、ケース クラスを別の方法で使用する必要がありますか? ケースクラスの階層全体を使用して、異なる量の情報が指定されたトランザクションを表すのでしょうか?