Interpreter Project: Classes

Object oriented progamming. Some people love it, some hate it. I lean towards the love it side. It simply sits in my brain more comfortably than functional programming does. In any case, Ringo now has support for Classes and almost everything they entail. Inheritance will be added in the next and final section.

You can see my progress here.

Creating Instances

I like the approach taken to create instances of classes. Many languages introduce a keyword, such as 'new'. Other languages have a class method embedded in all classes, such as Ruby's BasicObject::new. For Lox it is as simple as turning the class name into a function call, like SomeClass(). This allowed for reusing the existing function call code, and also meant that no new keywords needed to be parsed. A good middle ground between the two approaches.


Seems like for every one thing I like about Lox there is something else that I don't like. The way properties are implemented is not how I would do it. Classes are open for adding properties at any time. All you have to do is assign a value to an identifier and the instance of the class now has that property.

// Declare a Class named Example.
class Example {}

// Create an instance of the Example class and store it in e.
var e = Example();

// Add a property named new_property to the instance.
e.new_property = "Some Data";

One of the tennets of Object Oriented programming is encapsulation. A class should hide its internal representation and provide a public interface for accessing or modifying that representation. Better yet, don't expose the internal representation at all and only provide methods that perform meaningful actions for the class.


Methods work as you would expect. The properties of a class are stored in the instance of the class because they can be different for each instance. Methods, however, are stored in the class itself because the methods are shared amongst all of the instances.

There is one weird feature the is allowed in this language. You can assign a method to a variable and call it at some point in the future. The interpreter creates a closure around the method in this case so that future calls to the method reference the environment at the time of assignment. I can't think of a case where that ability would actually come in handy, but it is kinda cool.

Moving Forward

The next section is Inheritance. Classes will get the ability to subclass each other and share data and behavior between themselves. It looks like a short chapter, so it should not take as long as this chapter did. This will wrap up the simple implementation, the next section starts on building a Virtual Machine implementation of Lox in C.

My plan is to work through that VM code and implement my own language rather than Lox. It will allow me to understand the concepts a bit deeper if I have to modify things to fit my purposes.