简体   繁体   English

如何打破F#中的函数依赖关系?

[英]How can I break a function dependency in F#?

I'd like to unit test fun1 without calling fun2. 我想对fun1进行单元测试而不调用fun2。

let fun2() =
    // Some complex function with lots of dependencies.
    1

let fun1() =
    fun2() * 2

What the best way to break the dependency between the two functions? 打破两个功能之间的依赖关系的最佳方法是什么?

I've tried a couple of different ways, but they just add clutter. 我尝试了几种不同的方法,但它们只会增加混乱。

Pass fun2 into fun1 将fun2传递到fun1

let fun1(fun2) =
    fun2() * 2

Convert to a class and override 转换为类并覆盖

type FunClass() =
    abstract member fun2 : unit -> int
    default x.fun2() = 1

    member x.fun1() =
        x.fun2() * 2

type FunClassMock() =
    override member x.fun2() = 1

Use stategy pattern 使用策略模式

type Fun1Class(fun2Class) =

    member x.fun1() =
       fun2Class.fun2() * 2

Use a variable 使用变量

let fun2Imp() =
    1

let mutable fun2 = fun2Imp

let fun1() =
    fun2() * 2

Is there a cleaner way? 有没有更清洁的方法?

It depends on your usage, but you could do something like this: 这取决于您的用法,但是您可以执行以下操作:

let fun2() =
    // Some complex function with lots of dependencies.
    1

let createFun1 fun2 =
    fun () -> fun2() * 2

let fun1 = createFun1 fun2

This is also useful for unit testing since you can test fun1 by simply passing a simple function in for fun2. 这对于单元测试也很有用,因为您可以通过简单地将一个简单的函数传递给fun2来测试fun1。

It isn't very flexible, but a compiler directive would work. 它不是很灵活,但是可以使用编译器指令。

let fun2() =
  #if TESTING
  1
  #else
  // Some complex function with lots of dependencies.
  #endif

Defining fun2 in separate modules and open ing the needed module is another option. 另一种选择是在单独的模块中定义fun2open所需的模块。

module Impl =
  let fun2() =
    // Some complex function with lots of dependencies.

module Testing =
  let fun2() = 1

Any way you do it (that I know of, at least) is going to "add clutter". 您所做的任何方式(至少我知道)都会“增加混乱”。 How about something like this? 这样的事情怎么样?

let fun1() = 
    fun1_impl(fun2)

let fun1_impl(fun2) =
    fun2() * 2

Then, in regular code, use fun1 , and in your tests, use fun1_impl . 然后,在常规代码中使用fun1 ,在测试中使用fun1_impl

In all generality, the argument passing seems the cleanest. 一般而言,通过的论点似乎是最干净的。

The clutter effect might not be tackled technically, but semantically : it comes from the fact that it seems a bit arbitrary, from the lack of meaning attached to "function1". 杂乱的影响可能不是从技术上解决的,而是从语义上解决的:这是因为它看起来有些武断,这是由于缺少对“ function1”的附加含义。

Is there may be a higher, more coherent, level that might be more meaningful in your code ? 在您的代码中是否可能有更高,更连贯的层次可能更有意义?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM