[英]How can I break a function dependency in F#?
我想对fun1进行单元测试而不调用fun2。
let fun2() =
// Some complex function with lots of dependencies.
1
let fun1() =
fun2() * 2
打破两个功能之间的依赖关系的最佳方法是什么?
我尝试了几种不同的方法,但它们只会增加混乱。
将fun2传递到fun1
let fun1(fun2) =
fun2() * 2
转换为类并覆盖
type FunClass() =
abstract member fun2 : unit -> int
default x.fun2() = 1
member x.fun1() =
x.fun2() * 2
type FunClassMock() =
override member x.fun2() = 1
使用策略模式
type Fun1Class(fun2Class) =
member x.fun1() =
fun2Class.fun2() * 2
使用变量
let fun2Imp() =
1
let mutable fun2 = fun2Imp
let fun1() =
fun2() * 2
有没有更清洁的方法?
这取决于您的用法,但是您可以执行以下操作:
let fun2() =
// Some complex function with lots of dependencies.
1
let createFun1 fun2 =
fun () -> fun2() * 2
let fun1 = createFun1 fun2
这对于单元测试也很有用,因为您可以通过简单地将一个简单的函数传递给fun2来测试fun1。
它不是很灵活,但是可以使用编译器指令。
let fun2() =
#if TESTING
1
#else
// Some complex function with lots of dependencies.
#endif
另一种选择是在单独的模块中定义fun2
并open
所需的模块。
module Impl =
let fun2() =
// Some complex function with lots of dependencies.
module Testing =
let fun2() = 1
您所做的任何方式(至少我知道)都会“增加混乱”。 这样的事情怎么样?
let fun1() =
fun1_impl(fun2)
let fun1_impl(fun2) =
fun2() * 2
然后,在常规代码中使用fun1
,在测试中使用fun1_impl
。
一般而言,通过的论点似乎是最干净的。
杂乱的影响可能不是从技术上解决的,而是从语义上解决的:这是因为它看起来有些武断,这是由于缺少对“ function1”的附加含义。
在您的代码中是否可能有更高,更连贯的层次可能更有意义?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.