Design Patterns in VB.NET
page 3 of 4
by David Simmonds
Feedback
Average Rating: 
Views (Total / Last 10 Days): 60312/ 60

GoF Principles to code by

Design patterns did not just appear out of thin air.  They evolved from the application of certain design goals, which are widely known throughout the O-O community and which are taught along with almost every O-O language.  These include low-coupling, encapsulation and high-coherence.  You are expected to know these already.  To this the GoF have added certain higher-order design principles which help us to understand how the patterns came about and use them to test our application of the patterns.

Interface inheritance versus Implementation inheritance

The GoF hate inheritance so much that you would think one of them inherited a dog that bit him.  OK, so that is a bad attempt at humor, but the point is they really abhor class inheritance and with very good reason.  The truth is that any person who grew up in a Ghetto, but rejected the values generally passed on in those circumstances, would understand why class inheritance can be a terrible thing.  It locks in the behavior that your class is based on the parent class it inherits from.  Inheriting from a super-class is like getting from your behaviors hard-coded into you through the passing on of your parents’ genes.  It is hard to override inappropriate behaviors.

This, obviously, is why you have Interfaces in VB along with a compromise between class and interface inheritance: Abstract (MustInherit) Classes, along with a plethora of ways to inherit methods (mustoverride, overridable, notoverridable and shadows) in VB.  In social terms, Interfaces give you principles to live by.  These help you to figure out how to respond to life on a situation by situation basis, while parent inheritance means that you are limited to behaving the way your parents’ genes dictate.

Let us look at everyone’s favourite issue, money.  As responsible adults, we all have to earn a salary which allows us to care for our families.  However, we also need to ensure that the money we have stretches until more comes in.

We can declare an interface for a fiscally responsible person:

Interface GoodProvider
    Function EarnMoney ()
    Function ManageMoneyWisely()
End Interface

 

Your parents might have implemented it as:

' Parents interpretation of fiscal responsibility
Class YourParent
    Implements GoodProvider
    Function ToiledInTheField () Implements GoodProvider.EarnMoney
        MessageBox.Show("I go to my farm and plant and reap to sell at market")
    End Function
    Function KeepMoneySafe() Implements GoodProvider.ManageMoneyWisely
        MessageBox.Show("I keep my money under the mattress")
    End Function
End Class

 

But times change and so your implementation might be:

 

' You adapt to the new circumstances while fulfilling the same requirements:
Class ModernPerson
    Implements GoodProvider
    Function ExcelAtCareer() Implements GoodProvider.EarnMoney
        MessageBox.Show("I develop software using design patterns!")
    End Function
    Function InvestAstutely() Implements GoodProvider.ManageSalaryWisely
        MessageBox.Show("I talk to my stock broker regularly")
    End Function
End Class

 

Education generalizes our career options and allows us to earn a salary in any one of thousands of ways, some of which are more suited to our tastes, styles, abilities and makeup than others.  By specifying the required interface which we need to implement and allowing the class which implements the functionality to worry about how to get it done, we encapsulate that knowledge and allow for loose coupling between your classes and the clients which use them (in this case your children).

On the other hand, if we were to use class inheritance in this case, we would be locked into the behaviour of the parent class.  It would mean that if the parent class implemented the WorkedAtTheirJob using farming techniques, we similarly end up farming.  If we found it impossible to keep farming then we would be in trouble!  The problem is that left to the default situation, the default behaviour is carried through.  With interfaces and abstract classes, there is less default behaviour and so the natural thing is to figure out how to implement the functionality in each class.  It also means that we can interchange the implementing classes (so a child provided for by a stock broker can be just as well taken care of as a software developer’s child)

As the GoF point out, Inheritance breaks encapsulation since the behaviour and functionality of the subclass is tied to the ParentClass.

 

Object Composition instead of Inheritance

Think of Class inheritance versus Object composition in this way.  Suppose you got your car tires from the manufacturer, with the tire fixed inextricably to the rim.  This would be a problem and you have one solution: drive extremely slowly so the tread never wears out.  The better way is to make the wheel in a manner which allows it to be composed of a separate tire and rim.  If anything happens to one, you just change it and the other is still good to go.  The rim gets bent, you replace (or straighten) it.  If the tire gets worn, buy a new tire and have them put it on the rim.  The sweet thing is that it allows you to not only fix problems such as tire wear, but also enhance performance.  If you want a quieter or more fuel efficient roll, you can change the tire material; want better handling, go for lower profile tires.  Supposing you like the way your car looks but think the rims could lift the appearance, you can setup the car to look vastly different by changing the rims.  The cosmetic-object in this case is the rim and you can extend the look by changing it.

In an organization, object composition is what we do with departments and teams.  Instead of saying "I want someone to tune the database, manage security permissions for it, implement changes to table structures," we simply say “Get me a DBA.”  Throw in a couple of people who know how to write code (Programmers), someone who knows some advanced VB.NET (UML), and knows how to talk to users (Software-Engineers) then you have a development team.  The Bridge pattern, Adapter pattern and Command pattern and some other patterns rely on this principle of object composition.

Find what varies and encapsulate it

When you look at an automobile, you see that there is disposability built into the parts.  If they did not do it this way, you would have to change your whole engine when any major part wore out.  Cars would experience incredible plunges in resale value for every 10,000 or so miles they drive.  After 50,000 miles most cars would be absolutely un-maintainable.  What causes mechanical engineers to have to build in varying levels of disposability of parts?  

Well, there is an engineering principle that the more moving parts you have in a machine, the more susceptible it is to breakdown.  The moving parts wear against each other and fail.  The ordinary person sees this most in their shoes.  Thus, engineers build in changeable bearings, bushings and rubbers; parts which represent the interfaces between the moving parts and so bear the brunt of the wear.  Being mostly made of rubber, they are relatively inexpensive to change once the wear out.  You see this clearly in good software, except that instead of parts that literally wear against each other, we have code that wears against moving and changing user requirements.  Just as car makers build loose coupling into their car parts for interchangeability due to wear, we must build in interchangeability within our code.  We must determine what functionality requirement can vary over time, encapsulate it and instead of interacting with it directly, interact with it through an interface.  Many times it means making the structure of our code a bit more involved, but because we do it with recognizable design patterns, the developer who is grounded in patterns can almost instantly figure out the interactions within our classes and figure out which classes to change, substitute or add when a change in requirements comes about.  This is similar to a mechanic who knows which front end part to check and change when a tire wears unevenly.  And just as a mechanic knows which particular bolts to pull in order to change a front-end part without pulling the whole front-end, our software developer knows how the new class should be “bolted” into the other parts in our system.  So when a change is made, he can quickly access the code in the rest of the system which refers to that changed/substituted class in order to swing the updated or new class into use.

 

My contribution to the Design Principles: Separate Object models from Algorithms

The GoF did not mention this as a general design principle or theme.  They did mention it as a benefit of the Visitor pattern.  But looking at Composite, Iterator, Visitor and Interpreter, I see when it is worth generalizing it into a design principle because it is a recurrent theme running through those patterns.

The point is you should isolate the algorithms that you use on an object model from the object model itself as much as possible.  This may not seem clear right now, but when you look at the patterns mentioned above you will see the power of applying this principle.  You will be able to change object-hierarchies in a way which does not interfere with the operations that need to work on the components within that model. 

Incidentally, some folks will realize that the separation of object model from algorithms is very similar to the principle of encapsulating what varies, since in most cases the object model tends to be very stable while the algorithms will evolve over time.

 


View Entire Article

User Comments

Title: Code samples   
Name: Mike Angelastro
Date: 5/12/2008 10:13:13 AM
Comment:
What is a good source of VB .NET code samples for the design patterns?
Title: How do design patterns fit with SOD/SOP   
Name: Mike Angelastro
Date: 5/12/2008 10:10:30 AM
Comment:
How do design patterns fit with Service Oriented Design/Service Oriented Programming? The underlying principles are similar.

Another metaphor is a schematic diagram of an electronic circuit or logic circuitry. These explain how item is put together.
Title: Response to Estevez - Part II : Philosophy of Design Patterns   
Name: David M. Simmonds
Date: 5/21/2007 3:26:11 PM
Comment:
On the other hand, design patterns do have a very philosophical basis. The philosophy which applies to design patterns (and undergirds many religions) is that if you delay gratification (in this case the implementation of the software) and put more work into the design upfront, then you reap less pain overall and in the long run (maintaining one aspect of the system does not mess up other parts of the system). Modifications can be done painlessly and cheaply without testing every other feature in the software. Hence programmers would be involved in less "software crises".

Anyway, watch for the day when the due diligence (which is done leading up to a corporate merger/buyout) includes a software design review which determines whether the mergee has software built using design patterns. At that point, you are going to see just how tightly intertwined philosophical issues and Dollar issues can be.
Title: Response to Estevez   
Name: David M. Simmonds
Date: 5/21/2007 2:04:47 PM
Comment:
In response to Estevez:
"I think Design Patterns are an philosofic part
of programming, can't see any worth of using it."

My response is, TRUE !!! Especially if you work in your IT department's Pre-Requirements-Change unit (the Software-Development counterpart of the Pre-Crimes unit as portrayed in "Minority Report")

In other words, if you are a precog and you can read the user's minds from the day you collect User Requirements in order to do your Software Specifications, then you will never need to modify functionality in your software or add features to it. So you are right, why spend all of that effort designing the software to make it easy to extend or modify when it never needs to be modified or extended?
Title: Art of programming   
Name: Estevez
Date: 5/18/2007 5:11:20 PM
Comment:
I think Design Patterns are an philosofic part of programming, can't see any worth of using it.
Title: nice Analogy   
Name: Amos
Date: 5/10/2007 6:05:32 PM
Comment:
The way to use a car and car industry to illustrate patterns and software kick-ass.
Title: Perfect WHY article   
Name: Vin
Date: 4/13/2007 3:58:52 PM
Comment:
Everyone will be motivated to learn about design patterns after reading this article
Title: Easy to Read   
Name: Mayank
Date: 2/16/2007 11:46:26 AM
Comment:
The article is very well written & informative. It deals with a complex subject in a very lucid manner. Expect more such great articles in future.
Title: Look forward to more in the future   
Name: Ben
Date: 1/29/2007 6:41:04 PM
Comment:
Great article, I enjoyed it very much. Hopefully there will be follow-up articles with even more detail!
Title: Fantastic :)   
Name: Kris
Date: 1/26/2007 7:40:12 AM
Comment:
Very elegantly described and introduced to design patterns.
Probably also listing what excatly are 23 patterns defined, would make this article more informative
Title: So cool   
Name: Luis Vega
Date: 1/23/2007 5:19:38 PM
Comment:
Excellent Article, I want to read more.
Congratullations
Title: Good Analogies   
Name: Ali
Date: 1/18/2007 5:01:33 AM
Comment:
Great article! Very very nice real world examples. I am expecting great articles regarding this article in future.
Title: Solar System   
Name: Miri Davidian
Date: 1/15/2007 9:17:29 AM
Comment:
Dear Sir,

I have a question.
I would be grateful if you would help me.
What would be the design patterns solution for solar system?
The Sun, is obviously singleton.
The plans are obviously factory.
But, when it becomes to the stars,
I wonder what they are.
On one hand, the stars are factory for the sun;
on the other hand each is a singleton for his own plans.
So, what are they?

Many thank in advance,
Miri
miridavidian@gmail.com
Title: very good   
Name: Rushikesh K Khairnar
Date: 1/7/2007 1:35:09 PM
Comment:
Simple and informative
Title: Nifty   
Name: Denny Jacob
Date: 12/27/2006 3:48:46 PM
Comment:
Simple, flowing and not one wasted word. I wish more of us had this pattern of writing!!!!
Title: Very Good   
Name: Pandi
Date: 12/26/2006 12:01:56 PM
Comment:
It was very good to a new person who wants to know about Design patterns.
Title: many thanks   
Name: Monica
Date: 12/18/2006 11:58:07 AM
Comment:
clear view of how design patterns came to light!
Title: Tanks   
Name: Shaik Kaleelur Rahman
Date: 12/18/2006 5:32:27 AM
Comment:
Very Nice Article
Title: Well Done - Three Cheers   
Name: Rajeev Gopalakrishnan
Date: 12/12/2006 4:10:56 PM
Comment:
Wonderful, my friend, wonderful! I can't say that any more louder!!
Title: cool   
Name: shubha N
Date: 9/11/2006 5:44:18 AM
Comment:
this artical is very informative
Title: very informative   
Name: gowri shankar
Date: 9/11/2006 5:42:53 AM
Comment:
it was very informative good work
Title: Nice   
Name: Veeru
Date: 8/25/2006 8:58:23 AM
Comment:
This very nice,very useful to every one,and this is a wonderful job......
Title: KISS   
Name: George
Date: 7/27/2006 11:34:53 AM
Comment:
Keeping it Simple and Straight. A very refreshing article, waiting to see more of this... Great job
Title: Plain and Informative   
Name: Mehdi Anis
Date: 7/21/2006 3:51:23 PM
Comment:
I enjoyed reading this article. nicely written delivering good information. Thanks.
Title: Cool   
Name: Ed
Date: 7/18/2006 7:48:51 AM
Comment:
Great Article. Very useful. Wonderful job
Title: Cool   
Name: Ed
Date: 7/14/2006 6:03:56 PM
Comment:
Great Article. Very useful. Wonderful job!!!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 9/21/2014 8:06:19 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search