为什么在Ruby中使用类变量被视为“代码异味"? [英] Why is using a class variable in Ruby considered a 'code smell'?

查看:116
本文介绍了为什么在Ruby中使用类变量被视为“代码异味"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Reek ,创建一个类变量被认为是代码异味".这背后的解释是什么?

According to Reek, creating a class variable is considered a 'code smell'. What is the explanation behind this?

推荐答案

您可以在

类变量构成全局运行时状态的一部分,因此使系统的某个部分容易偶然或无意地依赖于系统的另一部分.因此,系统变得更容易出现问题,因为在此更改某些内容会破坏该位置的某些内容.特别是,类变量会使设置测试变得困难(因为测试的上下文包括所有全局状态).

Class variables form part of the global runtime state, and as such make it easy for one part of the system to accidentally or inadvertently depend on another part of the system. So the system becomes more prone to problems where changing something over here breaks something over there. In particular, class variables can make it hard to set up tests (because the context of the test includes all global state).

从本质上讲,这是全球状态的体现,几乎被普遍认为 evil ,因为它会使测试更加困难,并导致类/程序结构更加脆弱.

Essentially, it's a manifestation of global state, which is almost universally considered evil, because it makes tests more difficult and results in a much more fragile class/program structure.

此堆栈溢出问题可能也值得一读,这表明了主要问题使用类变量:如果有任何类从您的类继承并修改了该类变量,则该变量的每个实例都会更改,甚至从父级开始!可以理解,这可以让您轻松地用脚射击自己的脚,因此,除非您非常小心,否则最好避免使用它们.

This Stack Overflow question may also be worth reading, which shows the main problem with class variables: if any class inherits from your class and modifies the class variable, every instance of that variable changes, even from the parent! This understandably gives you a way to shoot yourself in the foot easily, so it may be best to avoid them unless you're very careful.

还值得将类变量与类实例变量进行比较. 这个问题有一些很好的例子来说明用法的不同,但是本质上,类变量是共享的,而类实例变量是不共享的.因此,为避免不必要的副作用,类实例变量几乎总是您想要的.

It's also worth comparing class variables with class instance variables. This question has a few good examples which illustrate the usage differences, but in essence class variables are shared, whereas class instance variables are not shared. Therefore, to avoid unwanted side effects, class instance variables are almost always what you want.

这篇关于为什么在Ruby中使用类变量被视为“代码异味"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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