当你不需要定义一些东西作为动态的to-redefs它定义东西作为动态的什么点? [英] What's the point of defining something as dynamic when you don't need to define something as dynamic to with-redefs it?

查看:139
本文介绍了当你不需要定义一些东西作为动态的to-redefs它定义东西作为动态的什么点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来, with-redefs 可以执行绑定到动态符号所能做的一切它没有需要 ^:dynamic 元数据的限制。所以我应该什么时候使用一个呢?

It seems to me that with-redefs can do everything that binding to a dynamic symbol can do, only it doesn't have the limitation of needing the ^:dynamic metadata. So when should I use one over the other?

推荐答案

除了需要 ^:dynamic $ c> binding 也创建只在当前线程中可见的绑定,而 with-redefs 创建的绑定在所有线程中可见。因此, with-redefs 是一个非常钝的工具,并有可能影响在同一个VM中运行的其他代码。我从来没有见过 with-redefs 在测试代码之外使用,也不应该是(至少在我看来)。

Aside from requiring the ^:dynamic metadata, binding also creates bindings that are only visible in the current thread, whereas the bindings made by with-redefs are visible in all threads. So, with-redefs is a very blunt tool and has the potential to affect other code running in the same VM. I've never seen with-redefs used outside of test code, nor should it be (at least in my opinion).

我会总结两者之间的区别,因为:

I would summarize the difference between the two as thus:


  • :dynamic 允许您以受控方式介绍一点动态行为。这是一个在API中定义扩展点的好方法,它让调用者远在调用链中改变代码的行为,而不必显式地将参数全部传递通过调用堆栈(其中一些甚至可能不是他们的代码)。

  • with-redefs 是一个免费的。它在测试中很有用。

  • binding with ^:dynamic allows you to introduce a little bit of dynamic behavior in a controlled fashion. It's a good way of defining extension points in an API that let callers far up the call chain change the behavior of your code without having to explicitly pass parameters all the way through the call stack (some of which might not even be their code).
  • with-redefs is a free-for-all. It's useful in testing, e.g. for mocking out entire sub-systems when the function under test has lots of dependencies.

声明一个var为 ^:dynamic 与使用earmuff命名动态vars(例如 * my-dynamic-var * )的约定一起,

Declaring a var as ^:dynamic, together with the convention of using earmuffs to name dynamic vars (e.g. *my-dynamic-var*), has the added bonus that it's a self-documenting way of advertising to callers that that part of your code can be modified dynamically.

总结:偏好 ^:动态 >和 binding 。在测试中使用 with-redefs ,并且作为最后一种手段动态改变未声明为 ^:dynamic (然后谨慎使用)。

In summary: prefer ^:dynamic and binding when writing APIs and production code. Use with-redefs in testing, and as a last resort to dynamically alter the behavior of vars beyond your control that weren't declared ^:dynamic (and then, use with caution).

这篇关于当你不需要定义一些东西作为动态的to-redefs它定义东西作为动态的什么点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆