6/28/2005 11:10:00 AM|W|P|Jay Flowers|W|P|Well after much looking I have been unable to locate an existing IRC Channel for Object Oriented Programming. In response to this deficiency I have create just such a channel #Object. I hope to see you there.|W|P|111997503729955729|W|P|New OOP IRC Channel|W|P|6/26/2005 09:40:00 AM|W|P|Jay Flowers|W|P|

So I have been posting an awful lot about oop exception handling. The approach that I have been following makes use of external polymorphism. As far as I can tell Chris Cleeland and Douglas C. Schmidt were the first to document its use as a pattern. They implemented with templates in C++. An OOP language with reflective abilities can achieve a similar effect. Before we dive into the implementation lets get some context, get on the same page as to what we are trying to solve.

Allow classes unrelated by inheritance or related by inheritance but without the desired virtual method to be treated polymorphically.

If you read the paper Douglas and Chris wrote my last sentence should sound familiar. Now a little motivation would be nice too.

Say I found that the best solution for my problem was to implement the Visitor pattern but the class that I would need to alter are not in my control. They are classes that have been purchased in a third party library.

I want to focus on explaining the implementation not on justifying the need for this pattern. Justification is worth at least a whole other blog entry. So on to the participants.

For the moment let's go with encapsulating all method implementations in one class. We want to be able to have a method implementation selected because it is associated with a type. In internal polymorphism this association is drawn through the type that implements the method. Here it will be drawn by the type of the parameter in the signature of the method (i.e. internal = type.method(), external = method(type)).

public class ExternalVisitor

{

    public void Accept(Animal animal) {}

    public void Visit(Parrot animal){}

    public void Visit(Alligator animal){}

}

Posted by Hello

I mentioned reflection earlier, that plus the concept of double dispatch can achieve external polymorphism. The Accept method on the class ExternalVisitor will use these concepts to dispatch to the method associated to the type of Animal pass it. It will reflect on the type passed as well as the methods named Visit searching for the method that accepts a parameter of the same or inherited type as passed. So if passed a Parrot the Visit method that accepts a parameter of type Parrot will be selected. The call will then be dispatched to that method (double dispatch). The call was redirected to the appropriate method, or double dispatched. If there is a type Cockatoo that inherits from Parrot it too would be dispatched to the method named Visit accepting a parameter of type Parrot.

I have packaged all the reflection stuff into a class called DoubleDispatchReflector. It is included in the ASOGS projects Patterns namespace. Here is some example usage.

public class ExternalVisitor

{

    public void Accept(Animal animal)

    {

        DoubleDispatchReflector dispatch = new DoubleDispatchReflector(this, "Visit");

        dispatch.Invoke(animal);

    }

    public void Visit(Parrot animal){}

    public void Visit(Alligator animal){}

}

I don’t know about you but I think that provided a lot of bang for your buck. Two lines and we have the guts of external polymorphism working.

The participants explained so far implement all the methods to be dispatched to in one class. Lets change perspective and imagine that we have found someone else's ExternalVisitor and we would like to reuse some of it’s methods and create some of our own. We would like to aggregate some of our own new code and reuse some old code.

Posted by Hello

This scenario has been packaged up into a class named Prizm. It too is included in the ASOGS projects Patterns namespace. And again here is some example usage.

public class AggregateVisitor

{

    public void Accept(Animal animal)

    {

        Prizm aggregate = new Prizm();

        object[] ParameterLists = new object[1];

        ParameterLists[1] = new Type[1] {typeof(Cockatoo)};

        aggregate.AddHandler(new NewExternalVisitor(), "Visit", ParameterLists);

        ParameterLists[1] = new Type[1] {typeof(Parrot)};

        aggregate.AddHandler(new OldExternalVisitor(), "Visit", ParameterLists);

        aggregate.Invoke(animal);

    }

}

Well that seems to be more than enough for this post. Maybe next time I will write about using multiple parameters.

Note:

I have not yet released the aggregation class (Prizm) and there have been modification to the DoubleDispatchReflector since it's last release.

The examples shown here are not for production use. They have been made for easy reading.

|W|P|111980198353853096|W|P|External Polymorpism|W|P|6/20/2005 03:06:00 PM|W|P|Jay Flowers|W|P|

I have not been able to find an appropriate project to push this stuff to so I have created my own, ASOGS. So far I have included these namespaces and classes:

  • ASOGS
    • Collections
      • Map
      • MapBase
    • ExceptionHandling
      • AggregateExceptionHandler
      • ExceptionHandlerBase
    • Reflection
      • AssemblyInformation
      • AssemblyInformationList
      • TypeArrayComparer
      • TypeArrayHashCodeProvider
    • Serialization
      • Cloner
      • Persistor
      • Serializer
    • Patterns
      • DoubleDispatchReflector
      • UniversalFactory

I have yet to move all the reuseable code that I have collected over the last year into the ASOGS project. Somethings that I plan to include are:

  • Exception Serialization Handling
  • Plugin Managment
  • Singleton Manager
  • Resource Pool Manager

I will try to post some details about these class in future blog entries, and get these additions into a ASOGS release soon.|W|P|111929974470701521|W|P|All Sorts of Good Stuff|W|P|6/17/2005 09:52:00 AM|W|P|Jay Flowers|W|P|I gave a presentation on OOP exception handling at Northrop Grumman yesterday. It covers the exception handling techniques that I have recently bogged about. The slides are all up to date, but the comments are a little sparse toward the end. After I digest the feedback from the presentation I will probably update the presentation. Enjoy.|W|P|111902086245439202|W|P|Exception Handling Presentation|W|P|6/07/2005 08:50:00 PM|W|P|Jay Flowers|W|P|Here is a quick example of an ExceptionHandler and how to use it. First the dirived ExceptionHandler:


Class Example

    Public Shared Sub Main()
        Dim handler As New MyExceptionHandler
        Dim MyExample As New Example
        Try
            MyExample.UnsafeAction()
            MyExample.AnotherUnsafeAction()
        Catch ex As Exception
            If Not handler.HandleException(ex) Then
                Throw
            End If
        End Try
    End Sub

    Private Sub UnsafeAction()
        Throw New Exception("This is a test excaption")
    End Sub

    Private Sub AnotherUnsafeAction()
        Throw New IO.IOException("This is a test excaption")
    End Sub

End Class

Now using it:


Public Class MyExceptionHandler
    Inherits ExceptionHandlerBase

    Public Overloads Overrides Sub Handle(ByVal exception As System.Exception)
        Console.WriteLine(String.Format("Handling : {0}", exception))
    End Sub

    Public Overloads Sub Handle(ByVal exception As IO.IOException)
        Console.WriteLine(String.Format("Handling : {0}", exception))
    End Sub

    Protected Overrides ReadOnly Property UseDefaultHandler() As Boolean
        Get
            Return True
        End Get
    End Property

End Class

I you have played with the Exception Handling Application Block it may look similar. I thought that MS had beet me to the punch when I found that particular Application Block the other day. As far as I can tell so far they do not do any thing like the visitor pattern or polymorphism with the excpetion type. they use magic strings to determin which handler to give the exception to. Maybe next post I will does a comparison fo the two approachs. I have consitered contacting the mainters of that Application Block to discuss how the approach I have inovated could be used in the Exception Handling Application Block.|W|P|111819651793133320|W|P|An ExceptionHandler Example|W|P|6/07/2005 07:37:00 PM|W|P|Jay Flowers|W|P|So I had a copy paste bug in my unit test for aggregate excpetion handling. It was using a table of signatures and handlers to determine which handler to dispatch to. The problem was
Hashtable(Signature)
does not do the same job as
Type.GetMethod("MethodName", Signature)
. The solution I found was Reflection.Emit. It was nice to have a real reason to learn some about this technology. I used emit to dynamicaly create a type with methods matchs all the signatures in the table.


Public Sub [AddHandler](ByVal handler As IExceptionHandler, ByVal ParameterLists As Object())
    For Each ParameterList As Type() In ParameterLists
        If Me.HandlerSignatures.Contains(ParameterList) Then
            Throw New ArgumentException("There is a handler that overlaps with the requested addition.")
        End If
    Next
    For Each ParameterList As Type() In ParameterLists
        Me.HandlerSignatures.Add(ParameterList, handler)
    Next
    If Me.IsActive Then
        Me.CreateAggregate()
    End If
End Sub

A client would pass what signatures from the handler should be added to the aggregate. The CreateAggregate method will use emit to create the aggregate. That code is a bit borring, thought what it does is cool. I learned a lot from Kenny Kerr's blog on IL. Just like layout of a UI Control a client can control creation of the aggregate. If many aggregates where being added SuspendAggregation couls be called and when the addtions where complete ResumeAggregation could be called to create the aggregate. When I was writting the HandleException methods of the AggregateExceptionHandler I noticed that the reflective double dispatch code I was writting was almost the same as ExceptionHandlerBase. I moved this code to a new class, DoubleDispatchReflector.


Public Class DoubleDispatchReflector
      ' Methods
      Public Sub New()
      Public Sub New(ByVal subject As Object, ByVal methodName As String)
      Public Function DispatchTo(ByVal args As Object()) As MethodInfo
      Public Function DispatchTo(ByVal arg As Object) As MethodInfo
      Public Function DispatchTo(ByVal subject As Object, ByVal methodName As String, ByVal args As Object()) As MethodInfo
      Public Function DispatchTo(ByVal subject As Object, ByVal methodName As String, ByVal arg As Object) As MethodInfo

      ' Properties
      Public Property MethodName As String
      Public Property Subject As Object

End Class

With that the AggregateExceptionHandler was complete. Now there are two standard ways to obtain reuse of ExceptionHandlers, inheritance and aggregation. Please download a copy and play with it. Let me know what you think.|W|P|111819337446501871|W|P|Aggregate ExceptionHandlers|W|P|6/06/2005 07:02:00 PM|W|P|Jay Flowers|W|P|

I have been having a problem with the use of try catch in .NET. It seems strange
to me that a series of catch statements would be used when all the power of OOP
is sitting there waiting to be used. I read an article about using Reflection in the Visitor Pattern for double dispatch. After reading this article I figured out
how to handle exception in an object oriented manner with in the try catch scheme. It all boils down to the following class:


Public MustInherit Class ExceptionHandlerBase

    Implements IExceptionHandler

    Protected MustOverride ReadOnly Property UseDefaultHandler() As Boolean

    Public Function HandleException(ByVal exception As Exception) As Boolean Implements IExceptionHandler.HandleException

        Dim handled As Boolean = False
        Dim types As Type() = New Type(0) {exception.GetType()}
        Dim MethodInformation As MethodInfo

        If Not exception.GetType Is GetType(Exception) Then
            MethodInformation = Me.GetType().GetMethod("Handle", types)
        End If

        If MethodInformation Is Nothing Then
            If Me.UseDefaultHandler Then
                Me.Handle(exception)
                handled = True
            End If
        Else
            MethodInformation.Invoke(Me, New Object(0) {exception})
            handled = True
        End If 

Return handled End Function Public MustOverride Sub Handle(ByVal exception As Exception) Implements IExceptionHandler.Handle End Class


I have only thought of a few qualities of this approach to exception handling that
make it a viable alternative or even an improvment on a catch blocks. First all
the power of OOP can be allied to architect exception handling. Second what
exceptions are handled is visible from the outside of a class. The following
are examples of an inheritor and a client.


Public Class ExampleExceptionHandler
    Inherits ExceptionHandlerBase

    Public Overloads Overrides Sub Handle(ByVal exception As System.Exception)

    End Sub

    Public Overloads Sub Handle(ByVal exception As IO.FileNotFoundException)
        'handle exception here
    End Sub

    Protected Overrides ReadOnly Property UseDefaultHandler() As Boolean
        Get
            Return False
        End Get
    End Property

End Class

Public Class Main

    Public Shared Sub Main()
        Try
            Throw New IO.FileNotFoundException("This is a test.")
        Catch ex As Exception
            Dim exceptionHandler As New ExampleExceptionHandler
            If Not exceptionHandler.HandleException(ex) Then
                Throw
            End If
        End Try
    End Sub

End Class


Clearly the only exception that Class Main will handle, because it uses
ExampleExceptionHandler, is FileNotFoundException. Normally one would have to
read the code of Class Main know what exceptions are handled. I have finished
an example for exception handling in the template Method Pattern, or Hollywood
Pattern. It basically consists of a mirror hierarchy of ExceptionHandler
classes, and a method factory implemented by the template Method concrete class
to provide the concrete ExceptionHandler. I have also created an
AggregateExceptionHandler which accepts multiple ExceptionHandlers. And I was
thinking of an ExceptionHandler base class that accepts multiple parameters, ie
ByVal exception as Exception, ByVal OtherObject as SomeOtherObject.

I had posted this entry a while ago but there was the possibility that my employer was
going to claim it as it's intellectual property.

There will be some more
posts on this subject shortly as the ideas did not seem patentable.

|W|P|111810337193599446|W|P|True OOP Exception Handling|W|P|