Generics are a powerful feature that advanced LabVIEW developers have been requesting for a long time. If you don’t know what generics are, here is a description of the feature from Microsoft’s MSDN documentation:
[Generics] make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations…
In other words, generics allow you to develop APIs that are data type agnostic. The developer using your API gets to choose what type they wish to use with your functions. If you haven’t dealt with generics before, this might sound a lot like LabVIEW variants, but there is an important difference between variants and generics. Variants defer typing all the way to runtime, whereas generics require that the type be specified at compile time. This means that the compiler can check whether or not the user of your API is being consistent with the data type they have chosen.
For example, let’s say you want to make a linked list API. This API would allow users to add and remove elements in a linked list. But let’s say you want to enforce that all elements in the linked list are the same data type. The only way to accomplish this in LabVIEW is to rewrite the entire API for every possible data type. You would need a numeric linked list, a boolean linked list, a string linked list, a waveform linked list, and so on. This is obviously cumbersome and tedious. In addition, how do you handle custom data types like clusters or enums? There’s no good answer.
What’s frustrating, is that LabVIEW clearly has this feature somewhere under the hood. Let’s take a look at the queue API, as an example. When creating a queue using ‘Obtain Queue.vi’, you are required to specify the data type of the queue via the ‘element data type’ input. From that point on, when enqueuing or dequeuing from the queue, the compiler can ensure that you use the correct data type (resulting in a broken wire and broken run arrow if you don’t comply). Just like our linked list example, the queue API clearly implements generics, since it enforces type consistency at compile time, while allowing the user to use any data type (including clusters, classes, enums, etc).
It’s unfortunate that this feature seems to be present at some level in LabVIEW, but is not exposed to the developer. I’m sure if it were feasible to do so, NI would have exposed this functionality by now. I think there might be ways to get close to generic-like functionality using xnodes, but honestly I haven’t had enough experience with that particular form of LabVIEW black magic to say for sure. Perhaps that will be the topic of a future post. Until then, if you’ve ever used xnodes to try and implement generics, feel free to comment below!