Returning Properties of an Object

QUESTION: I see how to write a GetProperty method to return a specfic property of my object, but I'd like to return a structure with all of the properties of my object. Doesn't it, like, take a lot of time and effort to do that?

ANSWER: Well, indeed it does, especially if you do it the way I do it.

But, fortunately, there are better ways, as Mike Galloy points out in an IDL Newsgroup thread. He suggests adding an ALL keyword to your GetProperty method and then using Create_Struct and Struct_Assign to return a structure of object properties. Here is an example program that demonstrates the idea.

   pro mg_instance_test::getProperty, all=all
      if (arg_present(all)) then begin
         all = create_struct(name=obj_class(self))
         struct_assign, self, all       endif    end 
   function mg_instance_test::init       self.a = 3.0       self.b = 'Hello'
      self.c = 123L       return, 1    end     pro mg_instance_test__define
      class = { mg_instance_test, a:0.0, b:'', c:0L }    end 

If the code above is compiled, it can be run like this.

   IDL> o = obj_new('mg_instance_test')    IDL> o->getProperty, all=all
   IDL> help, all, /structure
   ** Structure MG_INSTANCE_TEST, 3 tags, length=20, data length=20:
      A               FLOAT           3.00000
      B               STRING    'Hello'
      C               LONG               123    IDL> obj_destroy, o 

This is not a deep copy of the object, but it is a great way to copy simple objects whose member fields are simple IDL variables, including pointers and structures.

JD Smith has this to say about using Struct_Assign:

I use this technique a lot:


or simply

   snapshot={MYCLASS}    struct_assign,self,snapshot 

later apply snapshot:


This allows me to make snapshots of object data for the purpose of undoing changes, or examining how it was at a certain point in time. Keep a pointer to a list of these, and you have multiple undo. Add a text phrase when snapshotting ("Frobnoid change") and you can advertise "Undo Forbnoid change" and so on.

The lack of garbage collection starts getting painful at this point though (since older versions could refer to data newer versions have deleted).

Remember that snapshots of heap pointers (at whatever level in the heirarchy) are not immutable. If you want a deep copy, you can use the save/restore trick, first calling the new HEAP_NOSAVE routine on items you won't need a deep copy of. Or you can simply replicate certain heap data by hand (new=ptr_new(*old)). This reminds me that we're still lacking deep copy capability without hitting the disk.

Version of IDL used to prepare this article: IDL 7.0.3.

Web Coyote's Guide to IDL Programming