我是新的scala編程。我現在很困惑如何以異步和功能的方式聲明一個biz方法,方法實現應該包含許多日誌消息。作爲一個不好的做法,我寫了這樣的代碼:什麼是使用功能方式處理日誌消息的最佳做法
// trait
trait StoreService {
def create[Config]: Kleisli[Future, Config, Store]
}
// and the interpreter
trait StoreServiceInterpreter extends StoreService {
def create[Config]: Kleisli[Future, Config, Store] = Kleisli {cfg =>
// some implementation ...
log.info("bla bla bla ...")
// some implementation ...
// return a store
Store(...)
}
}
它的壞,導致實現與副作用,登錄INT東西的地方。所以,我改變了方法聲明是這樣的:
// trait
trait StoreService {
def create[Config]: Kleisli[Future, Config, Writer[Vector[String], Store]]
}
// and the interpreter
trait StoreServiceInterpreter extends StoreService {
def create[Config]: Kleisli[Future, Config, Writer[Vector[String], Store]] = Kleisli {cfg =>
// some implementation ...
// log.info("bla bla bla ...")
// some implementation ...
// return a store
Writer(Vector("bla bla bla...", Store(...))
}
}
使用作家,副作用被消除,但代碼是不明確的:
- 爲什麼作家回來了?
Writer[Vector[String], Store]
比Store
有更多的噪音,有什麼方法可以避免樣板代碼並保持無副作用? - 寫
log
不是臨時的!我應該使用:+
或++
操作來創建一個字符串矢量來存放消息,以添加日誌。我認爲這不是臨時記錄,就像在任何地方寫log.info(...)
一樣。
對我而言,我認爲日誌對我的程序的正確性不重要。所以我選擇不在我的代碼中模擬它們的副作用。我讚揚你對純FP的擁抱,並期待着答案。 – Stephen
是的,也許它可以更純粹 –