An extensible class factory

Some times you want to make a nice generic class that a user can extend via subclassing.

However, one issue arises with this.

How can a factory method in the super class create instances of the subclasses ? This is especially troublesome if the classes you have are encrypted so you cant change the source or in a plugin.

However, it IS possible to create an “extensible factory method” so the factory can create instances of the subclasses users provide.

Lets look at how you can do this.

Usually a class factory method looks something like

Class MySuperClass
  Private Sub Constructor()
  End Sub

  Shared Function CreateNew()
    return new MySuperClass
  End Function
End Class

The private constructor makes it so no one can create an instance without using the factory.

So how do you make this basic pattern extensible so the factory can create instances of the correct subclasses ?

If you had the source code you could change the factory method to

  Shared Function CreateNew(name as string)
    select case name
    case “MyCustomSubclass”
       return new MyCustomSubclass
    else
      return new MySuperClass
    end select
  End Function

But there are some real problems with this

the superclass has to be alterable – if you dont have source code you cant do this. So distributing code to other people to uses becomes a real problem

every time you add a subclass you have to remember to alter the superclass

What do you do if this is a plugin written in C++ ?

As the author of a class thinking about how to solve these issues is really important. And this one is solvable. For pure Xojo code and for plugin authors.

Recall that Introspection allows you to look at a class, and its constructors. As well you can invoke one and get back a new instance.

So lets create a mechanism to let the superclass know about subclasses, and then use that knowledge to create the right instances when we need them.

First lets add the “way to know about subclasses”

At runtime the way to “know” about other classes is .. introspection !

And that knowledge is a typeinfo object.

So our superclass needs a way to get the typeinfo’s of subclasses and hang on to it for later use.

Holding on to it for later is easy – an array of Introspection.TypeInfo objects will suffice.

  Dim mSubTypes() as Introspection.TypeInfo

Now how do we get all the info about subtypes ? 

We cant just go through all the objects that exist at runtime because if there are no instances of subtypes yet then we would not find any. So we need some way to “register” the subtypes with the superclass so it can use this information later.

So a method like

  Shared Sub RegisterSubType( subType() as Introspection.TypeInfo)

that adds to the array we defined earlier should suffice

Our class now looks like

Class MySuperClass
  Private Sub Constructor()
  End Sub

 Shared Function CreateNew(name as string)
    select case name
    case “MyCustomSubclass”
       return new MyCustomSubclass
    else
      return new MySuperClass
    end select
  End Function

  Shared Sub RegisterSubType(
         subType as Introspection.TypeInfo)
    mSubtypes.Append subType
  End Sub

  Private Dim mSubTypes() as Introspection.TypeInfo

End Class

And now all we really need to fix is the CreateNew method so it can return a subtype properly

We’ll leave the parameters as is for now – so we create “by name”

This has some implications, like if you make a typo you wont get back the instance you asked for, but we can fix that later.

The first thing I’ll do is slightly alter the method signature so it has a default parameter.

 Shared Function CreateNew(name as string = “”)

And that’s if for changing the method signature

This allows us to do a tiny bit of optimization AND makes writing code a tiny bit easier

So first things first – if NO name is supplied we just return a new instance of the superclass.

  if name = “” then
    return new MySuperClass
  end if

And after this we have to find the right “TypeInfo” and create an instance from that. And should we find no match we should return nil – which can be used as an error check to find any issues.

Each TypeInfo object has a NAME property.

So we an iterate through our list of registered TypeInfo objects, find the one with the right name, and invoke its Constructor.

  For i As Integer = 0 To mSubTypes.Ubound
    
    // find the type info with the right name
    If mSubTypes(i).Name = subtype then
    
    // found it so get a list of its constructors
    Dim cInfo() As Introspection.ConstructorInfo =
                               mSubTypes(i).GetConstructors
    
    // and find the 0 param constructor
    // since out factory does not pass along any params
    For j As Integer = 0 To cInfo.Ubound
      Dim pInfo() As Introspection.ParameterInfo = 
                                 cInfo(j).GetParameters
      
      // has no params ?
      If pInfo.ubound < 0 Then
        // yes - invoke this one & return the result
        // which will be an instance of the right type
        Return cInfo(j).Invoke
      End If
      
    Next
    
  End If
  
  Next

  // if we reach here we will be default return a nil 
  // or we could explicitly return nil

And there we go – a superclass with a factory method that can be extended by anyone – with or without source code !

The end result is a class as follows

Class MySuperClass
  Private Sub Constructor()
  End Sub

  Shared Function CreateNew(name as string = “”)
    if name = “” then
      return new MySuperClass
    end if

   For i As Integer = 0 To mSubTypes.Ubound
    
      // find the type info with the right name
      If mSubTypes(i).Name = subtype then
    
      // found it so get a list of its constructors
      Dim cInfo() As Introspection.ConstructorInfo =
                               mSubTypes(i).GetConstructors
    
      // and find the 0 param constructor
      // since out factory does not pass along any params
      For j As Integer = 0 To cInfo.Ubound
        Dim pInfo() As Introspection.ParameterInfo = 
                                 cInfo(j).GetParameters
      
        // has no params ?
        If pInfo.ubound < 0 Then
          // yes - invoke this one & return the result
          // which will be an instance of the right type
          Return cInfo(j).Invoke
        End If
      
      Next
    
    End If
  
    Next

    // if we reach here we will be default return a nil 
    // or we could explicitly return nil
  End Function

  Shared Sub RegisterSubType(
         subType as Introspection.TypeInfo)
    mSubtypes.Append subType
  End Sub

  Private Dim mSubTypes() as Introspection.TypeInfo

End Class

Something you might do is to make the factory NOT take a string but a typeinfo so that there’s no “typo’s” to debug at runtime. Using a typeinfo would mean most typo issues would be caught at compile time.

That’s left as an exercise for the reader.

Code for safety

Lots of time you see code like

static flag as boolean 
if flag then return

flag = true

// rest of method

flag = false

In a simple method/event with only a handful of lines there’s probably nothing wrong with this

But what do you do when the method spans into hundreds or thousands of lines ?

And if you use the philosophy of “bail early” ?

Then your methods/events start to look like

static flag as boolean 
if flag then return
flag = true

if condition then
  flag = false
  return
end if

if condition2 then
  if condition3 then
    flag = false
    return
  end if
else
    flag = false
    return
end if

flag = false

And following all those returns & making sure you reset the flag correctly in every one is tedious.

So what if you could make it so you NEVER had to worry about the flag remaining set when you returned ?

Remember that objects get destroyed when the last reference to them is removed – they automatically get cleaned up.

At first glance it seems that you should be able to do

static flag as date
if flag <> nil then return
flag = new Date()

// rest of method
return

and then when the method ends the date object would go out of scope, get destroyed and the world would be happy & safe for not forgetting to flip that flag.

Sadly because the variable is a static this wont happen – the static persists across calls and so it wont get destroyed.

So the trick is how to make the variable persist across method calls AND also get destroyed when things go out of scope.

But that doesn’t mean we’re stuck.

One issue we do have is that in the way we’ve set up our flag property its a value type which means other code can’t hold on to a reference to it to do anything later.

And because its a static declared in a method other code outside this method cannot touch it to flip its value.

So we need to deal with both these issues.

The second one is easiest to deal with – we can simply move the static from being declared in the method to a property on the class that is only used by this method (although its much more usual to see such a blocking action like this happen in several methods or events rather than just a single one)

So we’ll change

static flag as date

to a similarly named property on this class / window 

By simply doing this we make it possible to use an object that, when created and then goes out of scope makes it so we can use the constructor & destructor to change out flag so things get blocked & allowed as needed.


So how do we have something flip the flag when we need ?

In theory we want our code to look like

if flag then return // remember flag is a private 
                    // or protected property on the class

dim flipper as new FlagFlipper( ???????? )

// rest of method

So what does this “Flipper” thing looks like & how does it work ?

We’ll create a class – FlagFlipper. 

And this class needs to then be able to know how to set and clear the flag we set up. But we really don’t want this new class to have to reach inside other classes to do this.

And this is where delegates come into play.

A delegate is a “type safe function pointer” which means that

it’s a function you can pass around like any other parameter

 it’s type safe – you can’t just pass any old function 

So our new class is going to look something like

Class FlagFlipper
  Constructor( ?????????? )
    // flip the flag in the target class somehow

  End Constructor

  Destructor()
    // flip the flag in the target class somehow
  End Destructor
End Class

To this we’ll add 2 delegates

Delegate SetFlag()
Delegate ClearFlag()

Note that we do not put code in these.

Recall we do not want the flag flipper to know the innards of a class to know how to do its work.

So we need to “pass” the right “function” to the flipper so it can call them without having to know anything more than the two delegates.

So how do we do that ?

Well … addressof CREATES an instance of a delegate

So that seems like we need to use that somehow

We want the actual management of the flag to be in our original class.

So the methods to set and clear the flag should be part of that class (and it really doesn’t matter if this is a class/layout/ etc) Lets suppose we were originally using a Window – so we’ll add code to the Window

In my example so far things look like

Window Window1

  Event Open
    foo
  End Event

  Method foo
    if flag then return

    dim flipper as new FlagFlipper( ??????????? )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Method

  Private Property flag as boolan

End Window

And as stated we’re going to add two methods – setflag and clear flag

Now things look like

Window Window1

  Event Open
    foo
  End Event

  Sub foo
    if flag then return

    dim flipper as new FlagFlipper( ??????????? )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Sub
  
  Private Sub SetFlag()
    flag = true
  End Sub
  Private Sub ClearFlag()
    flag = false
  End Sub

  Private Property flag as boolan

End Window

Now how do we have to make the Constructor & set up of the instance look so the right setflag / clearflag methods are called ?

Well … delegates & address of !

If we make the constructor look like the following 

Class FlagFlipper
  Constructor( setFlagMethod as SetFlag, 
                 clearFlagMethod as ClearFlag )
    // flip the flag in the target class somehow
    setFlagMethod.Invoke
    mSetFlag = setFlagMethod
    mClearFlag = clearFlagMethod 

  End Constructor

  Destructor()
    // flip the flag in the target class somehow

  End Destructor

  Delegate SetFlag()
  Delegate ClearFlag()

  Private mSetFlag as SetFlag
  Private mClearFlag as ClearFlag 

End Class

Note that it holds on to a reference to the method to call to set or clear the flag

And the set up in the method that originally needed the flag looks like

Window Window1

  Event Open
    foo
  End Event

  Sub foo
    if flag then return

    dim flipper as new FlagFlipper( AddressOf SetFlag,
                      AddressOf ClearFlag )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Sub
  
  Private Sub SetFlag()
    flag = true
  End Sub

  Private Sub ClearFlag()
    flag = false
  End Sub

  Private Property flag as boolan

End Window

And now, by using an object that when it goes out of scope automatically cleans up after itself we’ll no longer have to worry about “did I clear that flag ?”

Here’s the completed project