考虑到这两种方法:
方法 1
module DomainCRUD =
let getWhere collection cond = ...
module DomainService =
let getByCustomerId f customerId =
f(fun z -> z.CustomerId = customerId)
// USAGE:
let customerDomains = DomainCRUD.getWhere collection
|> DomainService.getByCustomerId customerId
方法 2
type DomainCRUD(collection) =
member x.GetWhere cond = ...
type DomainService(CRUD) =
member x.GetByCustomerId customerId =
CRUD.GetWhere(fun z -> z.CustomerId = customerId)
// USAGE:
let domainService = new DomainService(new DomainCRUD(collection))
let customerDomains = _domainService.GetByCustomerId(customerId)
哪一个最适合函数式编程?我认为方法 1
会,但每次都调用 DomainCRUD.GetWhere collection
感觉有点多余。
哪个是最灵活且“可读”的?
最佳答案
方法 1,原因如下:
- 与类关联的函数不是curried但与模块相关的那些是。这意味着您可以部分应用模块内的函数来实现通常使用 OO 代码中的 DI 框架完成的操作。 (请参阅丹尼尔的评论)
- 您可以省略模块限定
DomainCRUD.GetWhere
简单地open DomainCrud
. - 除了打开模块之外,您还可以将其标记为
[<AutoOpen>]
或(相反)[<RequireQualifiedAccess>]
它提供了类所不具备的额外灵活性。 - 基于模块的方法不太冗长。
关于f# - 模块还是类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20802817/