Tips & Tricks - ByRef object passing
Today, I was reading some source code, and encountered the following method signature:
Method SendRequestSync(pRequest As %Library.Persistent, ByRef pResponse As %Library.Persistent)
And I immediately thought, why is there a ByRef?
Beforehand, I was under a (correct) assumption that objects are always passed by a reference, without exception. So, what does ByRef does here? A quick search in documentation yielded information on ByRef for non-object variables , but it was not what I was searching for.
Turns out that you can pass a reference by reference therefore allowing reference modification in a called code. To clarify, consider this example:
Class Utils.ObjByRef [ Abstract ]
{
/// Do ##class(Utils.ObjByRef).Test()
ClassMethod Test(UseByRef As %Boolean = {$$$YES})
{
Set Obj = {}
Set Obj.Property = 1
Write "At the begining ",Obj.Property,!
Do ..RefMethod(Obj)
Write "After Value pass ",Obj.Property,!
Do ..RefMethod(.Obj)
Write "After ByRef pass ",Obj.Property,!
}
ClassMethod RefMethod(ByRef Obj)
{
Set Obj = {}
Set Obj.Property = 500
}
}
It produces the following output:
>Do ##class(Utils.ObjByRef).Test() At the begining 1 After Value pass 1 After ByRef pass 500
In the first case we pass object reference by value, so if the called code changes the reference, the caller doesn't know about it. In the second case the reference is also passed by reference, so if the called code modifies the reference, the caller would get a new reference.
Do you use this feature? How?