重新定义任何不以下划线开头的 Ruby 方法理论上是否安全?
例如,如果您确实需要知道对象的 id 是什么,那么修改 Object#object_id
理论上是否安全,因为总有 Object#__id__
?
For example, is it theoretically safe to modify Object#object_id
since there's always Object#__id__
if you really need to know what an object's id is?
Background: Curiosity piqued by What's another name for object_id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在一个理想的系统中,所有内容都被完美记录,并且所有使用代码的人都知道什么被重新定义和修补 - 那么是的,也许吧。
但众所周知,这样的情况很少存在。就我个人而言,我认为修补
Kernel
、Class
、Module
或Object
中已定义的任何内容是禁忌(除非您在框架级别执行此操作。)最终,我相信最小意外原则应该渗透到所有级别的编码决策中。
In an ideal system where everything is perfectly documented and all people working with the code are aware of what's been re-defined and patched - then yes, maybe.
But as we all know, such situations rarely exist. Personally, I feel that patching anything already defined in
Kernel
,Class
,Module
orObject
is a no-no (unless you're doing it at a framework level.)Ultimately, I believe that Principle of Least Surprise should permeate coding decisions at all levels.
好吧,我认为我们可能更关心现实而不是理论。事实上,人们不会使用 __X__ 版本,除非他们意识到您已经覆盖并完全提升了默认行为。权力越大,责任越大;小心使用猴子补丁,切勿引入意外行为。最好只是向类中添加一个新方法。
Well, I think we are probably more concerned with reality than theory here. The fact is, people aren't going to use the
__X__
version until they realize that you have overriden and completely jacked up the default behavior. With power comes responsibility; use monkey-patching carefully and never introduce unexpected behavior. Better just to add a new method to the class instead.