Classes

Classes in Grace 0.7 are simpler than they used to be. A class declaration creates a “factory method”, that is, a method that returns a new object. Writing:

declares a factory method that returns an object with readable fields
colour and name, a variable that counts the number of mice the cat has
eaten, and two methods to eat a mouse and to miaow. Other than
Grace’s multi-part method names, this syntax is pretty much the same,
say, as Python or Scala, and with pretty much the same semantics.

To create objects from  the class, we just request the method directly:

Note that we don’t need parens around the arguments, because they are already delimited by quotes.  If the arguments had been expressions, then we would need parens.

More advanced programmer might want to know that classes aren’t primitive.  The cat()colour() class declaration above is pretty much equivalent to the following method declaration:


The key difference between this design and earlier and the earliest designs are that in the earlier designs, class declarations made objects that had a single factory method.  The main reason for the change is that the new design is simpler.  Most Grace programs did not use the actual class object; they simply requested the factory method. Programmers can always explicitly make an object if they need one, by putting the class declaration inside an object declaration.  In particular, classes at the top-level of a module are already inside an object: the module object.  There is often no need for another one.

One situation in which an enclosing object is useful is when there are several alternative ways to construct instances.  For example, a graphics library might provide methods r()g()b() and h()s()l() for constructing new colors, as well as a small selection of constants yellow, purple, brown, etc. It makes sense to make all of these methods on a colour object; r()g()b() might be a class, while h()s()l() and the named colors might make requests on r()g()b() with appropriately calculated arguments. Like this:

The old “dotted class” syntax did not support such a use, because the automatically declared object could have only a single factory method.

Leave a Reply

Your email address will not be published. Required fields are marked *