Skip to main content

Swizzling

Swizzling

If you open (load into memory) an instance of a persistent object, and use an object that it references, then this referenced object is automatically opened. This process is referred to as swizzling; it is also sometimes known as lazy loading.

For example, the following code opens an instance of Sample.Employee object and automatically swizzles (opens) its related Sample.Company object by referring to it using dot syntax:

 // Open employee "101"
 Set emp = ##class(Sample.Employee).%OpenId(101)

 // Automatically open Sample.Company by referring to it:
 Write "Company: ",emp.Company.Name,!

When an object is swizzled, it is opened using the default concurrency value of the class it is a member of, not the concurrency value of the object that swizzles it. See Specifying Concurrency Options.

A swizzled object is removed from memory as soon as no objects or variables refer to it.

Sometimes you might want to manually swizzle an object or check to see if an object is swizzled. For both of these tasks, you can use the property method <prop>GetSwizzled(). In the case of the Company property in the above example, calling CompanyGetSwizzled() swizzles the Company object and returns an OREF for the object. If you pass in a 1 as an argument, as in CompanyGetSwizzled(1), the method returns an OREF for the object, but only if it is already swizzled. Otherwise, it returns a null OREF.

As an example, in Terminal:

USER>set emp = ##class(Sample.Employee).%OpenId(102)
 
USER>set co = emp.CompanyGetSwizzled(1)
 
USER>if (co = "") {write "Company is not swizzled"} else {write co.Name}
Company is not swizzled
USER>set co = emp.CarGetSwizzled()
 
USER>if (co = "") {write "Company is not swizzled"} else {write co.Name}
Acme Company, Inc.
FeedbackOpens in a new tab