Introduce Creation Object

last modified: November 28, 2014

Refactoring Object instantiation to introduce fake constructors in VisualBasic6

Problem
Bruce Mckinney mentions that one of the biggest failures in VisualBasic (actually now VbClassic) up to version 6 is it's lack of constructors. This causes the problem that once you create a new object in VB, it is in an invalid state until you initialize each field, one at a time, unless you have a convention like, say: "always call the 'Init' method after creating a new object.

However, you have no way to impose the use of such convention and therefore you can't prevent users from using invalid instances of your objects.

Solution
One way I've found I can cope with that is by making all public classes in an ActiveX DLL to be PublicNotCreatable and introducing one single GlobalMultiuse class which I call CCreator, whose only purpose it's to create and initialize the other public classes in the DLL. Notice that this is not a Factory Object pattern, and hence the different name. (It may help to explain the difference for those who are only somewhat familiar with the Factory pattern.)

How to

:

Public Function NewCCustomer(sName as String) As CCustomer
        Set NewCCustomer = New CCustomer
        With NewCCustomer
        .Name = sName

        ' Add your initialization code here

        End With
End Function

method to the class.

Set obj = New CCustomer
obj.Name = sValue

with

Set obj = NewCCustomer(sValue)

Since your CCustomer class is now PublicNotCreatable, the compiler will warn you if you miss any occurrence of new.

-- AlfredoChavez


CategoryVisualBasic


Loading...