Friday, January 2, 2009

Static fields and methods are unnecessary

Happy new Year! Right now I'm in Hilton Head, South Carolina on the last day of a family vacation. (Ah, vacation.)

I've been thinking quite a bit lately about how to design a very simple dynamic object-oriented language along the lines of Ruby. Every value should be an instance of an object, etc.

One ugliness that I wanted to avoid was the need for static fields and methods. However, for things like the standard input and output streams, you don't want to have to create new instances of these objects every time they are needed.

Today it occurred to me that all you really need is a language mechanism to define "singleton classes". A singleton class defines a single instance at runtime. Singleton classes are a convenient place to stash things like standard input and output streams.

module System::IO {
field in;
field out;
field err;

method init() { = new System::InputStream(:stdin);
self.out = new System::OutputStream(:stdout);
self.err = new System::OutputStream(:stderr);
Here, the keyword "module" means singleton class.

Now, consider some code where this singleton class (System::IO) is used:
import System::IO;

IO.out.print("Hello, world\n");
The import directive lets the compiler know that in this translation unit, the identifier "IO" will refer to the instance of the singleton class "System::IO". As long as some runtime magic can produce a reference to the instance of a singleton class, all field and method accesses are done through ordinary object references. No static fields or methods needed.

No comments: