最接近“私有静态最终”的 Ruby 表示形式和“公共静态最终”; Java中的类变量?

发布于 2024-08-24 16:28:58 字数 440 浏览 10 评论 0原文

给定下面的 Java 代码,在 Ruby 类中最接近表示这两个 static final 变量的是什么?而且,Ruby 中是否可以像 Java 中那样区分 private staticpublic static 变量?

public class DeviceController
{
  ...
  private static final Device myPrivateDevice = Device.getDevice("mydevice");
  public static final Device myPublicDevice = Device.getDevice("mydevice");
  ...
  public static void main(String args[])
  {
   ...
  }
}

Given the Java code below, what's the closest you could represent these two static final variables in a Ruby class? And, is it possible in Ruby to distinguish between private static and public static variables as there is in Java?

public class DeviceController
{
  ...
  private static final Device myPrivateDevice = Device.getDevice("mydevice");
  public static final Device myPublicDevice = Device.getDevice("mydevice");
  ...
  public static void main(String args[])
  {
   ...
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

青丝拂面 2024-08-31 16:28:58

Ruby 中确实没有等效的构造。

然而,看起来您正在犯一个典型的移植错误:您在 A 语言中有一个解决方案,并尝试将其翻译成 B 语言,而您真正应该做的是找出解决方案 >问题,然后找出如何用语言 B 解决它。

我无法真正确定您要从那个小代码片段中解决的问题是什么,但这里有一个如何在 Ruby 中实现它的可能想法:

class DeviceController
  class << self
    def my_public_device;  @my_public_device  ||= Device['mydevice'] end

    private

    def my_private_device; @my_private_device ||= Device['mydevice'] end
  end
end

这是另一个:(

class DeviceController
  @my_public_device  ||= Device['mydevice']
  @my_private_device ||= Device['mydevice']

  class << self
    attr_reader :my_public_device, :my_private_device
    private :my_private_device
  end
end

区别在于第一个示例是惰性的,它仅在第一次调用相应的属性读取器时初始化实例变量。第二个示例在类主体后立即初始化它们会被执行,即使它们从不需要,就像 Java 版本一样。)

让我们回顾一下这里的一些概念。

在 Ruby 中,就像在所有其他“适当的”(对于“适当的”的各种定义)面向对象语言中一样,状态(实例变量、字段、属性、槽、属性,无论您想如何称呼它们)总是< /em> 私有。 没有办法从外部访问它们。与对象通信的唯一方法是向其发送消息。

[注:每当我写“没办法”、“总是”、“唯一的办法”等之类的东西时,它实际上并不意味着“没有办法,除了反思”。在这种特殊情况下,例如,有 Object#instance_variable_set。]

换句话说:在 Ruby 中,变量始终是私有的,访问它们的唯一方法是通过 getter 和/或 setter 方法,或者,如 Ruby 中所称,属性读取器和/或写入器。

现在,我一直在写实例变量,但在Java示例中我们有静态字段,即变量。嗯,在 Ruby 中,与 Java 不同,类也是对象。它们是 Class 类的实例,因此,就像任何其他对象一样,它们可以具有实例变量。因此,在 Ruby 中,类变量的等价物实际上只是一个标准实例变量,它属于一个恰好是类的对象。

(还有类层次结构变量,用双@符号@@sigil表示。这些真的很奇怪,你可能应该忽略它们。类层次结构变量在整个类层次结构中共享,即它们所属的类,其所有子类及其子类及其子类......以及所有这些类的所有实例实际上,它们更像是全局变量而不是类变量。 var 而不是 @@var,因为它们与全局变量的关系比实例变量更密切。它们并非完全无用,但很少有用。)

因此,我们已经介绍了“field”部分(Java field == Ruby 实例变量),我们已经介绍了“public”和“private”部分(在 Ruby 中,实例变量始终是私有的,如果你想将它们设为公共,请使用公共 getter/setter方法)并且我们已经介绍了“静态”部分(Java 静态字段 == Ruby 类实例变量)。那么“最后”部分呢?

在 Java 中,“final”只是“const”的一种有趣的拼写方式,设计者避免使用这种方式,因为 C 和 C++ 等语言中的 const 关键字被巧妙地破坏了,他们不想让人们感到困惑。 Ruby确实有常量(以大写字母开头表示)。不幸的是,它们并不是真正恒定的,因为尝试修改它们,同时生成警告,实际上是有效的。因此,它们更多的是一种约定,而不是编译器强制执行的规则。然而,常量更重要的限制是它们始终是公共的。

所以,常量几乎是完美的:它们不能被修改(嗯,它们不应该被修改),即它们是final,它们属于一个类(或模块) ,即它们是静态的。但它们始终是public,因此不幸的是它们不能用于建模private static final 字段。

这正是思考问题而不是解决方案的关键所在。你想要什么?您想要

  1. 属于一个类的状态,
  2. 只能读取不能写入,
  3. 只能初始化一次并且
  4. 可以是私有的或公共的。

您可以实现所有这些,但方式与 Java 完全不同:

  1. 类实例变量
  2. 不提供 setter 方法,只有 getter
  3. 使用 Ruby 的 ||= 复合赋值来仅分配一次
  4. getter你

唯一需要担心的是,你没有在任何地方分配给 @my_public_device ,或者更好的是,根本不访问它。始终使用 getter 方法。

是的,这实现中的一个漏洞。 Ruby 通常被称为“成年人的语言”或“成年人同意的语言”,这意味着您不必让编译器强制执行某些事情,而只需将它们放入文档中,并简单地相信您的开发人员同伴已经学会了接触其他内容人们的隐私是粗鲁的……


一种完全不同的隐私方法是函数式语言中使用的方法:使用闭包。闭包是关闭其词法环境的代码块,即使在该词法环境超出范围之后也是如此。这种实现私有状态的方法在Scheme中非常流行,但最近也被Douglas Crockford等人推广。对于 JavaScript。这是 Ruby 中的一个示例:

class DeviceController
  class << self
    my_public_device, my_private_device = Device['mydevice'], Device['mydevice']

    define_method :my_public_device  do my_public_device  end
    define_method :my_private_device do my_private_device end

    private :my_private_device
  end # <- here the variables fall out of scope and can never be accessed again
end

请注意我的答案顶部的版本之间微妙但重要的区别:缺少 @ 符号。在这里,我们创建的是本地变量,而不是实例变量。一旦类主体结束,这些局部变量就会超出范围,并且永远无法再次访问。 只有定义两个 getter 方法的两个块仍然可以访问它们,因为它们关闭了类主体。现在,它们确实私有并且它们是最终,因为整个程序中唯一仍然可以访问它们的是纯< em>getter 方法。

这可能不是 Ruby 惯用的做法,但对于任何有 Lisp 或 JavaScript 背景的人来说都应该足够清楚了。它也非常优雅。

There really is no equivalent construct in Ruby.

However, it looks like you are making one of the classic porting mistakes: you have a solution in language A and try to translate that into language B, when what you really should do is figure out the problem and then figure out how to solve it in language B.

I can't really be sure what the problem is you are trying to solve from that small codesnippet, but here is one possible idea for how to implement it in Ruby:

class DeviceController
  class << self
    def my_public_device;  @my_public_device  ||= Device['mydevice'] end

    private

    def my_private_device; @my_private_device ||= Device['mydevice'] end
  end
end

Here's another:

class DeviceController
  @my_public_device  ||= Device['mydevice']
  @my_private_device ||= Device['mydevice']

  class << self
    attr_reader :my_public_device, :my_private_device
    private :my_private_device
  end
end

(The difference is that the first example is lazy, it only initializes the instance variable when the corresponding attribute reader is first called. The second one initializes them as soon as the class body is executed, even if they are never needed, just like the Java version does.)

Let's go over some of the concepts here.

In Ruby, as in every other "proper" (for various definitions of "proper") object-oriented language, state (instance variables, fields, properties, slots, attributes, whatever you want to call them) is always private. There is no way to access them from the outside. The only way to communicate with an object is by sending it messages.

[Note: Whenever I write something like "no way", "always", "the only way" etc., it actually no means "no way, except for reflection". In this particular case, there is Object#instance_variable_set, for example.]

In other words: in Ruby, variables are always private, the only way to access them is via a getter and/or setter method, or, as they are called in Ruby, an attribute reader and/or writer.

Now, I keep writing about instance variables, but in the Java example we have static fields, i.e. class variables. Well, in Ruby, unlike Java, classes are objects, too. They are instances of the Class class and so, just like any other object, they can have instance variables. So, in Ruby, the equivalent to a class variable is really just a standard instance variable which belongs to an object which just happens to be a class.

(There are also class hierarchy variables, denoted with a double at sign @@sigil. Those are really weird, and you should probably just ignore them. Class hierarchy variables are shared across the entire class hierarchy, i.e. the class they belong to, all its subclasses and their subclasses and their subclasses ... and also all instances of all of those classes. Actually, they are more like global variables than class variables. They should really be called $$var instead of @@var, since they are much more closely related to global variables than instance variables. They are not entirely useless but only very rarely useful.)

So, we have covered the "field" part (Java field == Ruby instance variable), we have covered the "public" and "private" parts (in Ruby, instance variables are always private, if you want to make them public, use a public getter/setter method) and we have covered the "static" part (Java static field == Ruby class instance variable). What about the "final" part?

In Java, "final" is just a funny way of spelling "const", which the designers avoided because the const keyword in languages like C and C++ is subtly broken and they didn't want to confuse people. Ruby does have constants (denoted by starting with a capital letter). Unfortunately, they are not really constant, because trying to modify them, while generating a warning, actually works. So, they are more of a convention than a compiler-enforced rule. However, the more important restriction of constants is that they are always public.

So, constants are almost perfect: they cannot be modified (well, they shouldn't be modified), i.e. they are final, they belong to a class (or module), i.e. they are static. But they are always public, so unfortunately they cannot be used to model private static final fields.

And this is exactly the point where thinking about problems instead of solutions comes in. What is it that you want? You want state that

  1. belongs to a class,
  2. can only be read not written,
  3. is only initialized once and
  4. can be either private or public.

You can achieve all of that, but in a completely different way than in Java:

  1. class instance variable
  2. don't provide a setter method, only a getter
  3. use Ruby's ||= compound assignment to assign only once
  4. getter method

The only thing you have to worry about, is that you don't assign to @my_public_device anywhere, or better yet, don't access it at all. Always use the getter method.

Yes, this is a hole in the implementation. Ruby is often called a "grown-up's language" or a "consenting adults language", which means that instead of having the compiler enforce certain things, you just put them in the documentation and simply trust that your fellow developers have learned that touching other people's privates is rude ...


A totally different approach to privacy is the one used in functional languages: use closures. Closures are blocks of code that close over their lexical environment, even after that lexical environment has gone out of scope. This method of implementing private state is very popular in Scheme, but has recently also been popularized by Douglas Crockford et al. for JavaScript. Here's an example in Ruby:

class DeviceController
  class << self
    my_public_device, my_private_device = Device['mydevice'], Device['mydevice']

    define_method :my_public_device  do my_public_device  end
    define_method :my_private_device do my_private_device end

    private :my_private_device
  end # <- here the variables fall out of scope and can never be accessed again
end

Note the subtle but important difference to the versions at the top of my answer: the lack of the @ sigil. Here, we are creating local variables, not instance variables. As soon as the class body ends, those local variables fall out of scope and can never be accessed ever again. Only the two blocks which define the two getter methods still have access to them, because they close over the class body. Now, they are really private and they are final, because the only thing in the entire program which still has access to them is a pure getter method.

This is probably not idiomatic Ruby, but for anyone with a Lisp or JavaScript background it should be clear enough. It is also very elegant.

[旋木] 2024-08-31 16:28:58

我能想到的最接近最终变量的方法是将相关变量作为模块的实例变量:

class Device
    # Some static method to obtain the device
    def self.get_device(dev_name)
        # Need to return something that is always the same for the same argument
        dev_name
    end
end

module FinalDevice
    def get_device
        # Store the device as an instance variable of this module...
        # The instance variable is not directly available to a class that
        # includes this module.
        @fin ||= Device.get_device(:my_device).freeze
    end
end

class Foo
    include FinalDevice
    def initialize
        # Creating an instance variable here to demonstrate that an
        # instance of Foo cannot see the instance variable in FinalDevice,
        # but it can still see its own instance variables (of course).
        @my_instance_var = 1
    end
end

p Foo.new

p (Foo.new.get_device == Foo.new.get_device)

输出:

#<Foo:0xb78a74f8 @my_instance_var=1>
true

这里的技巧是,通过将设备封装到模块中,您只能通过该模块访问设备模块。在 Foo 类中,如果不直接作用于 Device 类或 ,就无法修改您正在访问的设备FinalDevice 模块。 FinalDevice 中的 freeze 调用可能合适,也可能不合适,具体取决于您的需求。

如果您想创建公共和私有访问器,您可以像这样修改 Foo

class Foo
    include FinalDevice

    def initialize
        @my_instance_var = 1
    end

    def get_device_public
        get_device
    end

    private
    def get_device_private
        get_device
    end

    private :get_device
end

在这种情况下,您可能需要修改 FinalDevice::get_device 来接受参数以及。

更新:@banister 指出 FinalDevice 中声明的 @fin 确实可以通过 Foo 的实例访问。我懒惰地假设,由于它不在 Foo#inspect 输出的默认文本中,所以它不在 Foo 内。

您可以通过更明确地使 @fin 成为 FinalDevice 模块的实例变量来解决此问题:

class Device
    def self.get_device(dev_name)
        dev_name
    end
end

module FinalDevice
    def get_device
        FinalDevice::_get_device
    end

    protected
    def self._get_device
        @fin ||= Device.get_device(:my_device).freeze
    end
end

class Foo
    include FinalDevice

    def get_device_public
        get_device
    end

    def change_fin
        @fin = 6
        @@fin = 8
    end

    private
    def get_device_private
        get_device
    end

    private :get_device
end

f = Foo.new
x = f.get_device_public
f.change_fin
puts("fin was #{x}, now it is #{f.get_device_public}")

它会正确输出:

fin was my_device, now it is my_device

The closest thing I can think of to a final variable is to put the variable in question as an instance variable of a module:

class Device
    # Some static method to obtain the device
    def self.get_device(dev_name)
        # Need to return something that is always the same for the same argument
        dev_name
    end
end

module FinalDevice
    def get_device
        # Store the device as an instance variable of this module...
        # The instance variable is not directly available to a class that
        # includes this module.
        @fin ||= Device.get_device(:my_device).freeze
    end
end

class Foo
    include FinalDevice
    def initialize
        # Creating an instance variable here to demonstrate that an
        # instance of Foo cannot see the instance variable in FinalDevice,
        # but it can still see its own instance variables (of course).
        @my_instance_var = 1
    end
end

p Foo.new

p (Foo.new.get_device == Foo.new.get_device)

This outputs:

#<Foo:0xb78a74f8 @my_instance_var=1>
true

The trick here is that by encapsulating the device into a module, you can only access the device through that module. From the class Foo, there's no way to modify which device you're accessing, without directly acting upon the Device class or the FinalDevice module. The freeze call in FinalDevice may or may not be appropriate, depending on your needs.

If you want to make a public and private accessor, you can modify Foo like this:

class Foo
    include FinalDevice

    def initialize
        @my_instance_var = 1
    end

    def get_device_public
        get_device
    end

    private
    def get_device_private
        get_device
    end

    private :get_device
end

In which case you'll probably need to modify FinalDevice::get_device to take an argument as well.

Update: @banister has pointed out that @fin as declared in FinalDevice is indeed accessible by an instance of Foo. I had lazily assumed that since it wasn't in the default text output by Foo#inspect, it wasn't inside Foo.

You can remedy this by more explicitly making @fin an instance variable of the FinalDevice module:

class Device
    def self.get_device(dev_name)
        dev_name
    end
end

module FinalDevice
    def get_device
        FinalDevice::_get_device
    end

    protected
    def self._get_device
        @fin ||= Device.get_device(:my_device).freeze
    end
end

class Foo
    include FinalDevice

    def get_device_public
        get_device
    end

    def change_fin
        @fin = 6
        @@fin = 8
    end

    private
    def get_device_private
        get_device
    end

    private :get_device
end

f = Foo.new
x = f.get_device_public
f.change_fin
puts("fin was #{x}, now it is #{f.get_device_public}")

Which correctly outputs:

fin was my_device, now it is my_device
孤星 2024-08-31 16:28:58
class DeviceController
  MY_DEVICE = Device.get_device("mydevice")
end

是的,如果需要,require 'device'

尽管没有什么可以阻止您在其他地方重新定义常量,除了警告:)

class DeviceController
  MY_DEVICE = Device.get_device("mydevice")
end

And yeah, require 'device' if needed.

Although nothing will stop you from redefining the constant somewhere else, except a warning :)

我不在是我 2024-08-31 16:28:58

Ruby 中的私有静态:

class DeviceController
    @@my_device = Device.get_device("mydevice")
end

Ruby 中的公共静态:

class DeviceController       
    def self.my_device; @@my_device; end

    @@my_device = Device.get_device("mydevice")
end

Ruby 不能有“final”:)

private static in Ruby:

class DeviceController
    @@my_device = Device.get_device("mydevice")
end

public static in Ruby:

class DeviceController       
    def self.my_device; @@my_device; end

    @@my_device = Device.get_device("mydevice")
end

Ruby can have no 'final' :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文