Monday, December 15, 2003

Another Blog to add to your list


I just discovered the blog of my good friend Michael Duff. He has invented a new blogging term "Blirgin". It means someone who has never blogged :)

Check out his blog at Duff Blog

Wednesday, December 10, 2003

Interface and Abstract Class - Part 3


When to use an Interface

The most obvious place you'd need to use an interface rather than an abstract class is when you need to use the functionality defined in the interface across many different classes. For example, one of the techniques in Java for implementing threads is the Runnable interface, which has a single "run()" method. It is a method that will be used by who knows how many different classes so it is best implemented as an interface.

Next would be when you know you are going to have to derive things needed in your classes from several sources. Classes can only inherit from one parent class but can implement multiple interfaces. For example, the SqlCommand class in .NET has to be a child of the Component class but it also needs to implement standard methods for database commands and methods needed so it can be cloned. So it inherits from the Component class and implements the IDbCommand and ICloneable interfaces.

There are situations in some languages where you cannot use inheritance, such as in .NET when you are defining a structure. For example, the Int32 structure in .NET implements three interfaces, IComparable, IFormattable and IConvertible.

The last place you would use an interface is similar to the first rule. You would use an interface where you don't need (or don't want) to inherit from a base class. For example, you want a set of "command" classes to run the piece of functionality you have encapsulated in them, you have one that runs an FTP upload, another runs a database query, another copies some files across the network, etc. They are not similar enough to create a super-class so instead you would use an interface so they provide a standard method for accessing their functionality.

Thursday, December 04, 2003

Interface and Abstract Class - Part 2


What is an Abstract Class?

An abstract class has a couple of features that are similar to an interface: You can't instantiate an abstract class and it can contain method and property signatures. The main difference from an interface is that the abstract class can provide implementation to methods, etc.

An example abstract class could be one used for encrypting files:


Public MustInherit Class AbstractFileEncryptor
 
Public Property Key() As String
'code for the property
End Property
 
Public Property Source() As String
'code for the property
End Property
 
Public Property Target() As String
'code for the property
End Property
 
'An abstract method
Public MustOverride Sub Encrypt()
 
End Class

We give implementation to the Key, Source and Target properties because they will be used in all sub-classes and they will all have the same functionality. However we have no clue how the Encrypt() method will be implemented because the sub-classes will be for different encryption algorithms. For example:


Public Class RSAFileEncryptor : Inherits AbstractFileEncryptor
Public Overrides Sub Encrypt()
'code to implement RSA encryption
End Sub
End Class

Tomorrow: When to use which.

Tuesday, December 02, 2003

Interface and Abstract Class - Part 1


The next pattern (adapter) uses an Interface and I thought I'd have a go at simply describing what an interface is, what an abstract class is and what the difference between them is. My main reason is for the benefit of programmers who are not familiar with object oriented concepts or who had worked with Visual Basic 6, which has some strange ideas of what Interfaces and Abstract Classes are.

When .NET first came out I took a course in it to get up to speed. I had done a good bit of programming in Java so I was familiar with object oriented programming and was happy to see that the ".NET" changes that had been made to Microsoft's languages were basically a copy of Java. Suddenly VB was a real language and no longer a three-legged mongrel with a missing ear. The guy giving the course was a long term VB programmer and unfortunately it was quite plain from early on that he had a poor understanding of object oriented concepts. He told us that there was no real difference between an Interface and an Abstract Class and when I (big mouth that I am) told him they were different he said, "that may be the case in Java but not in .NET." I think his misunderstanding stemmed from the fact that VB6 didn't have class inheritance but sort of "interface inheritance" so he was stuck with the idea that inheritance had to come from something that had no code in it but just signatures.

What is an Interface?

Simply put, an interface is a sort of class with method signatures but no code. It could be described as a class with no implementation. It can contain method, event and property signatures and any class that implements the interface must implement those members. It's as if the Interface is a legal contract that says what the agreement is on how a class implementing the Interface will present itself to the world. For example if the Interface has a method "Execute()" then the implementing class must have a method with the same signature and must add the code to do whatever "Execute()" is supposed to do.

Because the Interface is just a contract you cannot instantiate an object of that type. Let's say we have an interface like this:


Public Interface InterfaceX
Property Command() As String
Sub Execute()
End Interface

You may think you can do this with it:


Dim myVar As New InterfaceX
myVar.Command = "Select * from Whatever"
myVar.Execute()

Unfortunately it won't work because an Interface is just a contract and you can't instantiate it.

So how can we use the Interface? Let's create a class that implements the Interface:


Public Class ClassX : Implements InterfaceX
Public Property Command() As String Implements InterfaceX.Command
'code goes here
End Property
 
Public Sub Execute() Implements InterfaceX.Execute
'code goes here
End Sub
End Class

Now we can do this:


Dim myVar As InterfaceX
myVar = New ClassX
myVar.Command = "Select * from Whatever"
myVar.Execute()

Well great, you say, but why didn't you just do this:


Dim myVar as New ClassX
myVar.Command = "Select * from Whatever"
myVar.Execute()

If you had one class with an Execute() method then there would be no need for an Interface, but what if you have a situation where you are going to have a collection containing many objects of 10 different classes and all will need to be processed? Are you going to write code like this?


Dim myVar1 as Class1
Dim myVar2 as Class2
'etc ...
Dim myVar10 as Class10
For n = 0 to CollectionX.Length - 1
If Typeof CollectionX(n) is Class1 then
myVar1 = CType(CollectionX(n), Class1)
myVar1.Execute()
ElseIf Typeof CollectionX(n) is Class2 then
myVar2 = CType(CollectionX(n), Class2)
myVar2.ExecuteProc()
'etc ...
ElseIf Typeof CollectionX(n) is Class10 then
myVar10 = CType(CollectionX(n), Class10)
myVar10.ExecuteStatement()
End If
Next

Wouldn't you rather do something like this?


Dim myVar as InterfaceX
For Each myVar in CollectionX
myVar.Execute()
Next

That is the beauty of an Interface.

Tomorrow: Abstract Classes

Monday, December 01, 2003

Facade Pattern (Façade Pattern)


Description

This is a very useful pattern. It is used to create a simple interface to a set of classes. Instead of having to deal with all the classes involved you just deal with the Facade class.

Example

Let's say we have a set of classes that allow us to encrypt and decrypt byte streams. What we want to do is encrypt and decrypt files, folders and entire folder trees. Any application we create will have to deal with files, folders, trees and the byte streams, that's about 8 classes right there - encrypt file, decrypt file, encrypt folder, decrypt folder, encrypt tree, decrypt tree, encryption stream and decryption stream. Well maybe if you were only going to do this sort of thing once you could just do it and to hell with the complexity. But what if you were going to have to do it in several programs or even several places within the current program, and worse still, what if you built the whole complex mess and then had to modify it? This is looking ugly. So how can we simplify it?

We create a class that has a simple public interface and we put all the logic for dealing with the other classes into this "Facade". Now any application we create only has to deal with one class with a simple interface. It doesn't have to care about the details of files, streams, etc. Now if we have to make modifications we can change the internals of the many encrytion classes without affecting the client program at all.


Public Class CryptoFacade
 
Public Property Key() As String
 
Public Property Source() As String
 
Public Property Target() As String
 
Public Property Type() As String
 
Public Sub Encrypt()
 
Public Sub Decrypt()
 
End Class

We hide the other classes in the assembly by giving them "Friend" visibilty.


Friend Class EncryptFile
'code to encrypt a file
End Class
 
Friend Class DecryptFile
'code to decrypt a file
End Class

So the Facade class provides a sort of API to the other classes, thus keeping things simple for the client class that wants to use its functionality.

References

Wikipedia - Facade Pattern
Data & Object Factory - Facade Pattern
Bob Tarr University of Maryland - Facade Pattern
Bob Tarr - Design Patterns

Friday, November 21, 2003

Light Relief - Sort Of


As a break from software design patterns here is a site that's funny but has a serious message. I recommend taking up their offer at the end of the video and finding stores that provide meat & poultry from sustainable and organic sources.

The Meatrix

Thursday, November 20, 2003

Singleton Pattern


Description

I once saw this pattern summarized as "There is only one Elvis and there will only ever be one Elvis". The Singleton is a pattern that is used when you want one and only one instance of an object.

The usual reasons for this are: the object encapsulates an important resource that is used in many places (for example if you don't want an application to be able to open up several connections to the database make a singleton out of the database connection), or the resource can only be used by one thread at a time (e.g., a class that plays a song file. You only want one song playing at a time.)

Example

The usual way this is implemented is by
1) declare a private static (shared in VB) variable to reference the single instance,
2) create a static method in the singleton class that returns the single instance
3) make the constructor private so the class can only be instantiated by itself.

Here is an example:


Public Class SingletonMP3Player
'1) the private variable
Private Shared _instance As SingletonMP3Player
 
'2) the static method to return the singleton
Public Shared Function GetInstance() As SingletonMP3Player
'if it has not already been instantiated then create it
If _instance Is Nothing Then
_instance = New SingletonMP3Player
End If
Return _instance
End Function
 
'3) the private constructor
Private Sub New()
'prevents instantiation from outside the class
End Sub
 
'Other methods required to make the class useful
Public Sub Play(filename As String)
'code to play, stopping self if already playing something else
End Sub
 
Public Sub StopPlaying()
'code here
End Sub
 
Public Sub OtherUserfulMethod()
'etc ...
End Sub
End Class


Here is how you could use it:


Public Class Singing
Sub SingTheBlues()
Dim myPlayer As SingletonMP3Player
myPlayer = SingletonMP3Player.GetInstance()
myPlayer.Play("c:\music\blues\Born Under A Bad Sign.mp3")
End Sub
 
Sub GrowlDemonically()
Dim myPlayer As SingletonMP3Player
myPlayer = SingletonMP3Player.GetInstance()
myPlayer.Play("c:\music\deathmetal\Blackwater Park.mp3")
End Sub
 
'or a show off way to do it
Sub JustListen()
SingletonMP3Player.GetInstance().Play("c:\music\prog\3 Min Warning.mp3")
End Sub
End Class

Resources

Wikipedia - Singleton pattern
Data & Object Factory - Singleton
DotNetExtreme - Singleton pattern

Tuesday, November 18, 2003

Prototype Pattern


Description

This is another pattern that builds objects in a way that protects the client from having to know the exact class of the required object. So when would you use it instead of Factory, Abstract Factory or Builder? My answer would be:

  1. When you have objects that take a lot of resources to create (e.g., if you have to read a file or database table to get values) but don't take a lot to clone.
  2. When you have a lot of immutable objects and you don't want to keep creating new instances but instead you want to use a single instance and pass around copies of it. (e.g., fonts - you will use a particular font a lot in a word processor program, but it can be the same instance every time.) This sounds like the "Singleton" pattern, which I'll describe next, but notice that I say "when you have a lot of immutable objects."
  3. When you have a large number of sub-classes and could instead make them into a single class only differing by the values of certain attributes. (e.g., you have several types of customer and you could sub-class them, but it is actually easier to create instances of the one class and give them different values to represent the different types. Create the PremierCustomer prototype once, loading the data that differentiates him from a CreditRiskCustomer, then copy that prototype and change the "Name", "Address", etc. values.)
  4. If there are a large variety of classes to be instantiated and the various instances differ only in certain attributes. (e.g., you have a game program and Monster, Hero, Villain, etc., classes. You can have lots of different monsters and they will differ in the graphic used to display them, their size, viciousness, etc. Rather than create a new Monster object every time simply copy the prototype and change the graphic, etc.)

(Note: Clone has two definitions: a "shallow clone" and a "deep clone". A shallow clone copies value type variables within the original but doesn't make a copy of reference type variables, it just returns the reference. I have also seen shallow clone used to mean that you return a reference to the prototype object - that's not strictly speaking a clone, but it does get used that way by some people. A deep clone copies everything within the prototype so the copy has no connection with the prototype - this usually takes a lot more resources than a shallow clone. Which method you use depends on your particular situation.)

Example

Let's say we have a system that inventories audio visual materials. To create the objects that represent the materials takes a lot of resources but to then customize them to the particular type of material (e.g., 1" tape) is relatively quick.

Lets start with the Material super-class:


Public MustInherit Class Material : Implements ICloneable
 
Public MustOverride Property Description() As String
 
'Returns a shallow clone
Public Function Clone() As Object Implements ICloneable.Clone
Return CType(Me.MemberwiseClone(), Material)
End Function
 
Public MustOverride Sub CommonMethod()
End Class


And here is a sub-class:


Public Class Tape : Inherits Material
'All sorts of complex objects that take a long time to initialize
Private TypeX As ComplexClassOfSomeKind
'etc ...
 
Public Overrides Property Description() As String
'code goes here
End Property
 
Public Overrides Sub CommonMethod()
'code here
End Sub
 
'other methods ...
End Class


Now we have the class that controls the creation of the prototypes and provides the clones:


Public Class MaterialBuilder
Private _prototypes As New Hashtable
 
Public Sub New()
InitializePrototypes()
End Sub
 
Public Sub InitializePrototypes()
'put objects of the different material sub-classes into the hashtable
_prototypes.Add("TAPE", MaterialFactory("TAPE"))
_prototypes.Add("CD", MaterialFactory("CD"))
_prototypes.Add("DVD", MaterialFactory("DVD"))
'etc ...
End Sub
 
Public Function BuildMaterial(aType As String) As Material
Dim builder As Material
builder = _prototypes.Item(aType)
Return builder.Clone()
End Function
 
Private Function MaterialFactory(aType As String) As Material
'factory code goes here
End Function
End Class


The pattern could be used like this:


Class ClientClass
Public Sub DoIt(aType As String, description As String)
Dim builder As New MaterialBuilder
Dim myMaterial As Material = builder.BuildMaterial(aType)
myMaterial.Description = description
myMaterial.CommonMethod()
'etc ...
End Sub
End Class

Resources

Wikipedia - Prototype Pattern
Data & Object Factory - Prototype Pattern
DotNetExtreme - Prototype Pattern

Friday, November 14, 2003

Builder Pattern


Description

This pattern could be described as a way of building complex objects which share common elements.

Example

Let's say we have documents that we want to provide to our clients in whatever format they require. Some clients want Word format, some want PDF, some want HTML and some want XML. We also know that in the future more formats will be required. Our documents can be broken down into elements such as document header, page header, margin width, pre-data descriptive text, data, post-data descriptive text, etc.

The builder pattern is perfect to handle this. First make sure you are familiar with the abstract factory pattern I described yesterday. Builder has many similarities to abstract factory. The main difference being that the "factories" or "toolkits" created by the abstract factory are now called "builders" and instead of providing objects for a particular domain they provide methods to build the various parts of a single complex object.

We start with an AbstractBuilder class which contains a static (shared in VB) factory method to create the builder objects that will build the documents in the various formats. It also contains abstract methods to build the various parts of the formatted document and finally a property for returning the finished document in the required format. The different document classes must use a common interface so the client code can handle them without knowing what class they are, so the property returns a type of that interface.


Public MustInherit Class AbstractDocumentBuilder
Public Shared Function GetBuilder(format As String) _
As AbstractDocumentBuilder
Select Case format.ToUpper()
Case "WORD"
Return New WordBuilder
Case "PDF"
Return New PDFBuilder
Case "XML"
Return New XMLBuilder
Case Else
Return Nothing
End Select
End Function
 
Public MustOverride Sub BuildDocHeader(docHeaderText As String)
Public MustOverride Sub BuildPageHeader(pageHeaderText As String)
Public MustOverride Sub BuildPreDataText(preDataText As String)
'more methods for other parts of the document ...
 
Public MustOverride ReadOnly Property Document() As IDocument
End Class

Note: You could give these part builder methods "do nothing" implementations so there would be no need to implement them for formats that don't have that part.

Next are the concrete builder classes for the formats:


Public Class WordBuilder : Inherits AbstractDocumentBuilder
Private _document As New WordDocument
 
Public Overrides ReadOnly Property Document() As IDocument
Get
Return _document
End Get
End Property
 
Public Overrides Sub BuildDocHeader(docHeaderText As String)
'code here for Word format
End Sub
 
Public Overrides Sub BuildPageHeader(pageHeaderText As String)
'code here for Word format
End Sub
 
Public Overrides Sub BuildPreDataText(preDataText As String)
'code here for Word format
End Sub
End Class


In my example the IDocument interface contains a method to write the document to a file. You could give it whatever methods are appropriate for your implementation. For example you could give it a "Send()" method so it emails itself to the person requesting it.


Public Interface IDocument
Sub Write(fout As FileStream)
End Interface


Next is the class representing the formatted document:


Public Class WordDocument : Implements IDocument
Public Sub Write(ByVal fout As FileStream) Implements IDocument.Write
'code to write the document to the stream
End Sub
 
'other needed methods & properties
End Class


Finally the client would contain code something like this (note: "doc" represents the original unformatted document):


Public Sub WriteDocument(format As String, fout As FileStream)
Dim finalDocument As IDocument
Dim builder As AbstractDocumentBuilder
builder = AbstractDocumentBuilder.GetBuilder(format)
builder.BuildDocHeader(doc.DocumentHeader)
builder.BuildPageHeader(doc.PageHeader)
builder.BuildPreDataText(doc.PreDataText)
'Build other parts of the document ...
 
finalDocument = builder.Document
finalDocument.Write(fout)
End Sub


To add a new format you create the builder class for it and add a 'Case "NEWDOC"' to the Select statement in the abstract builder class.
Resources

Data & Object Factory: Builder Pattern
Wikipedia - Builder Pattern
DotNetExtreme - Builder Pattern

Thursday, November 13, 2003

Abstract Factory Pattern


Description

This could be described roughly as a factory that produces factories. The usual description is a factory that produces toolkits.

Example

So what does that mean? Well, here's an example: we are consulting an entertainment company that produces movies and TV shows. Some of the classes involved would be Customer, Product, Deal, License, Market, SalesPerson. Now products can be licensed in different media such as Pay-Per-View, Premium Cable, Basic Cable, Domestic TV, International TV, etc. and the deals are very different in each media. The classes we described earlier vary across these media. For example, an international TV deal involves different languages (e.g., French, German and Italian) and many markets (e.g., France, Switzerland, Belgium, Germany, Italy), whereas a domestic TV deal involves only one language (e.g., Spanish) and one market (e.g., Los Angeles). Also the way the customers are viewed within the different media is different and the data associated with a customer is different. The sales people are paid differently and different data about them is kept in each media. So we have a set of class heirarchies something like this:


Customer
|
-----------------------------------------------
| | | |
DomesticTVCustomer IntTVCustomer PPVCustomer etc
 
 
Deal
|
--------------------------------------------
| | | |
DomesticTVDeal IntTVDeal PPVDeal etc


The code might look something like this:


Public MustInherit Class Deal
Public MustOverride Sub MakeLotsOfMoney()
'other members of deal
End Class
 
Public Class DomesticTVDeal : Inherits Deal
Public Overrides Sub MakeLotsOfMoney()
'Money making code goes here
End Sub
'etc ...
End Class
 
Public Class PPVDeal : Inherits Deal
Public Overrides Sub MakeLotsOfMoney()
'Money making code goes here
End Sub
'etc ...
End Class

And there are several other similar heirarchies for the other classes.

Now we don't want to have to write different code for every media so how can we get around it? Well, what if we create a factory that creates the objects for the different media?


Public Class MediaFactory
Public Function GetCustomer(media As MediaType) as Customer
Select Case media
Case MediaType.DOMESTIC
return New DomesticTVCustomer
Case MediaType.INTERNATIONAL
return New InternationalCustomer
Case MediaType.PPV
return New PPVCustomer
Case ETC
'etc ...
End Select
End Function
 
Public Functon GetDeal(media As Integer) as Deal
'big select statement
End Function
 
Public Function GetLicense(media As Integer) as License
'big select statement
End Function
 
'etc ...
End Class

Not bad but now we have big select statements in every method and if we add a new media we have to go into every method and add something to the select. Well, what if we make a factory that generates factories, one for each media? The resulting "factory" classes are not really factories so they often get called "toolkits". But remember that for the Factory pattern we have to create a super-class for the toolkits and then a factory class to create the toolkit objects. So let's kill two birds with one stone and put the Factory method into the super-class.

Now we have something like this:


Public MustInherit Class AbstractMediaFactory
 
Public Enum MediaType As Integer
DOMESTIC
INTERNATIONAL
PPV
'etc ...
End Enum
 
Public Shared Function GetFactory(media As MediaType) As AbstractMediaFactory
Select Case media
Case MediaType.DOMESTIC
Return New DomesticTVFactory
 
Case MediaType.INTERNATIONAL
Return New InternationalTVFactory
 
Case MediaType.PPV
Return New PPVFactory
 
Case MediaType.ETC
'etc ...
 
Case Else
Return Nothing
 
End Select
End Function
 
Public MustOverride Function GetDeal() As Deal
Public MustOverride Function GetCustomer() As Customer
Public MustOverride Function GetLicense() As License
'Other GetXXX functions go here
End Class
 
Public Class DomesticTVFactory : Inherits AbstractMediaFactory
Public Overrides Function GetDeal() As Deal
Return New DomesticTVDeal
End Function
 
Public Overrides Function GetCustomer() As Customer
Return New DomesticTVCustomer
End Function
 
Public Overrides Function GetLicense() As License
Return New DomesticTVLicense
End Function
End Class
 
Public Class PPVFactory : Inherits AbstractMediaFactory
Public Overrides Function GetDeal() As Deal
Return New PPVDeal
End Function
 
Public Overrides Function GetCustomer() As Customer
Return New PPVCustomer
End Function
 
Public Overrides Function GetLicense() As License
Return New PPVLicense
End Function
End Class

To use this pattern we first get the factory (or toolkit) we need



Dim myFactory as AbstractMediaFactory
myFactory = AbstractMediaFactory.GetFactory(media)

Then we get the specific object we want to use:


Dim theDeal as Deal
theDeal = myFactory.GetDeal()
theDeal.MakeLotsOfMoney()


Now if we want to add a new media we simply create the classes and toolkit class for the media, then add a "Case MediaType.NEWMEDIA" to the Select statement in the abstract factory class.

Resources

Data & Object Factory - Design Patterns: Abstract Factory
Wikipedia - Abstract factory pattern
DotNetExtreme - Abstract Factory Pattern