Recently spotted something on web about using ByRef (instead of ByVal) arguments including both an aleady started AutoCAD Transaction instance and an already opened AutoCAD Architecture object, but wondered why. It is in VB.NET. Here is a cleaned up version.
Shared Function FindClassification(ByVal name As String,
ByRef tr As Transaction,
ByRef node As ClassificationTree) As ObjectId
Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor
Dim id As ObjectId = ObjectId.Null
If node Is Nothing Then
Return id
End If
If Not (node.Id.IsNull) Then
Dim classi As Classification = CType(tr.GetObject(node.Id, OpenMode.ForRead), Classification)
If classi.Name.Equals(name) Then
Return classi.ObjectId
End If
End If
If node.Children.Count > 0 Then
Dim child As ClassificationTree
For Each child In node.Children
id = FindClassification(name, tr, child)
If id.IsValid Then
Return id
End If
Next
End If
Return id
End Function
The function looks a bit advanced since recursion is applied. However, the logic and code inside the function has some issues, big or small, apart from the ByRef argument that we are going to focus on in this post.
• The node.Id.IsNull case is not addressed.
• The ‘ed’ variable is declared but not used.
• It seems the ‘node’ object is reopened with its own ObjectId. Why is that?
• Why use ObjectId.IsNull and ObjectId.IsValid alternatively rather than keep using a single consistent approach?
• Is ‘node.Children.Count > 0’ necessary?
• If the answer to the above question is yes, is ‘node.Children’ always valid (cannot be Nothing)?
• Would it not be better to use the following concise and reliable version?
For Each child As ClassificationTree In node.Children
id = FindClassification(name, tr, child)
If Not id.IsNull Then
Return id
End If
Next
Let’s back to the ByRef arguments. Are they areally necessary and good?
Through checking the code, it is obvious not since the ‘tr’ and ‘node’ are not supposed to be replaced (reassigned) with some newly started Transaction or created ClassificationTree inside the method after it returns. Even if the ‘tr’ and ‘node’ objects are supported to be updated of something inside the method, they do not have to be passed with ByRef either. Apparently, the author does not know the difference between ByVal and ByRef. It’s not a surprise since even experienced software developers can be confused about the ByVal and ByRef sometimes.
The leading edge AutoCAD .NET Addin Wizard (AcadNetAddinWizard) provides various project wizards, item wizards, coders and widgets to help program AutoCAD .NET addins.
Posted by: |