Wednesday, December 31, 2003

Top New Year Resolutions


I just heard on a radio show that the top two resolutions are 1) lose weight and 2) get out of debt.

Here are my answers to these:

1) Lose Weight
First of all you need a target weight. Use the calculator I gave a link to yesterday to determine your ideal weight. Next you have to face the facts that if you are overweight it is probably because you eat the wrong foods, you eat too much food and/or you don't exercise enough. From my own experience the main problems are eating the wrong foods and insufficient exercise. From what I've seen the usual reason people eat too much is because they don't get the nutrients they need from what they are eating, so eating too much is usually a result of eating the wrong foods. So what are the right foods? Well, that's a tough one. For myself I've figured it out over a period of years. I read the following books:

In Fitness and In Health by Dr. Philip Maffetone (There is also another version available on Amazon: The Maffetone Method. Dr. Maffetone educates you on how to figure out what your body needs and how to exercise and burn fat in a low stress manner. Great book. For a taste of what is in the book here is the Two Week Test.

Eat Right for Your Type by Peter J. D'Adamo. This book helped me to figure out what to eat and what to avoid. You should also get the updated list of foods in the Food, Beverage and Supplement Lists from Eat Right for Your Type and you can check the Eat Right 4 Your Type Web site.

Next is the good old Atkins Diet.

Finally there is the possibility that the problem is not physical. If that is the case then the answer is Dianetics. Get the book Dianetics: The Modern Science of Mental Health and check out the Dianetics Web site.

Next: Get out of Debt

Tuesday, December 30, 2003

Useful calculator


I just found a calculator that takes your height and weight and calculates what your "lean" and "ideal" weights should be and what your current state is (e.g., overweight, normal, etc.).

Body Surface Area, Body Mass Index

This should help give you a target for your "lose weight" New Year Resolution.

Monday, December 29, 2003

This is hilarious


Jim Meskimen is one of the most talented people I've ever met. As an improv actor and impressionist he is second to none. If you don't know of Jim or doubt my impeccable taste then just check out his latest: go to Applied Silliness then click on the picture of Saddam.

Warning: if you have a heart condition or are allergic to falling off your chair laughing then get medical advice before following the above link.

Tuesday, December 23, 2003

No one can claim that Saddam is being maltreated


When the US captures someone we treat 'em right, no matter what kind of evil dictator they may be: Saddam's Makeover

Sweetie, that beard has just got to go!

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

Wednesday, November 12, 2003

Software Design Patterns


Partly for my own education and partly to interest anyone who may be reading this blog, I'm going to do a series of posts on software design patterns. I find that describing something so another can understand it improves my own understanding, so I'll begin with the "Gang of Four" Factory Pattern.

Factory Pattern


Basic Description

A Factory is a class (or it can be just a method) that creates objects derived from a common super-class or interface. It is usually used in a situation where you don't want your client class to have to figure out what the specific class of an object is, because it could be of several different types. You create a super-class or interface and code the client to call methods of that super-class or interface. Now you have the problem of how to provide the different objects to the client without the client having to know which class is being created. The answer is to create a factory class that has a method that takes a parameter which it uses to figure out which type of object to return.

Example Code

Here is an example in VB.NET of a factory pattern:
(Note: If large spaces appear between lines of code then widen your browser)

First the factory class. (Note: this could be implemented as a method in the client class rather than as a class.)

Public Class ProcessControllerFactory

Public Shared Function GetController( process As String) As ProcessController
Dim result As ProcessController

Select Case process.ToUpper()
Case "EXTRACT"
result = New ExtractController()
Case "IMPORT"
result = New ImportController()
Case "MATCHING"
result = New MatchingController()
Case "CONFIRMATION"
result = New ConfirmationController()
Case "DISTRIBUTION"
result = New DistributionController()
Case Else
result = Nothing
End Select

Return result
End Function

End Class



The client class gets the process controller it wants like this:

Public Sub Execute( action as String)
'declare the variable using the superclass as the type
Dim processCtrl As ProcessController
'now get the controller
processCtrl = ProcessControllerFactory.GetController(action)
'now call the method common to all classes derived from the superclass
processCtrl.runProcesses()
'other code here
End Sub


If the factory were implemented as a method then "Execute" would look like this:

Public Sub Execute( action as String)
Dim processCtrl As ProcessController
'calls its own method
processCtrl = GetController(action)
processCtrl.runProcesses()
'other code here
End Sub


The classes of the objects produced by the factory look like this:

Public Class ImportController
Inherits ProcessController

Public Overrides Sub runProcesses()
'code goes here
End Sub

End Class


And the super-class of all process controller classes looks like this:

Public MustInherit Class ProcessController

Public Overridable Sub runProcesses()
'default handling code goes here or it could be an abstract method
End Sub

End Class

Resources

Factory pattern example
The Factory Method Design Pattern by Gopalan Suresh Raj
Solve application issues with the factory pattern
Implementing the factory pattern using attributes and activation - C# Programming
The Simple Factory Pattern in C#

Friday, November 07, 2003

Psychiatry USA


I just came across a site that gives the entire strategy used by psychiatry.

It also points out that no physical tests exist to show that any "mental disease" exists. One quote is from the mighty National Institute of Mental Health: "...there is no independent test for ADHD. This is not unique to ADHD, but applies as well to most psychiatric disorders, including other disabling disorders such as schizophrenia..." Click on this link for more quotes on the fact of no tests for mental disorders.

Tuesday, November 04, 2003

Cancellation of the Reagan mini-series


I'm not particularly political, it's not a sport I'm very interested in, I prefer sports like basketball or soccer. I am also not a fan nor a detractor of Ronald Reagan; I took even less interest in politics in the 80's than I do now. But when I heard some of the quotes from the script of "The Reagans" I was angered by this new method of character assassination and abuse of the freedom of speech.

I think the founding fathers must be spinning in their graves at the kind of abuse that passes for freedom of speech these days. Back when the US was founded they knew what freedom of speech meant because for years it had been denied them by a repressive imperial government. If you spoke out of line you ended up in jail or worse. Now we see things like pornography, pirating of copyrights and outright lies defended as "freedom of speech".

Want to know what freedom of speech really is? Then go to North Korea, Iran or China and start speaking out against those repressive regimes. You'll soon get the idea.

But perhaps there is hope for true freedom of speech. The public outcry against the Reagan mini-series was fueled in large part by such non-mainstream media outlets as the Drudge Report and talk radio. Thanks to the Internet, people were able to deluge CBS with complaints to the point where it became clear to the powers-that-be at CBS that this show was going to be a major embarrassment to them, so they pulled the plug.

Another good sign was something I heard on the radio this morning. It was on KNX 1070 in LA, which is a CBS radio station. A reporter was interviewing the TV critic of the LA Times. I thought, "here we go", CBS interviewing a guy from a very left-leaning paper. The outcome seemed obvious. But I was wrong. The interviewer was trying to characterize the pressure on CBS as coming from the famous "great right-wing conspiracy" that was dreamed up during the Clinton era, but the TV critic was having none of it and simply pointed out that a "docu-drama" that was full of lies shouldn't be aired in the first place and that the producers should have made sure it was truthful then no one could have complained about it.

And I think that is the essence of what freedom of speech is all about: TRUTH.

Monday, November 03, 2003

Another Good Blog


My friend Zack, who is studying at Berkley University, has a very interesting blog. He talks about history, science and philosophy in a very enlightening way. I've added a link to his site in my links - click on The Lab.

Friday, October 31, 2003

Excellent Blog


I just discovered that my friend Stan has a blog. It's themed on movie reviews and comments on that world. Very well written and interesting: He calls his blog EQUIVOQUE: noun, an amusing use of an ambiguous word. Check it out and enjoy.

Thursday, October 30, 2003

Great Website


A friend just sent me a link to a great site. It's called DoctorYourself.com. It's a site about natural health and natural remedies.

Since the medical profession not only failed to help my daughter as a baby, but actually made her worse, I've not been to a medical doctor. She had a very severe internal yeast infection - it was so bad you could see the stuff growing in her mouth. The doctor gave her an anti-biotic which was (I later found out) in a solution of sugar. Now, even I knew that yeast loves sugar, but evidently the highly trained and qualified medical doctor didn't. Consequently my daughter got worse.

Luckily a friend referred me to a chiropractor who was also a nutritionist. My daughter's condition was handled by what is called "Alternative Medicine" and it was handled quickly and very successfully.

My viewpoint on "conventional medicine" is that if you are dying from some horrendous accident and sowing up a pumping artery or fixing a broken bone is needed then it can be helpful. But under any other conditions it is more harmful than helpful.

A body runs on food, which contains vitamins, minerals and other substances that it uses to build and repair itself. Seems to me kinda obvious that these should be given a great deal of attention by anyone calling themselves any kind of healer. Well, medical doctors know squat about nutrition which explains why so many Americans have diabetes, heart disease, cancer, etc., etc.

The trouble with vitamins and minerals is that the pharmaceutical companies can't make a fortune out of them so they prevent their use by any means at their disposal.

Anyway, enough venting. Just check out DoctorYourself.com.

Thursday, October 16, 2003

Bend It Like Beckham


My friend Stan sends out emails to a few friends giving them his opinions on movies. I especially liked this one so I thought I'd post it for the world to see.

***

Star Wars proved you could spend a lot of money on a movie and get it back. It ended a drought about 20 years long in which the movie industry was afraid to do that. The result was a rebirth for film.

From the beginning of the movie industry, producers have also known that star power was capable of selling movies. But Lucas put out Star Wars without any really big stars, and took the brass ring. (No, Harrison Ford doesn’t count. He wasn’t a star yet.)

But today, studios and producers fall all over themselves creating SFX (special effects) CGI (Computer Generated Imagery) and even fully animated features that aren’t about a duck and a rabbit ... They also still use the power of big stars to suck in the fans. By the time you have big stars walking on Mars being chased by aliens while dodging ray guns, you are supposed to have a bulletproof concoction that will rake in the dough so fast it’s in the black before it goes to video.

But it doesn’t always work.

So how do you explain movies like My Big Fat Greek Wedding or Bend It Like Beckham? No big stars, no special effects, just competent basic cinematography and relatively unknown competent actors and a wonderful story that makes you realize how great life is and how much you love people...

One thing is still basic: The story has to be good. A good story will sell a film that has neither the biggest effects nor the biggest stars, and a super-production with a bad story can die a sorry death.

Bend It Like Beckham is one of those heart-warming films that has so much of what a good story is all about, nothing else matters. You can’t help getting caught up in this great little tale about a talented young Indian woman in Britain who wants to become a soccer star (that’s "football" to you non-Americans) and endeavors to make it go right in spite of her very traditional Sikh parents who have a much more hide-bound notion of how her life should be and a wicked reaction to the idea of her running around on a field kicking a ball "with her legs showing".

Her partner in crime is actually a pretty big star! But she wasn’t when this movie was made. Keira Knightley was the damsel in distress in the blockbuster Pirates Of The Caribbean. But Beckham came out before Pirates. So it’s like seeing unknown Harrison Ford in Star Wars or unknown Julia Roberts in Mystic Pizza. The entire film was made for 3.5 million dollars - chicken feed by today’s standards, when 75 million is common and 200 million is not unheard of. Big stars bloat the budget by 5-20 million each before you even stop by Kodak to pick up the film. But Beckham has made more than 10 times it’s original investment. After a meek opening weekend of only about $190,000.00, it began to grow by word of mouth, mostly. You can count on the fact there wasn’t a lot of publicity in a 3.5 million-dollar budget.

Like it’s beautiful little star Parminder Nagra, who played the Indian soccer phenom, the film finally "showed its legs" and walked through months of hanging around in the top 20 box office successes while jillion-dollar blockbusters came and went in a few weekends. Now it’s finally gone to video.

If that doesn’t make you want to see the video yourself, then let me add one detail. This is a true "feel good" movie! In my lexicon, that’s a good thing, not a bad one.

Just to clear up your next question, "Beckham" is the name of a current British soccer super-star that is worshipped by the girls, and "Bend It" is a soccer phrase, at least in Britain, that has to do with putting some kind of spin on the ball, as nearly as I can tell. So the phrase "Bend It Like Beckham" is something like a baseball fan saying, "Slam it like Sammy Sosa" or a basketball fan saying, "Dunk It Like Shaq".

Wednesday, October 08, 2003

California Wins


The worst Governor in California history bit the dust yesterday. He wasn't terminated by the new Governator, no he was terminated by the people of the State who are sick to death of him and of the legislature.

A commentator yesterday said that if the recall had also included the legislature then they all would have been kicked out too (Democrats and Republicans), and I think he was right.

I hope the legislature gets the message that the people of California want an end to their anti-business attitude, their irresponsible "it's the economy to blame" excuses, their bungling and their gridlock.

Music Review - Oceanborn by Nightwish


I heard a track from this CD some time ago on an Internet radio station, I think it was ProgRock.com or it could have been ProgRadio.com. Anyway, I liked the track but I didn't pursue it further until a couple of weeks ago I was chatting to a girl I met who is from Hungary. We got onto the subject of music and I told her I liked metal and progressive metal. I was surprised when she said metal was her favorite too because she is in her late teens and (at least in the US) most girls of her age are into the usual hit-radio dross. She mentioned that one band she liked in particular was Nightwish and that the lead singer is a woman who was trained as an opera singer. I recalled the track I'd heard and decided to check out the album.

Well, I'm glad I did. This is an excellent album which I'd describe as melodic metal; very tuneful and lively. The vocals of Tarja certainly demonstrate her classical training and the keyboards of Tuomas give a nice classical vibe.

The band hails from Finland and I read on their website (Nightwish) that Oceanborn was their first album. If this is their first album then I'm going out to get more because they rock.

NightWish: Oceanborn

Tuesday, October 07, 2003

California Election


Well, it ain't over 'til the fat lady sings, but if the people I know are representative of the feeling in California today then I think Davis is out and Arnold the Governator is in.

There are a lot of pissed-off people here right now. They are sick to death of the kind of smear politics being practiced by the re-elect Davis newsletter, sometimes known as the LA Times.

The Gloria Alred 11th hour fiasco was just another demonstration of how extreme such people will go to retain power and to slime their biggest rival. Trotting out a woman with a 30 page long criminal record of prostitution and drugs, so she could accuse Schwarzenegger was pretty blatant. I guess Gloria and the accuser were rather surprised when within a couple of hours two people who were actually there come out and told the truth - Schwarzenegger wasn't even there.

Possibly the cancelled subscriptions to the LA Slimes will have an effect, but probably not. The kind of people who would run this kind of campaign care only for power and they "know" that they are "right."

Tuesday, September 30, 2003

Book Review - The Da Vinci Code by Dan Brown


I really enjoyed this book. It's a mystery/suspense/action novel which includes hidden messages in Leonardo Da Vinci's art, an actual 1000 year old secret society, an actual (and rather bazaar) Catholic Order and the Holy Grail. There are some more even stranger elements, but they are important surprise story elements so I won't say any more.

Anyway, it really grabbed me from the start and I couldn't put it down. I highly recommend it: The Da Vinci Code

Thursday, September 18, 2003

Avast! It's Talk Like A Pirate Day!


There be not much fur me t' say, mateys. This 'ere web site speaks fur itself: Talk Like A Pirate Day - September 19

Friday, September 12, 2003

College: The place to learn how to be unethical


Two news stories today demonstrate how bad it's getting in US universities. The first is a survey of college student's attitudes about downloading music. The majority don't have a problem with it because they don't think they'll get caught. When asked about stealing outside of cyberspace they said they didn't do that because they think they'll get caught. Free Downloading Not Freeloading, College Students Say. So what we have here is the attitude that if you can get away with it then it's okay and if you're likely to get caught then don't do it. This is just another example of the erosion of the concepts of right and wrong, a goal announced in the late 1940's by the president of the World Federation of Mental Health. The field of education was one of the main areas targeted by the WFMH psychiatrists and as can be seen from this survey they've succeeded.

The other story is about "binge drinking" which is practiced by about 40% of college students: Study Links College Binge-Drinking to Marketing.

College is supposed to be where you go to learn the skills you need for your future career. It is supposed to be where our future leaders are educated. But it turns out that college is the place you go to learn how to get drunk and steal music off the Internet. Where you learn that "right" is what you can get away with and that "wrong" is getting caught.

Perhaps we should change the much used "God Bless America" to "God Help America."

Wednesday, September 10, 2003

File Swapping - The new revolution


The irresponsible attitude of file swappers is bad enough, "I didn't know it was illegal," "CDs are too expensive," "I didn't know my kids were doing this," etc., etc. (You have to wonder at the parents who "didn't know." What else are their kids doing on the Internet that they "don't know" about? Viewing porn? Being stalked by pedophiles?). But what really gets me is a quote I saw in the LA Times from a file swapping proponent who uttered this inanity: "The record companies are in their death throws. The new revolution is here." What revolution? Destroying musicians by stealing their livelihood is the new revolution?

What do these idiots think is going to happen if they continue to promote and facilitate the theft of music? Do they think musicians are going to continue to create music so a bunch of criminals can then steal it and pay the musician nothing for all that work? The end product of "the new revolution" is no new music. If it isn't stopped, file swapping will destroy not the music industry but music itself.

Tuesday, September 09, 2003

Book Review: Harry Potter and the Order of the Phoenix by J.K. Rowling


Well, In a word: Disappointing, whiny, tedious and much too long.

I was really looking forward to the new book. I loved the first four books; they kept me enthralled. Number 5 is the first one I've been able to put down.. In the middle I got so fed up with Harry's whining, yelling at people and outbursts of pointless and illogical anger that I put it down and read a couple of other books. Eventually I got back to it but then, near the end I got fed up with the pointless diversions off the main line of the story and started reading another book. I actually haven't finished Order of the Phoenix yet but I will eventually, just to see if it improves.

I hate to sound so negative, but after the first four books I was expecting another great book so the disappointment is all the greater.

Things I liked in the book:

While Harry seems to be "immaturing" most of the other characters are maturing. Ron and Neville especially.

Things I didn't like:

1. Harry's constant whining and angry outbursts and the same whiny antagonistic attitude of some other characters (such as Sirius). For example, at one point Harry and the Weasly twins attack Malfoy because he said something nasty about their mothers. This angry outburst was so inappropriate (how many times has Malfoy said the same thing in the past? Aren't they used to him by now? Plus the twins never reacted like that before - they normally just bad-mouth back) that it was obviously a ploy to get Harry and the twins banned from playing Quidditch.

2. People doing totally stupid things for no apparent reason or behaving inconsistently. Most of these were poorly disguised ways to create certain situations and plot elements.

3. Putting things in the story that were pointless or obviously put there just so they could be used later as part of another situation. An example of pointless additions was a scene where Harry and co. have to get into a particular part of a building. They have to find the right door out of hundreds. Harry knows that the light on the other side of the door he wants is bluish and flickering. He opens a door, the light is bright and not flickering. He's in a big hurry because he's trying to save someone, so what does he do? He steps in and takes a look around and we get a couple of pages about this room. Then he steps out and opens another door and it also has the wrong type of light so what does he do? He steps in and looks around. It makes no sense at all and actually gets annoying.

4. Finally the book is much too long. If all the unnecessary detail and pointless elements were removed it would be about a third of the size and a much better read.

J.K. needs to read some Louis L'Amour and take a few tips from him. His books are never boring, the behavior of his characters is consistent and he gives you what is needed to move the story along while still providing interesting surrounding color.

Anyway, if you still want to read it after my lousy review here's a link: Harry Potter and the Order of the Phoenix

Friday, September 05, 2003

Music Review - Space Metal by Star One


Star One is another brilliant creation of Arjen Anthony Lucassen, the genius behind Ayreon.

If you like Ayreon you'll love Star One. The Space Metal album is composed of songs by Arjen based on his favorite Science Fiction movies and TV shows. The cast of vocalists in itself is impressive (Russel Allen from Symphony X to name one) and the album has the same kind of character based vocals as the Ayreon album "Into the Electric Castle" but with the more metal oriented musical style of "Flight of the Migrator".

If you are not familiar with Ayreon then Star One is melodic progressive metal with several singers. Each song is the story from a Sci-Fi movie and the four vocalists each take the part of a character from the movie. The vocals are great and the music is never less than gripping.

One thing I really like about Space Metal (and every album I've ever heard by Arjen Lucassen) is that you can understand the vocals, they are not drowned by the music and the vocalists are of such quality that every word comes across clearly. The other thing I like is that even with the metal guitar driving the beat, the melody is not lost and the keyboards (which play a major part in the music) are not relegated to a secondary position.

If you like good music then you'll love Space Metal by Star One.

Wednesday, August 27, 2003

Music Review - Beethoven's Last Night by Trans-Siberian Orchestra

I was listening to ProgRock.com and on came an awesome piece of music.  I love mixtures of different genres and this was classical plus rock, definitely a favorite of mine.  I checked out the artist and saw it was the Trans-Siberian Orchestra.  I requested a couple more songs from the album and that was enough - I had to have it. 

The album was Beethoven's Last Night and it totally blew me away.  This is the best blend of classical and rock I've ever heard.  Rock bands have played with orchestras before but the difference here is that the band and the orchestra are one.  They didn't get together just to make this album or play a couple of concerts, they are one and you can hear it.

The album is a concept album telling the story of Beethoven's last night on earth and the attempts of Mephistopheles to remove his music from the ken of man.  The music and vocals are very emotional and the album is very well produced.  I can't wait to hear more from them.

Sunday, August 24, 2003

Music Review - Feel Euphoria by Spock's Beard


Spock's Beard was delivered a crushing blow when lead vocalist, keyboardist and main writer Neal Morse left. Their new album shows the band has not only recovered, but evolved into a new lean mean music machine!

Does this sound familiar? A progressive rock band brings out a double-album, a concept album about the adventures of guy in New York. Shortly after the lead singer leaves and the drummer takes over the vocal duties. Are you thinking: Genesis - 1974? Well you'd be right, but the story also applies to Spock's Beard - 2003. In an uncanny repeat of history Neal Morse (lead vocals) left the band after the double-CD concept album "Snow" and Nick D'Virgilio (drummer) took over.

For Genesis, the difference after Peter Gabriel left was noticeable but not too much for fans to bear. Gabriel was a writer and the front-man, but Phil Collins sounded very like him and most of the instrumental writing was done by the other band members even when Gabriel was around. The difference for the Beard is that Neal Morse was the band leader and the main writer. His style was stamped on everything the band did.

So you have to hand it to the remaining band members, not only did they have to replace a great vocalist who also played major keyboards and some guitar but they had to replace the main writer of the band too.

So how did they do? Incredibly well. First off there is new life and vigor in the music that I didn't know had been missing until I heard it on the new album. It starts off in high-gear on the first track and just goes on from there. Every song on the album is great.

Nick D'Virgilio is a great vocalist and very successfully replaces Neal. Ryo Okumoto steps forward to not only play his own Hammond and Mellotron parts, but to more than replace Neal's other keyboards. And the writing is fresh and lively while still retaining a distinctive Spock's Beard vibe. About the only thing missing is the classical feel that Neal brought to the band. The new style is definitely more rock oriented.

So as a fan of the band I am very pleased with the new album. Plus I have the solo career of Neal Morse to look forward to.

Feel Euphoria by Spock's Beard

Thursday, August 21, 2003

Music File Swapping


I just read an article on NewsFactor about the RIAAs efforts to stop pirating of music: RIAA Legal Tactics Scare File-Swappers

From the comments of the Electronic Frontier Foundation (EFF) representative it sounds like the EFF supports the pirates, not surprising when you consider their history of supporting copyright thieves.

I have friends who are musicians and writers and when someone copies (steals) a song my friends don't get paid anything for their creativity. The consequences are that they can't make a living from playing and writing and so they have to do something else and they don't create more music.

Now I'm not talking about big names or big stars, the kind of people who make millions, I'm talking about the people who make up the majority of the music industry - the people who make an average living playing in bands and writing songs. They don't make millions, they make about the same as the rest of us working at a 9 to 5 job.

So think of it this way, when you "swap" (steal) a song you just prevented another song from being created. Swap enough songs and there won't be any more new music.

Wednesday, August 20, 2003

Music Review - The Unknown by Conspiracy


Conspiracy consists mainly of Chris Squire (Yes) and Billy Sherwood (World Trade, Yes) and a great combination they make. The music is upbeat progressive rock with great harmonies, catchy hooks, smart lyrics and great melodies. That doesn't leave me with much more to say except that from start to end the excellence of the performance never flags.

I give it 5 stars. The Unknown by Conspiracy.

Monday, August 18, 2003

My Favorite Software Book Author


My favorite writer on software matters is Martin Fowler. What he has to say is always practical, useful and useable. I think the main reason for this is that he evaluates importances. He doesn't just throw 20 pieces of data at you without giving you any idea of what is important and what isn't.

For example, in his book UML Distilled he points out how useless Use Case diagrams are and that really the text of use cases is what you really need. I found this out the hard way myself when I utilized Use Cases for the first time some years ago. Reading his book first would have saved me a lot of wasted time.

Martin has a great website and an excellent blog called Martin Fowler's Bliki. I highly recommend them to any software developer.

Sunday, August 17, 2003

Anti-Virus Software


I'm trying out the BlogThis! feature you can add to your links toolbar in IE so that while surfing, if you find a cool site you can immediately make a blog entry. Just drag the "BlogThis!" link onto your links toolbar and it'll create a button for instant blogging - very cool.

I just surfed to the site for my anti-virus software and clicked my new "BlogThis!" button and in no time flat a blogger window poped up and away we go! The link to the site is created so all you have to do is type your blog entry around it - here's the link: Panda Software Antivirus

By-the-way, Panda is an excellent anti-virus product, much better than Norton and MacAfee (or is it McAfee?). I use Panda Titanium Anti-Virus and not only does it use far less resources than Norton, but it has caught every virus that's ever tried to get onto my machine - mainly through email. It's got a great user interface and is pretty much a "set it and forget it" program.

Anyway, I like it so it must be good :)

Free UML Tool



There's a great free (yes FREE) UML tool called Poseidon for UML Community Edition . It's the base version of Poseidon for UML but comes with all the features you'd want.  Not only can it create all UML diagrams, but it will generate Java code for you and even reverse engineer from Java source code.  It is a Java application so you can run it on any platform that has a Java Virtual Machine.  Not bad for a free download.

Saturday, August 16, 2003

Album Review - Celestial Entrance by Pagan's Mind

The review of Celestial Entrance by Pagan's Mind on ProgressiveWorld.Net caught my interest because the reviewer compared them to Dream Theater and emphasized the melody in their music.

On first listening I didn't agree. The album seemed rich in drumming and rythmic metal guitar but lacking in melody. However, after playing it on a different CD player (I've got to get rid of that old portable) I saw (heard?) the light. It took me three careful listens before I was hooked but I can now say this is a great album. And that's often the way it is for me, I'll think an album is okay or less than okay on first listen but it will gradually grow on me and end up being a favorite.

Pagan's Mind is a band from Norway playing high energy, intricate progressive metal. Celestial Entrance is their second album and if they can keep up this quality and energy it sure won't be their last.

About the only thing I'd like them to change in their future albums is their copying of Dream Theater riffs. They don't do it a lot and one of the songs is a tribute to DR, but I'd personnally prefer they stuck to their own music, which can certainly stand on its own.

On the plus side the musicianship is excellent. If they are half this good live then they are well worth seeing. Another thing I liked was the clever use of vocal effects to add drama to the songs.

This is a five star album.

This is my first post so forgive me if it doesn't really say anything except, "testing, testing, 1, 2, 3."