Are there pitfalls in using class modules as namespaces in VBA
VBA does not support namespaces (packages for Java poeple). Namespaces in other languages ββhelp avoid ambiguity and complement tools such as autocomplete member names.
One way to model namespaces in VBA is to declare what are static defacto methods in the Class module, and then declare a default instance of that class in the standard module. It's even a pattern that some Microsoft docs follow . You can also use this approach for pseudo-space placement.
Are you my peers expecting any technical problems using this approach?
This is not a poll question; I am not asking about orthodoxy or aesthetic conversion. I ask, "Will this cause problems? If so, what?"
Example:
' Class module called clsIOText Public Function ReadAllText(ByVal FileName As String) As String With New FileSystemObject With .OpenTextFile(FileName, ForReading) ReadAllText = .ReadAll .Close End With End With End Function ' Class module call clsIO Public Text As New clsIOText ' In a standard module somewhere Public IO As New clsIO ' Usage like a namespace ' 1. Fully qualified Debug.Print IO.Text.ReadAllText("C:\temp\example.txt") ' 2. With a namespace alias-like object Dim Text As clsIOText Text = IO.Text Debug.Print Text.ReadAllText("C:\temp\example.txt")
source to share
There are no other answers yet ...
The pitfalls I came up with are more constraints and bugs:
- You need to set the Instancing property for each class to "2 - PublicNotCreatable". Otherwise, if the project is compiled and then referenced by another project, the members will not appear in the Object Explorer (although they will still be used).
- You cannot declare external API declarations in a class module as Public. To expose them to code outside the class, you must make them
Declare
private and then create a public wrapper method. - This still does not allow for organizing types in namespaces - only collections of static methods.
- From queries and macros, you can only call global methods in a standard module. Therefore, to use any functions completed in namespace classes, you will need to define wrappers in a standard module, rephrasing the hierarchy.
source to share