是不是的形式直接在ruby中使用实例vars? [英] is it bad form to use instance vars directly in ruby?

查看:182
本文介绍了是不是的形式直接在ruby中使用实例vars?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你应该总是在ruby中创建访问游标(用于读和/或写)吗?如果你有一个类不打算在外面重用,我不能直接使用实例变量?

Should you always create accesssors (for reading and/or writing) in ruby? If you have a class that's not meant to be reused outside, can't I just use instance variables directly?

我遇到的问题之一是它的问题,

One of the problems I ran into is that it's problematic to stub out @instance_vars in tests.

推荐答案

实例变量不会在测试中存在事情,当谈到测试。

Instance variables don't matter when it comes to testing. You should be testing your methods, in order to verify that they produce the correct results.

当您定义属性的阅读器方法时,您应该测试您的方法,以验证它们是否产生正确的结果。你将这个属性暴露给世界。无论属性的值是来自实例变量,数据库,文件,运行时计算还是其他都没关系。人们可以调用该方法来获取值。

When you define a reader method for an attribute, you expose that attribute to the world. It doesn't matter if the value of the attribute comes from an instance variable, a database, a file, runtime computation or whatever. People can just call the method to obtain the value.

同样,当为属性定义一个writer方法时,你可以让所有人知道它们可以设置它,如果他们需要。

Similarly, when you define a writer method for an attribute, you are letting everybody know that they can set it, if they need to. It doesn't matter where the value goes to.

只有您的方法定义了您的公共API。

Only your methods define your public API. Everything else is an implementation detail.

在类定义中,直接访问实例变量肯定没有什么危害:

Within your class definition, there is certainly no harm in accessing instance variables directly:

@variable = :value

调用方法如果简单的赋值是你需要的。当然,有时候你需要更复杂的功能。延迟初始化,例如:

There's no reason to call methods if simple assignments are all you need. Of course, sometimes you need more sophisticated functionality. Lazy initialization, for example:

def variable
  @variable ||= :value
end

# ...

variable.to_s

如果您的方法仅供内部使用,则不应将其包含在公共API中。标记为私人:

If your method is for internal use only, you should not include it in your public API. Mark it as private:

private :variable

说实话,Ruby中没有什么是真正的锁定。即使没有setter方法,如果他们真的想要的话,人们可以很容易地篡改你的对象:

To be honest, though, nothing is really locked down in Ruby. Even without setter methods, people can easily tamper with your object if they really want to:

class << (object = Object.new)
  private
  def variable; @variable end
end

object.variable
# NoMethodError: private method `variable' called

# send bypasses access control
object.send :variable
# => :value

object.instance_variables
# => [:@variable]
object.instance_variable_get :@variable
# => :value

object.instance_variables.each do |variable|
  object.instance_variable_set variable, nil
end
object.instance_variable_get :@variable
# => nil

这篇关于是不是的形式直接在ruby中使用实例vars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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