Project

General

Profile

Actions

Feature #6308

open

Eliminate delegation from WeakRef

Added by headius (Charles Nutter) almost 12 years ago. Updated over 2 years ago.

Status:
Assigned
Target version:
-
[ruby-core:<unknown>]

Description

WeakRef's delegation features are a really awful pattern that should not be allowed in future versions of Ruby.

WeakRef makes no guarantees as to the liveness of its contained object. It can be collected at any time if there are no strong references to it.

WeakRef currently uses delegation to pass method calls through to the contained object. This encourages a pattern where a WeakRef is passed to methods that expect to have a reference to the underlying object, making it appear to be that object.

Unfortunately, this is never a good idea. Because the object can be collected at any time, you may get a nil reference from getobj arbitrarily in code that tries to call methods against the given WeakRef. That means using WeakRef as a delegate will always result in unreliable code, and errors may happen for inexplicable reasons.

I believe Ruby 2.0 should eliminate WeakRef's delegation features and make it a simple reference holder. There's no safe way to use a weak reference except to grab a reference to the object, check that it is alive (non-nil) and then proceed with the use of the object, as follows:

obj = weakref.getobj
raise AppropriateError unless obj
obj.do_something
obj.do_something_else

Along with eliminating delegation, I would recommend simply making the get method #get, since the uglier #getobj is only named that way because it is not delegated.


Files

0001-weakref.rb-non-delegation.patch (1.63 KB) 0001-weakref.rb-non-delegation.patch nobu (Nobuyoshi Nakada), 10/31/2013 02:07 PM

Related issues 1 (1 open0 closed)

Related to Ruby master - Feature #6309: Add a reference queue for weak referencesAssignedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0