If you have an interface class object and you implement several types of the object, what can you do when your object has no handler? That’s where the Null Object pattern comes into play.
Here’s an example of how you could implement the Null Object Design Pattern in VBA to detect whether a file type processor based on a processing interface was found:
Step 1: Define the Processing Interface (Put in a class module called IProcessor)
' IProcessor Interface ' Public Interface IProcessor Sub ProcessFile(ByVal filePath As String) ' End Interface
Step 2: Implement Concrete Processors (Put in two classes, TextFileProcessor and ImageProcessor respectively)
' TextFileProcessor Clas 'Public Class TextFileProcessor Implements IProcessor Public Sub ProcessFile(ByVal filePath As String) Implements IProcessor.ProcessFile ' Implementation for processing text files MsgBox "Processing text file: " & filePath End Sub ' End Class ' ImageFileProcessor Class ' Public Class ImageFileProcessor Implements IProcessor Public Sub ProcessFile(ByVal filePath As String) Implements IProcessor.ProcessFile ' Implementation for processing image files MsgBox "Processing image file: " & filePath End Sub ' End Class
Step 3: Implement the Null Object (Put in a class module called NullProcessor)
' NullProcessor Class 'Public Class NullProcessor Implements IProcessor Public Sub ProcessFile(ByVal filePath As String) Implements IProcessor.ProcessFile ' Do nothing End Sub 'End Class
Step 4: Factory Method to Get the Appropriate Processor (Put in a class module called ProcessorFactory)
' ProcessorFactory Class 'Public Class ProcessorFactory Public Function GetProcessor(ByVal fileType As String) As IProcessor Select Case fileType Case "txt" Set GetProcessor = New TextFileProcessor Case "jpg" Set GetProcessor = New ImageFileProcessor Case Else Set GetProcessor = New NullProcessor End Select End Function 'End Class
Step 5: Usage Example (Put in a normal module)
Sub TestProcessor() Dim factory As ProcessorFactory Set factory = New ProcessorFactory Dim processor As IProcessor Set processor = factory.GetProcessor( "txt") processor.ProcessFile "example.txt" Set processor = factory.GetProcessor( "unknown") processor.ProcessFile "example.unknown" ' Check if processor is NullProcessor If TypeName(processor) = "NullProcessor" Then MsgBox "Processor is NullProcessor" Else MsgBox "Processor is not NullProcessor" End If End Sub
In this example, the ProcessorFactory
class returns the appropriate processor based on the file type. If the file type is not recognized, it returns a NullProcessor
that does nothing. This way, you avoid null checks and simplify the code. Note that you can use TypeName to get the actual type name to check to see if it is the null type if you need to. Also you can use TypeIs NullProcessor as another alternative.