Comment on this RCR (edit wiki page) | RCRchive home

RCR 254: Latent object instantiation

submitted by mig on Tue May 18 2004 04:48:56 PM -0700

Status: pending


Abstract

Instance won't be created until any use of a variable pointing to that.

Problem

class Foo def initialize @xml = REXML::Document.new(...) end Here are methods in which @xml may or may not be used. It is good to have @xml instantiated at one place, but in the case it is not used, it's unuselessly to load XML. end

Proposal

@xml = REXML::Document.latent() where latent() is similar to new(), difference is that instantiation is done only when @xml is used.

Analysis

Implementation


Vote for this RCR

Strongly opposed [2]
Opposed [5]
Neutral [1]
In favor [0]
Strongly advocate [0]

Change the status of this RCR to:

accepted

rejected

withdrawn


The first question is: why? This RCR seems woefully thin, and not something that needs to be in the language as there are programming patterns around this. There are libraries and applications for which the act of instantiating an object is necessary even if the object is otherwise unused. A good example would be an object that represents a lock on a file; you may obtain the lock and not use the object until later (when you release the lock). If the lock is not instantiated immediately, then other processes may not see the file as locked. Austin Ziegler


Implementation is easy enough. Add Module#latent, and have it return a proxy object for that class.

The purpose of this RCR is that there is a resource that is very heavy that we may end up not using, i.e. a local Server, or Database connection, or Windowing toolkit, or Remote FTP/NFS filesystem. A file lock, or condition variable/monitor, and many others are too light weight to consider using this.

Austin, even if your implementation returns locks in the LOCK-ed position, the instantiation is separate from the behavior. Lock#new versus Lock#lock. Lock#latent would delay instantiation, the Lock#new call, until it was needed after the Lock#lock call. Your implementation may combine new and lock into a single call.

Suppose you have something that can display results in either GUI or console mode. Display is determined by an external random process, and can be displayed several times. During initialize, you don't want to instantiate the GUI unless the GUI is going to be used. So "@gui = Results::GUI.latent", and "@console = Results::Console.latent". Then when the external random process chooses GUI, the first time @gui is used it will instantiate and replace itself. This is also faster than "@gui ||= Results::GUI.new" when self#doGUI is called many times.

-chemdog


Fair enough. Is there a reason to put this in the core, though? Austin Ziegler.

Add comments here


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog