Skip links

Ring Language: Dynamic Behavior of Classes and Objects

We have been exploring the Ring Programming Language in the last two articles. Ring is a dynamic programming language with many interesting features. In today’s article, let us try to understand how this dynamic behavior is reflected in Classes and Objects.

In Ring, we can define classes at runtime. One way to do this is to execute a “script”. As part of the script, we can define a class, and so when the script is executed, the class gets “defined”. 

Look at the code fragment below:

Dynamic Class Creation
Dynamic Class Creation

When we execute this code, this is the output:

Output
Output

Being able to define classes at runtime is definitely interesting. What happens if we redefine this class, say, with a different structure?

Class Redefinition
Class Redefinition

That is not allowed! This results in an error at runtime:

Redefinition Not Allowed
Redefinition Not Allowed

Next, let us dynamically define another class that has a single method, and then invoke that method:

Another Class Dynamically Created
Another Class Dynamically Created

Here is the output:

Invoking Method Dynamically
Invoking Method Dynamically

What if we try to invoke a method that is not defined in the class?

Invoking an Undefined Method
Invoking an Undefined Method

Here is the runtime error:

Undefined Method Error
Undefined Method Error

This is along expected lines.

Reflection 

Ring has an interesting “Reflection” API. I am going to touch upon just three functions today. For more information, you can go through this article.

The first function we will consider is “methods()”. Given an object as argument, this function returns a list of methods supported by the object. We can then invoke the “discovered” methods.

Discovering Methods at Runtime
Discovering Methods at Runtime

This is the output:

Invoking the Discovered Method
Invoking the Discovered Method

No surprise here.

Next, using the “addmethod()” function, we can add a new method to an object. Likewise, there is an “addattribute()” function to add an attribute to an object:

Reflection API Example
Reflection API Example

And the output is:

The Output
The Output

What is peculiar and important to keep in mind is that  we are not adding the method and attribute to the “DynamicClass2” class, but only to a single instance of that class. This implies that if we create another object of this class and try to access the method or attribute that we just now added to the other object, we will get an error!

Here is a code fragment that shows this:

Changes are Object-Specific
Changes are Object-Specific

Here is the corresponding output:

This is the Proof
Error When Accessing Attribute

It is clear that Ring differs from other popular languages in the way Classes and Objects are handled. 

We will continue to explore other features of Ring in future articles. Here is the code used in today’s article.

Have a nice weekend!

Leave a comment