Friday, December 4, 2009

Inheritance, and why it rocks!

Inheritance is something that is very foreign to a VB6 developer, however it is very, very cool. Think about this scenario lets say your are on a team of developers. You are working on a product intended to sell to a retailer who wants to process credit cards. But each retailer will use a different credit card processor so you need to support Costco, paypal, and Autorize.Net. Your job is to write the code that connects to the gateway, but there are other devlopers on your team that need to be able to use your code. How do you give them one interface to your code, but you want to execute the right routine based on the credit card processor? Well inheritance offers the perfect solution.

Here we create our 'base' class. We declare it as MustInhert so that we can use the MustOverride property on the ProcessCard Function

Public MustInherit Class CreditCard

  Public MustOverride Function ProcessCard(ByVal CardNumber As String) As Boolean

End Class


You'll notice that we created a function signature, but it has no code attached. We add the code later when we create the gateway's class.

When your create your class that inherits your base class you'll notice when you add the line 'Inherits CreditCard' that it will autofill the MustOverride Function.  Visual Studio makes it easy for you!

Public Class Costco
  Inherits CreditCard

  Public Overrides Function ProcessCard(ByVal CardNumber As String) As Boolean
    'code to process a costco card
  End Function

End Class

Public Class AutorizeNet
  Inherits CreditCard

  Public Overrides Function ProcessCard(ByVal CardNumber As String) As Boolean
    'code to process a Autorize.Net card
  End Function

End Class

Public Class PayPal
  Inherits CreditCard

  Public Overrides Function ProcessCard(ByVal CardNumber As String) As Boolean
    'code to process a PayPal.Net card
  End Function

End Class

Your other team members will love you if you now use a 'wrapper' to manage the gateway, check this code out:

Public Class MyCreditCard
  Private mGateWay As CreditCard

  Sub New()
    'ASK THE DATABASE OR INI OR SOMETHING
    'WHAT PROCESSOR TO USE and put it in i
    Dim i As Integer

    Select Case i
      Case 0
        mGateWay = New Costco
      Case 1
        mGateWay = New AutorizeNet
      Case 2
        mGateWay = New PayPal
    End Select

  End Sub

  Public Function ProcessCard(ByVal CardNumber As String) As Boolean
    mGateWay.ProcessCard(CardNumber)
  End Function
End Class

Now your UI guy just has to write something like this and he never has to worry about which credit card processing gateway you are using.

  Public Sub ProcessCC()

    Dim cc As MyCreditCard = New MyCreditCard

    cc.ProcessCard("12456789012345")

  End Sub

No comments:

Post a Comment