Skip to main content

Defining Method Generators

Defining Method Generators

To define a method generator, do the following:

  1. Define a method and set its CodeMode keyword to objectgenerator.

  2. In the body of the method, write code that generates the actual method code when the class is compiled. This code uses the %code object to write out the code. It will most likely use the other available objects as inputs to decide what code to generate.

The following is an example of a method generator that creates a method that lists the names of all the properties of the class it belongs to:

ClassMethod ListProperties() [ CodeMode = objectgenerator ]
{
    For i = 1:1:%compiledclass.Properties.Count() {
        Set prop = %compiledclass.Properties.GetAt(i).Name
        Do %code.WriteLine(" Write """ _ prop _ """,!")
    }
    Do %code.WriteLine(" Quit")
    Quit $$$OK
}

This generator will create a method with an implementation similar to:

 Write "Name",!
 Write "SSN",!
 Quit

Note the following about the method generator code:

  1. It uses the WriteLine method of the %code object to write lines of code to a stream containing the actual implementation for the method. (You can also use the Write method to write text without an end-of-line character).

  2. Each line of generated code has a leading space character. This is required because ObjectScript does not allow commands within the first space of a line. This would not be the case if our method generator is creating Basic or Java code.

  3. As the lines of generated code appear within strings, you have to be very careful about escaping quotation mark characters by doubling them up ("").

  4. To find the list of properties for the class, it uses the %compiledclass object. It could use the %class object, but then it would only list properties defined within the class being compiled; it would not list inherited properties.

  5. It returns a status code of $$$OK, indicating that the method generator ran successfully. This return value has nothing to do with the actual implementation of the method.

Specifying CodeMode within a Method Generator

By default, a method generator will create a code method (that is, the CodeMode keyword for the generated method is set to code). You can change this using the CodeMode property of the %code object.

For example, the following method generator will generate an ObjectScript expression method:

Method Double(%val As %Integer) As %Integer [ CodeMode = objectgenerator ]
{
    Set %code.CodeMode = "expression"
    Do %code.WriteLine("%val * 2")
}
FeedbackOpens in a new tab