PreviousUpNext

5.3.13  Roll-Your-Own Objected Oriented Programming

There are about as many definitions of "object oriented programming" as there are object oriented languages, but implementation hiding and dynamic (runtime) binding of methods are central to most of them. We will discuss more elaborate approachs to object oriented programming in Mythryl later, later, but here is a very simple technique which is often enough for the job at hand.

The idea is to create some state which is shared by a set of functions but hidden from the rest of the program, and then to access those functions via a record of pointers to them.

For didactic clarity we will take as our example a simple counter which may be incremented, read or reset:

    #!/usr/bin/mythryl

    fun make_counter ()
        =
        {
            # Create counter state, initialized to zero:
            #
            count = REF 0;

            # Define our methods
            #
            fun increment () =  count := *count + 1;
            fun get       () = *count;
            fun reset     () =  count := 0;

            # Create and return record of methods:
            #
            { increment, get, reset };
        };


    # Demonstration of counter use:
    print "\n";

    counter = make_counter ();      printf "State of counter after creation  d=%d\n" (counter.get ());
    counter.increment ();           printf "State of counter after increment d=%d\n" (counter.get ());
    counter.reset ();               printf "State of counter after reset     d=%d\n" (counter.get ());

When run this script will print out:

    linux$ ./my-script

    State of counter after creation  d=0
    State of counter after increment d=1
    State of counter after reset     d=0

Things to note about this technique:

For an industrial strength example of this technique in action see the library graph implementation in src/lib/graph/oop-digraph.api and src/lib/graph/oop-digraph.pkg.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext