Quick review:
I've been writing API code which receives user input that can come as either an object or a value type - a problem outlined here.
In order to write an unknown data type to a variable, I first came up with this:
Public Sub LetSet(ByRef variable As Variant, ByVal value As Variant)
If IsObject(value) Then
Set variable = value
Else
variable = value
End If
End Sub
called like
Dim result As Variant
LetSet result, objectOrValueType()
However an alternate approach that I've come up with is the following:
Public Property Let LetSet(ByRef variable As Variant, ByVal value As Variant)
If IsObject(value) Then
Set variable = value
Else
variable = value
End If
End Property
called like
Dim result As Variant
LetSet(result) = objectOrValueType()
which I like because it feels closer to LetSet a = b
- the ultimate goal but one that I don't believe is possible.
Both live in standard modules and are functionally equivalent - the return value of objectOrValueType()
(some arbitrary function that generates the unknown data) is stored in result.
So I'm wondering which is better and is there anything I can do to improve on either approach? Any other feedback is, of course, also welcome.
NB, just to add some context, I've come across 2 use cases for this:
- A buffered list; this class is drip-fed data of unknown kind from some asynchronous process, and merges it into batches of fixed size - then raises an event when a new batch is ready. Because the internal data store is constantly being written to, I can't expose that, so I need some way to copy items to variant arrays for each batch and expose those in the event.
- Overloaded arithmetic functions; I've defined some
Add
method that can take integers and sum them with the+
operator. However I'm allowing classes to implementIAddable
and define their own response to theAdd
method; this implementation may return an object. So I need to be able to write the result of this calculation to the return variable of theAdd
method.
For the former I could use a Collection
and avoid the issue altogether as @Freeflow points out in their answer - but the batches are fixed size so an array makes more sense for me. For the latter, I don't see a way around using this approach, as the return type of the function is down to the user, not me.