R 和 Stata 中全局变量的危险示例 [英] Examples of the perils of globals in R and Stata

查看:49
本文介绍了R 和 Stata 中全局变量的危险示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近与同学的对话中,我一直主张避免使用全局变量,除了存储常量.这是一种典型的应用统计类程序,每个人都编写自己的代码,并且项目规模很小,因此人们很难看到草率习惯带来的麻烦.

In recent conversations with fellow students, I have been advocating for avoiding globals except to store constants. This is a sort of typical applied statistics-type program where everyone writes their own code and project sizes are on the small side, so it can be hard for people to see the trouble caused by sloppy habits.

在谈论避免使用全局变量时,我主要关注以下全局变量可能引起麻烦的原因,但我想在 R 和/或 Stata 中提供一些示例 遵循原则(以及您可能认为重要的任何其他原则),我很难想出可信的原则.

In talking about avoidance of globals, I'm focusing on the following reasons why globals might cause trouble, but I'd like to have some examples in R and/or Stata to go with the principles (and any other principles you might find important), and I'm having a hard time coming up with believable ones.

  • 非局部性:全局变量使调试变得更加困难,因为它们使理解代码流变得更加困难
  • 隐式耦合:全局变量允许远距离代码段之间的复杂交互,从而打破了函数式编程的简单性
  • 命名空间冲突:常用名称(x、i 等)被重用,导致命名空间冲突

这个问题的一个有用的答案是一个可重复的和自包含的代码片段,其中全局变量会导致特定类型的问题,理想情况下是另一个代码片段,在其中更正了问题.如果需要,我可以生成更正的解决方案,所以问题的例子更重要.

A useful answer to this question would be a reproducible and self-contained code snippet in which globals cause a specific type of trouble, ideally with another code snippet in which the problem is corrected. I can generate the corrected solutions if necessary, so the example of the problem is more important.

相关链接:

全局变量不好

全局变量不好吗?

推荐答案

我也有幸为没有编程经验的本科生教授 R 语言.我发现的问题是,大多数关于全局变量不好的例子都相当简单,并没有真正理解这一点.

I also have the pleasure of teaching R to undergraduate students who have no experience with programming. The problem I found was that most examples of when globals are bad, are rather simplistic and don't really get the point across.

相反,我尝试说明最小惊讶原则.我使用了一些很难弄清楚发生了什么的例子.以下是一些示例:

Instead, I try to illustrate the principle of least astonishment. I use examples where it is tricky to figure out what was going on. Here are some examples:

  1. 我要求全班写下他们认为 i 的最终值是什么:

i = 10
for(i in 1:5)
    i = i + 1
i

部分班级猜对了.那么我问你应该写这样的代码吗?

Some of the class guess correctly. Then I ask should you ever write code like this?

在某种意义上,i 是一个正在改变的全局变量.

In some sense i is a global variable that is being changed.

以下代码返回什么:

x = 5:10
x[x=1]

问题在于x

以下函数是否返回全局或局部变量:

Does the following function return a global or local variable:

 z = 0
 f = function() {
     if(runif(1) < 0.5)
          z = 1
     return(z)
  }

答案:两者都有.再次讨论为什么这很糟糕.

Answer: both. Again discuss why this is bad.

这篇关于R 和 Stata 中全局变量的危险示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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