asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Object-Oriented Programming for VBScripters
By Robert Chartier
Rating: 3.6 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    If you want to make the move to .NET and feel intimidated by object-oriented programming (OOP), this article is designed to ease any level VBScripter (ASP) into .NET by clarifying some OOP concepts.

    Objects, Types, and Variable Scope

    Think of an "object" as simply a container that could have state, behavior, and identity. Objects are typically represented as a "class" and are considered to be a custom "type." Every single program you create will be composed entirely of classes.

    Let's start with the basics. There are a few big differences between classic ASP and .NET, more specifically VBScript and C#. With VBScript, all variables are of type "variant," which means they can be treated as any data type you wish. Any action taken when performing some action on the variable was determined by the action and the data in the variable itself. For example:

    
    a = "1"
    a = a + a
    response.write a
    
    
    will produce "11", but
    
    a = 1
    a = a + a
    response.write a
    
    
    will produce "2"

    This is because the ASP engine attempts to determine the subtype of the variant and perform the addition (or concatenation) operation on it.

    With C#, you are no longer faced with this. C# mandates specifying the exact variable type, and limits what you can do with that variable based on its type. This is desirable for many reasons. For example, there are no misconceptions about what will happen when using a variable. It becomes very predictable. Some of the more basic data types in C# and the .NET Framework include string, int, long, etc.. All of these should be fairly familiar, including their capabilities and basic operations.

    Variable scope rules in C# play a larger role. In VBScript, without having "Option Explicit" turned on, we could create and use any variables at any time. This is typically one of the biggest problems with code maintenance. Developers created variables all over the place, sometimes for no apparent reason, and expected the administrator to know what each is used for. People became lazy because the environment allowed them to be.

    C# requires you to declare all variables, including their type. There's no more guessing the purpose of a variable based on its name. Now we can guess based on the name and data type! Along with this, it is the responsibility of the programmer to use "good" naming standards for variables and comment effectively in order to help those who maintain the code.

    Scoping rules pay a large role in most languages. Variables can be broken down into two types, global and local. A global variable is available to all portions of the object or application. It can be seen and used globally. A local variable is only available to a specific method or section within the object or application. It is created, used, and destroyed within that finite section and no other areas have access to it (See Figure 1.1).

    Figure 1.1 Understanding Scope

    
    Dim A
    
    Function doThis() 
    	Dim B
    	Response.write B
    End function
    
    Function doThat()
    	Dim C
    	Response.write C
    End function
    
    Notice how the "A" variable is declared out of the two methods. Since this is the case, it is deemed as "global" to those two methods, which implies that each of the two methods have access to that variable. Notice the "B" and "C" variables are declared within the two methods. These variables will not be available outside of those methods. Their memory space is allocated and destroyed within those methods. This means that they are private to those methods.

    Namespace

    A "namespace" can simply be considered a library of classes. We can group together a project or a set of classes together into a namespace. It is probably best to consider it a logical grouping structure element. In many cases there would be a need to create classes with the same name, but for different purposes. With namespaces we can separate these different classes into logical groupings to avoid a collision of these classes. Some organizations like all their namespaces to start with a common top level, something like the company name. (Santra.DataTie, Santra.WebServices, etc.). This allows for developers to easily distinguish in-house objects from those that are provided by the framework. The last thing to remember about namespaces is that they cannot contain other namespaces.

    In C#, whenever we wish to import (or make available) a specific namespace into our current project, we must use the "using" keyword. This instructs the compiler to include that specific namespace into this project when compiling. The compiler then knows that each public class within that namespace is available to this project. Figure 1.2 demonstrates a custom namespace that contains a custom class.

    Figure 1.2 Namespace Demonstration

    
    using System;
    //our custom namespace
    namespace SampleOOP {
    
      //our custom class
      public class Person {
    
        //some member variables
        private string firstName;
        private string lastName;
        private string emailAddress;
        private System.DateTime birthDate;
        
       //for the member variables, we use getters and setters
       //for the properties
        public string FirstName {
          get {return firstName;}
          set {firstName=value;}
        } 
        public System.DateTime BirthDate {
          get {return birthDate;}
          set {birthDate=value;}
        }
    
       //a read only property
        public int Age {
          get {return CalculateAge( System.DateTime.Now ); }
        }  
       //a protected method.  We will cover more on this later
        protected int CalculateAge(System.DateTime ThisDate) {
          return (ThisDate-birthDate).Days/365;
        }
        
      }
    }
    
    

    Public, Protected, and Private

    Whenever we create a class we must be able to control what access other objects have to its internal members. One of the fundamental goals of OOP is the ability to hide the implementation of the object itself (encapsulation). OOP hides the messy details inside and allow others to use it without concern about how it was implemented. We can use the keywords "public," "protected," and "private" to facilitate this need to control the access to the class. Each of these are described here:

    1. Public -- Anything that can create an instance of this object has access to this member.
    2. Protected -- Only classes that are derived from this class have access to this member. (We will cover "derived" classes later.)
    3. Private -- This member can only be accessed by other members within this specific class.

    Look back at Figure 1.2 and notice each of these keywords is used. The variables within the class have been declared as private. This means only the methods within this class have access to them. But notice that we have the properties (using get/set) that have public access. Properties such as this enforce the idea that we should never allow any outside object to influence internal member variables of a class directly (more encapsulation). In most of the classes you create, you want to limit the number of public members to the minimum that is necessary to facilitate that object's purpose. Private members should be also used at a minimum because they do not allow for inherited classes to access them. That leaves us with most of our members being defined as "protected." Whenever I create a class, I will typically set all non-public members to protected, until it is about to go into production. And then those that I will not need in any derived class, I set to "private."

    Object Inheritance

    Object inheritance is a fairly simple concept to understand, but it has to be one of the most important features available. Essentially it allows us to create a "child" class that takes on the members and properties of another class, the parent. If we take a look back at Figure 1.2, we see a basic "Person" object. We can represent a simple person with this object. Now we need to represent an "Employee," which is exactly the same as a Person, but with a few added members. Take a look at our Employee:

    Figure 1.3 Inheritance Example

    
    namespace SampleOOP {  //**1**
      public class Employee : Person {   //**2**
        protected double wage;
      
        public double Wage {
          get { return wage; }
          set { wage = value; }
        }
      }
    }
    
    
    Notice a few things here, the first marked item ("**1**") shows us that this class shares the same namespace because it can be assumed that these two classes can be logically grouped together. The next item ("**2**") shows us how we derive from our Person class (our base class). This implies that when we create an instance of the Employee object, it will contain all of the Public members of the Person object and, of course, its own Public members. If we think back to the previous section, we see that we have "protected" members. These will make more sense now. The members in the Person class that were marked as protected are also available in the Employee class.

    Constructors and Overloading

    When we create a class, there are also some special methods we can create to initialize that object with our default settings. The first is a "constructor," which is a method that is called when the object is first created. It takes on the same name as the class and has no return type at all. This is an important ability that our classes can exhibit because it allows for us to execute some code immediately after the object is created. A perfect example of this would be to set the internal state of the object to its defaults. Every class that is created will have a default constructor, no matter if you define it or not. The underlying framework will automatically add the default constructor for you if you do not specify one explicitly.

    In the real world, a simple default constructor that cannot take any input from the calling class is usually pretty useless. So what we can do is take advantage of "overloading." This means that we can create a method with the same name, but that has different parameters and no return type. A point to remember is that you can overload any of your methods in your class, just as long as they have different signatures. A method signature is made up of only its inputs; the return is not included.

    Refer back to Figure 1.2 and see that there are no methods that take on the same name as the class. This means that this class has no default constructor defined. In Figure 1.4 below, we modify the class and add the default constructor, including one overloaded constructor.

    Figure 1.4 Constructors

    
    using System;
    //our custom namespace
    namespace SampleOOP {
    
      //our custom class
      public class Person {
    
       //class constructors
       public Person() {  //**1**
       }
    
      //**2**
       public Person(string firstname, string lastname, string email, System.DateTime birthdate) {
       	firstName = firstname;
    	lastName = lastname;
    	emailAddress=email;
    	birthDate = birthdate;
    }
    
        //some member variables
        private string firstName;
        private string lastName;
        private string emailAddress;
        private System.DateTime birthDate;
        
       //for the member variables, we use getters and setters
       //for the properties
        public string FirstName {
          get {return firstName;}
          set {firstName=value;}
        } 
        public System.DateTime BirthDate {
          get {return birthDate;}
          set {birthDate=value;}
        }
    
       //a read only property
        public int Age {
          get {return CalculateAge( System.DateTime.Now ); }
        }  
       //a protected method.  We will cover more on this later
        protected int CalculateAge(System.DateTime ThisDate) {
          return (ThisDate-birthDate).Days/365;
        }
        
      }
    }
    
    
    Marker 1 ("**1**") shows our default constructor, which takes no action. Even more important is marker 2 ("**2**"). It shows us the overloaded constructor that accepts the parameters to initially load up the objects.

    The only time we can take advantage of these constructors is when we create a new instance of the object.

    
    //creates the Object, calling the default constructor
    Person rob = new Person();  
    
    //creates the Object, calling the overloaded constructor
    Person roboverload = new Person("rob", "chartier", rob@santra.com, new System.DateTime("December 16, 1974"));
    
    
    It is important to understand why we would do this. If we did not have the ability to use constructors, we would either need to:

    • create a new method that would allow us to perform the same action as the constructor (such as a method called "Init" that did nothing other than perform this same initialization of our object),
    • or call the property (get/set) for each item we want to set into the object.

    This is a lot of work that we would want to avoid.

    Conclusion

    In this article I have merely covered the bare minimum that you should investigate during your exploits into the .NET Framework and OOP. Once you fully understand the content covered here, you will want to dive into these concepts:

    1. Virtual and Override
    2. Interfaces vs. Multiple Inheritance
    3. Abstract Classes
    4. Design Patterns
    5. Unified Modeling Language (UML)

    The last two items on that list will take you deep into the OOP world. You must first fully understand everything presented here and the first three items on the above list before you begin down the path of design patterns and UML. I also recommend that you pick up a book James W. Cooper's book, Visual Basic Design Patterns: VB 6.0 and VB.NET with CDROM (see http://books.internet.com/books/0201702657). Or you could wait for James Cooper's up-and-coming C# publication to hit the market.

    About the Author

    Robert Chartier has developed IT solutions for more than nine years with a diverse background in both software and hardware development. He is internationally recognized as an innovative thinker and leading IT architect with frequent speaking engagements showcasing his expertise. He's been an integral part of many open forums on cutting-edge technology, including the .NET Framework and Web Services. His current position as vice president of technology for Santra Technology (www.santra.com) has allowed him to focus on innovation within the Web Services market space.

    He uses expertise with many Microsoft technologies, including .NET, and a strong background in Oracle, BEA Systems, Inc.'s BEA WebLogic, IBM, Java 2 Platform Enterprise Edition (J2EE), and similar technologies to support his award-winning writing. He frequently publishes to many of the leading developer and industry support Web sites and publications. He has a bachelor's degree in Computer Information Systems.

    Robert Chartier can be reached at rob@aspfree.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Aug 7, 2002 - Using MySQL in the Win32 Environment
    Developers who don't want to spend a lot of money on SQL Server and who want a database that's more robust than Access may find MySQL to be a pleasant alternative. This introductory article covers the bare essentials for getting MySQL installed and running in the Win32 environment.
    [Read This Article]  [Top]
    Jul 17, 2002 - Software Development: Steps To Better Ensure Success
    There is never a guarantee of project success when endeavoring to build a sophisticated application. However, there are established steps to follow that will ensure a clear, concise scope, support for the team involved, and a solid opportunity for successful deployment.
    [Read This Article]  [Top]
    Jul 15, 2002 - Securing SQL Server for Web Applications
    If your SQL Server is exposed to the Internet, then hackers are probing it. This article shows how to secure a SQL Server database that's being used with a Web application
    [Read This Article]  [Top]
    Jul 1, 2002 - Protecting Your Web Application Against Dangerous Requests
    Enrico Di Cesare provides a solution for hiding and securing querystring values that pass through a url.
    [Read This Article]  [Top]
    Mar 27, 2002 - A Best Practice for Using ADO Objects
    A few members of the 15 Seconds discussion list talk about the proper way to use methods in order to prevent ADO object errors.
    [Read This Article]  [Top]
    Jan 2, 2002 - The ASP.NET Page Life Cycle
    Solomon Shaffer explores the life cycle of an ASP.NET page from initialization to unloading. He also explains the various methods to override ASP.NET server-side events.
    [Read This Article]  [Top]
    Dec 19, 2001 - Application Architecture: An N-Tier Approach - Part 2
    Rob Chartier creates a simple portable and reusable address book in .NET to demonstrate the power of N-tier application architecture. Complete source code included!
    [Read This Article]  [Top]
    Oct 23, 2001 - Application Architecture: An N-Tier Approach - Part 1
    Learn about N-tier application architecture and realize that developing with multiple layers produces a flexible and reusable application for distribution to any number of client interfaces.
    [Read This Article]  [Top]
    Oct 23, 2001 - Application Architecture: An N-Tier Approach - Part 1
    Learn about N-tier application architecture and realize that developing with multiple layers produces a flexible and reusable application for distribution to any number of client interfaces.
    [Read This Article]  [Top]
    Sep 11, 2001 - Randomizing a Recordset
    Ed Myers' article shows several ways to use a SQL calculated field and the ORDER BY clause to arrange a recordset in random order. A simple tool is provided for verifying that the results are uniformly random. A technique for bubbling records with certain attributes to the top of an otherwise randomized list is also shown.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers