我有一些与数据库兼容的函数,对于每个函数,我都记录了一些有关更改的信息。
这样做:
case class DBResult[T](result: T, Seq[String])
trait DiffableBy[T] {
def -(old: T): Seq[String]
}
case class B1(..) extends DiffableBy[A1]
case class A1(..)
def f(..): DBResult[Result, Seq[String]] = {
..
val before = B1(..)
val after = A1(..)
futureRes.map(res => DBResult(res, before - after)
}
有很多不同的功能。当我调用f
函数时,很容易写日志左右,但这个日志是纯字符串并以一种方式计算。
但现在我想以不同的方式找到它们之间的区别。例如,假设有两个案例类b
和a
。当他们之间的一个字段不同时,请记录,当其他字段发送电子邮件等时
可以这样做:
trait Before
trait After
case class BeforeAndAfter(before: Before, after: After)
case class B1(..) extends Before
case class A1(..) extends After
case class DBResult[T](result: T, beforeAndAfter: BeforeAndAfter)
def f(..): DBResult[Result, BeforeAndAfter] = {
..
val before = B1(..)
val after = A1(..)
futureRes.map(res => DBResult(res, BeforeAndAfter(before, after))
}
.. // many more functions like f
// and then use it like this
case class EmailChanges(..)
case class LogChanges(..)
def ExtractEmailDiff(beforeAndAfter: BeforeAndAfter): Seq[EmailDiff] =
beforeAndAfter match {
case BeforeAndAfter(b: B1, a: A1) => { .. }
case BeforeAndAfter(b: B2, a: A2) => { .. }
case _ => Seq.empty[EmailDiff]
}
def ExtractLogDiff(beforeAndAfter: BeforeAndAfter): Seq[LogDiff] =
beforeAndAfter match {
case BeforeAndAfter(b: B3, a: A3) => { .. }
case BeforeAndAfter(b: B4, a: A4) => { .. }
case _ => Seq.empty[LogDiff]
}
但我不喜欢这里的模式匹配,因为很容易忘记覆盖一些情况。是否有更容易或更好的方法来做到这一点?