Object Oriented Programming Pillar #2: Inheritance

The second pillar of OOP is Inheritance. But if you read the title of today’s blog, you probably already guessed that. Inheritance allows us to both reuse and extend code, plus allow you to easily make changes to a class and have them ripple through to the decedents.

Take a look at the Employee class from yesterday. When I think of employees in a company, I can think of at least two kinds, Managers and Peons (like me). Both are types of employees, but both have some things different. Inheritance allows us to reuse the best parts of employees, but add special functionality as well.

Let’s create a new class, called Manager. Here’s what I coded:

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Manager : Employee

  {

    // Constructor, call the base

    public Manager(): base()

    {

    }

 

    // Meaningless work, just like a real manager would do.

    public void MakeHairPointy()

    {

      string myPointyHairOrder = “Write me a program by last week.”;

    }

 

  }

}

 

The first thing you may notice is the : Employee after the class Manager. This tells the compiler that the Manager class is descended from the Employee class. Any methods, properties, and events available in the Employee class are now automatically available in the Manager class.

Next you see a line that says public Manager(). This is the constructor for the class. In here you can put code that you want to execute when the class is created. Perhaps this is setting some defaults for class variables, creating other classes, or a variety of other items. I don’t need to do anything, so I’ve just left it blank.

After the Manager() you see the : base() construct. This tells the compiler “hey, before you run the constructor in Manger, go run the constructor in your base class, employee, then come back and run the Manager’s constructor”. Even though I don’t currently have any code in Employee’s constructor, one day I might. Plus if I’m following good encapsulation then I don’t know whether or not Employee has a constructor, nor do I care.

Using the base() keyword is not only common practice but a good idea. If you don’t, you’ll likely wind up on the side of the road, homeless holding a sign that reads “Will code() for food;”.

Enough on constructors, let’s look at a sample that uses our new Manager class.  

      Manager mgr1 = new Manager();  //Constructor runs here!

      mgr1.FirstName = “Arcane”;

      mgr1.Lastname = “Code”;

      mgr1.MakeHairPointy();

      MessageBox.Show(mgr1.FullName(), “Manager FullName Dialog”);

Even though you won’t find them in the code for the Manager class, you see I am calling FirstName, LastName, properties and the FullName method. The Manager inherited these from Employee.

Imagine you had not one or two types of employees, but fifty? Then imagine your boss wanted you to make a change to the FirstName property, so that if the length were only one character it automatically put a period at the end of the first name? Now you begin to see the power of inheritance.

You make your change to the Employee class, which is known as the base class. Recompile, and you are done. That change is automatically reflected in all of the child classes that inherit from the base Employee class.

What if you have a situation where you want to implement something in the base class in a slightly different way? You have the power to override the base classes implementation of that method. That’s a fancy way of saying you can create a method with the same name in your descended class, with your new code. But there’s a big “if” you need to know about. (Isn’t there always?)

When you create a method in a base class, you must use the virtual keyword in the method declaration. This flags the compiler that it’s OK to override in child classes. Without the virtual keyword, the compiler will produce errors and fail. So let’s fix our employee classes FullName method so we can override it later.  

    public virtual string FullName()

    {

      string returnValue;

      returnValue = _firstname + ” “ + _lastname;

      return returnValue;

    }

 

All that was really needed was to slip the virtual keyword between the scope and the return type. Now we are ready to rewrite this method in our Manager class. 

 

    public override string FullName()

    {

      return “Oh great one “ + base.FirstName + ” “ + base.Lastname;

    }

 

Now when I run my code, I will see the rewritten FullName for the manager appear.

 

[OOP Demo 2 Picture]

 

Note too the use of the base.FirstName and base.LastName. Through the keyword base, you can access any of the non-private properties and methods of the base class. I could just have easily have done:

 

    public override string FullName()

    {

      return “Oh great one “ + base.FullName();

    }

 

If you take some time to plan your code architecture (see my post https://arcanecode.wordpress.com/2007/02/07/arcane-thoughts-the-passion-of-the-programmer/ or http://shrinkster.com/lvw) you can probably come up with many good relationships where you can go from abstract to something more concrete.

A real world example, in my database layer I descend all data handling classes from a base class that has common properties / methods such as the connection string and a connection object. This lets me write the connection “goo” once and use it over and over.

Don’t forget that at their heart, forms and toolbox items are classes as well, and you can inherit from them. A common technique is to override all of the common controls and use your version in your applications. The technique is slightly different so I will defer discussion on inheriting graphical stuff until another day.

A classic story I heard on DotNetRocks (http://www.dotnetrocks.com) is the lead developer who gets a call three days before their 300 form application is due to go to production. “Oh by the way” says the customer, “we forgot to mention it but it’s a requirement that all text boxes force their letters to uppercase.”

Even though they had not tweaked the text boxes previously, they had still made a decision lo those many months ago to inherit from the base text box and use the new one in their project. Because of that, they made a quick change to one routine in their custom text box, and all 300 forms were fixed in less than half an hour.

Inheritance can be an incredibly powerful tool when used correctly, but as my favorite hero Spider-Man used to say, “with great power comes great responsibility”. Make sure your inheritance chain is well thought out, lest you feel trapped in a spider’s web of your own making.

Object Oriented Programming Pillar #1: Encapsulation

I was working with an IT person who was new to .Net and Object Oriented Programming (OOP). Since these were new concepts to my coworker, I thought they might be new to others as well and as such thought it’d be a good idea to spend a little time discussing them.

OOP has three basic concepts: Encapsulation, Inheritance, and Polymorphism. Let’s start today by going over the first, encapsulation. Encapsulation is a little like Las Vegas. What happens in a class, stays in a class.

Instead of reading the word encapsulation, instead substitute “self contained”. Your classes should be like a little black box. You can rewire the inside all you want, as long as the end results to the outside world look the same. Let’s look at an example, a simplified version of the classic employee class.

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Employee

  {

    private string _firstname;

    private string _lastname;

 

    public string FirstName

    {

      get

      {

        return _firstname;

      }

      set

      {

        _firstname = value;

      }

    }

 

    public string Lastname

    {

      get

      {

        return _lastname;

      }

      set

      {

        _lastname = value;

      }

    }

 

    public string FullName()

    {

      return _firstname + ” “ + _lastname;

    }

  }

}

 

I’ve kept it very simple, two properties and one method, FullName. Here’s a simple example of creating (aka instantiating) an employee object out of the employee class, loading it’s properties, then calling the FullName method.

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Arcane”;

      emp1.Lastname = “Code”;

      MessageBox.Show(emp1.FullName(), “FullName Dialog”);

 

Now let’s suppose, for whatever reason we need to rewrite the FullName method. In my example, we’ll pretend like a new coding standard has emerged that says you can never return a calculated value (like we did in the first write) but instead place it into a variable before returning it. This allows us to view the final result in the method quite easily.

We can do so, without having to change the routine (above) that called it. Here’s a new version of FullName.

 

    public string FullName()

    {

      string returnValue;

      returnValue = _firstname + ” “ + _lastname;

      return returnValue;

    }

 

When you run the application again, it still works. The routine that creates the emp1 object doesn’t know, and doesn’t care how you wrote the FullName routine. As long as you don’t change the method’s signature, you are free to rewrite FullName to your hearts content. That’s the beauty of encapsulation.

Arcane Thoughts: The Passion of the Programmer

One of my favorite bloggers is Jeff Atwood, and his Coding Horrors blog (http://www.codinghorror.com/blog/). Why? He’s passionate not just for code, but for coding.

I see a lot of people who are good at writing code. They know the syntax, can knock out some code, and get the application completed. Then there are people like Atwood, Steve McConnell, Paul Sheriff or Carl Franklin. These guys are passionate about the process of writing code.

When I speak of process, I’m talking about more than just writing, but the design of the code, how much reuse can you achieve from your existing components, do you do test driven development, waterfall, how often do you have code reviews, and more. This is the stuff that doesn’t help you write code, it helps you write better code.

Yesterday I had a root canal. I spent more than three hours in the dentists chair. Since there wasn’t much opportunity for stimulating conversation, I brought along my PDA and listened to some old DotNetRocks (http://www.dotnetrocks.com) episodes. In one of the episodes (http://www.dotnetrocks.com/default.aspx?showNum=104) Carl and Richard were interviewing Paul Sheriff on architecture.

During this episode, somewhere between the root canal and fitting a new crown, I realized that the coders who are passionate tend to also be architects, whether they realize it or not. They care about things like code reuse, good design, and adhering to standards.

If you are interested in learning more about architecture, I would recommend taking a look at the Patterns and Practices libraries at Microsoft. (http://msdn.microsoft.com/practices/). This is a collection of tools, e-books, and articles designed to not only recommend ways to architect your code, but the tools to get it done. Be sure to check out the “Getting Started” link on the upper left, it’s a good place get started on the road to not getting the job done, but getting the job done right.

Arcane Combinations: MaxiVista and UltraMon Tip

Two of my favorite Windows add-ins are MaxiVista and UltraMon. I’ve already blogged about each tool, https://arcanecode.wordpress.com/2006/08/30/9/ and https://arcanecode.wordpress.com/2006/09/06/multiple-monitors-made-even-easier/ respectively. When used together, they provide a great user experience, placing a task bar on each window.

I have discovered one issue when using the combo. My main computer is my big HP laptop. I also have my older desktop which has dual monitors, and my old IBM Thinkpad laptop which is handy for an e-mail monitor. I take these over from my laptop, using MaxiVista. When installed, MaxiVista sets up the HP Laptops internal monitor as #1, the desktop as monitors 2 and 3, and the Thinkpad as #4. I also have a big 21 inch monitor I hook to the HP Laptop, which becomes #5.

My problem arises when I don’t have the desktop turned on. UltraMon seems to check each monitor, and when it finds #2 is not on, it stops putting toolbars out. Very annoying. After a lot of searching I finally came upon a solution, and thought I’d share.

Right click on the UltraMon icon in the toolbar, and select Options… from the popup menu. Now click on the “Ignored Monitors” tab. Click on the monitor numbers that are not active, then check the “ignore this monitor” box.

[Picture of UltraMon Options]

 

 

 

 

 

 

 

 

 

 

 

 

There you go, just click on OK and your taskbar should appear. When you need activate the remote monitors, just open this and uncheck the “ignore…” option and you’re good to go!

Standard disclaimer, I don’t work for either company, nor make any money off sales, or receive any compensation. I just think they are some cool tools!

VS Add-In: Oracle Developer Tools for Visual Studio.Net

I found a useful and important add-in for those who deal with Oracle databases using Visual Studio. Oracle Developer Tools for Visual Studio.Net. ODT for VS adds an Oracle Explorer, similar to the Data Explorer built in to VS. It has an incredible amount of functionality built in.

I already mentioned the Oracle Explorer, which gives you a tree that lets you examine your tables (and columns), views, stored procedures, packages, sequences, and all of the other objects Oracle supports.

There’s a plethora of designers and wizards that will allow you to create and alter the aforementioned objects. They work by generating SQL that you can preview before it’s applied.

The feature I find most useful is the PL/SQL editor. Right inside VS I can now write my stored procedures. But what’s really powerful is I can set a breakpoint, and step from my VB.Net or C# code right into the stored procedure, step through the stored procedure, then back into my application. THAT is useful.

You can obtain ODT for VS directly from Oracle, at no cost. http://www.oracle.com/technology/tech/dotnet/tools/index.html or http://shrinkster.com/lry.

I did run into one issue after the install. Oracle installs it’s ODP driver and creates a new Oracle home for your machine. In order to make the connections I had to copy my tnsnames.ora, ldap.ora, and sqlnet.ora files from my old oracle home to the one for 10.2, by default it’s in C:\oracle\product\10.2.0\client_1\network\ADMIN. I found this solution and some other interesting tidbits at the FAQ: http://www.oracle.com/technology/tech/dotnet/col/odt_faq.html or http://shrinkster.com/ls0.    

I’m not going to regurgitate a lot of how to here, instead I’ll refer you to a good article on the Oracle site, at http://www.oracle.com/technology/oramag/oracle/06-sep/o56odp.html or http://shrinkster.com/lrz. This article has the basics to get you up and running.

If you work with Oracle databases, this is a must have add-on for your Visual Studio environment.

AL Tools

I found a cool suite of Windows tools I thought I’d tell you about. AL Tools (http://www.altools.net) has a suite of standard tools that have an attractive interface. They offer a ZIP tool, one for music, one for FTP, one to browse photos, and one to store passwords.

So far I’ve used the ALSee to view my collection of photos. It has a nice feature that will let you resize a slew of photos with just a few clicks, great when you have lots of pics to e-mail to the grandparents or upload to a website.

I’ve also used ALShow to view some of the IPTV shows I enjoy. http://www.dl.tv and http://crankygeeks.com for example. So far it’s handled everything I’ve thrown at it, it flows smoothly and resizes very well.

I’ve briefly explored the password program, it looks good for storing passwords to websites but I’m not sure so far if it will work well for non web apps. Eventually I plan to explore the other apps, next on my list will be the FTP program as it seems to have some nice features, such as automatically resuming when a transfer fails and handling transfers over 2 gig.

For personal use, all of their tools are free. I admit I like their interfaces, they are simple and clean, which is refreshing after some of the tools I’ve used lately. Check ‘em out, just make sure to go to the .net address, the .com address is in Japanese. Unless of course you happen to read Japanese, in which case you can go to whichever one you want.

Delegates Made Easy in C#

During my discussion of SQL Server Compact Edition, I mentioned Delegates. I thought I’d take a moment to cover what a delegate is, and how you can effectively use them in your application.

Let’s say you send an employee to the mall, and tell him “OK, when you get to the mall I will tell you which store to go in, because right now I haven’t decided yet.” A delegate is somewhat like that. You can tell your application that you are going to call a method with a certain signature, but you will tell it the name of the method at run time instead of compile time. (The signature, in case you haven’t heard the term, is the name and return type of the method plus the list of the data types of the parameters you pass.)

Let’s create a simple example. Create a new windows form app. Put on a label, a text box, and two buttons. When done, it should look something like this:

Now add a class, and name it “TheDoSomethingClass”. Once it’s created, we’ll need to put a declaration at the class level:  

    public delegate void DoDelegate(string msg);

 

We are creating a new variable type called DoDelegate. It’s descended from a Delegate, and has one parameter. It has to be pubic, so we can later create a variable of the DoDelegate type.

Next, we’ll add one method to the class, and pass in our delegate type.  

    public void DoSomething(DoDelegate doit)

    {

      for(int i=0; i < 3000;i++)

      if (doit != null)

      {

        doit(“Count=” + i.ToString());

      }

    }

 

This method has one parameter, “doit”. Notice that doit is of type DoDelegate. I created a little loop, just so we can see some action. Next, I check to see if the doit variable is null. This is very important, traditionally a delegate is never required but optional for use in your class. Thus you should always check to see if it’s null before attempting to use it. In the next line we actually call the doit method, and pass in it’s parameter, in this case a single string.

Now let’s look at how to use our delegate. Let’s return to our form, and add a new method. This method will be called ShowInLabel, accept a single string which it will display in the label control. I also added a DoEvents, just to get the label to update immediately.  

    private void ShowInLabel(string theMessage)

    {

      label1.Text = theMessage;

      Application.DoEvents();

    }

Now for the final step which ties everything together. In the click event for the button next to the label, we need to add two lines of code. The first line will instantiate a new object from our TheDoSomethingClass class. The second line will call the DoSomething method.  

    private void btnLabel_Click(object sender, EventArgs e)

    {

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.DoSomething(

         new TheDoSomethingClass.DoDelegate(ShowInLabel));

    }

 

Notice something important: in the second line we create a new variable of type DoDelegate. Perhaps if I do it in 3 lines it will make it slightly clearer.

 

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      TheDoSomethingClass.DoDelegate myNewDoDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInLabel);

      dsc.DoSomething(myNewDoDelegate);

 

As part of the constructor, we pass it the name of a method that has the same signature as the delegate. In this case, ShowInLabel has the same signature (one parameter, a string) as the delegate was declared with. The Delegate’s signature and the signature of the method you want to assign to it must match or you’ll get an error.

Now let’s flex our power a little. Create another method with a different name, but the same signature. This one we’ll call ShowInTextBox, and like the other we have to have one string as a parameter. In this method we will update the text box instead of the label with the passed in message.  

    private void ShowInTextBox(string theMessage)

    {

      textBox1.Text = theMessage;

      Application.DoEvents();

    }

Now in the click event for the button associated with the text box, we’ll repeat the code from the other button with one exception. In the constructor, we’ll pass in the name of the new method.  

    private void btnTextBox_Click(object sender, EventArgs e)

    {

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.DoSomething(

        new TheDoSomethingClass.DoDelegate(ShowInTextBox));

    }

DoDelegate method what so ever, yet it was able to call a completely different method.

You can also store the delegate, in case you want to use it for several methods in your class, or manipulate it a bit easier. Put this code in your class (note I squished down the get/set to save a bit of space, I don’t normally code that ugly.) I added a private variable to hold our delegate, a property get / setter, and a new method that will take advantage of it.  

    private DoDelegate _TheDelegate;

 

    public DoDelegate TheDelegate

    {

      get

      { return _TheDelegate; }

      set

      { _TheDelegate = value; }

    }

 

    public void DoSomethingElse()

    {

      for (int i = 0; i < 3000; i++)

        if (_TheDelegate != null)

        {

          _TheDelegate(“Count=” + i.ToString());

        }

    }

Now to call it, all we have to do is go back to our form and add this code to a button click event:

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.TheDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInLabel);

      dsc.DoSomethingElse();

      dsc.TheDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInTextBox);

      dsc.DoSomethingElse();

Note here I changed the delegate between calls, I could have also coded more methods that used the same call. Also note if I had tried calling DoSomethingElse before assigning a delegate, the program would have run just fine I just wouldn’t have been shown any messages, thanks to the if ( _TheDelegate != null) statement.

Now that I’ve shown you how a delegate works, let’s take a moment to discuss some times when you might want to use it. The first example I can think of is to support an add in architecture. You can dynamically load DLLs at run time, and when you do you can query it to see if it supports a certain delegate type, perhaps one for communicating a message like our example. If so, you can assign that delegate to the message handler for your particular app. Not only does this mean you can use multiple add-ins with the same app, it also means you could support multiple apps with one add-in.

Here’s another example from my personal experiences. I have a winforms app that can connect to multiple database. (Each of our sites has it’s own database.) Most users only need to connect to one, so I save the database they were last connected to in the settings file. When the user reloads the app, I reconnect to the same database.

When my app loads, there are a lot of lists of values I retrieve to populate drop down combos. During load, however the only form visible is my splash screen. Using delegates in my load routine I have all progress messages from my data layer displayed on the splash screen.

During the course of using my program, the user can choose to hook to a different site, and hence a different database, which means I have to reload all those lists of values again. This time though, I don’t have the splash screen up. True, I could show it again, but it would look really goofy.

Instead, in my load routine I instead pass a delegate to the data layer that instead will display progress messages on the status bar control at the bottom of the form.

The beauty of this is that the data layer has no clue where or if it is displaying messages, nor should it have to care. I can also reuse this data layer DLL in other apps down the road, should the need arise, and take advantage of the status messages it provides.

In my example I have kept it simple and used a single parameter for my delegate. Know that you are not restricted; you can use multiple parameters if you wish. The important thing to remember is your signatures must match. The return type and number of parameters for your delegate (DoDelegate) must match the signature of the methods you assign to it (ShowInLabel, ShowInTextBox).

When designing your classes, especially those destined for DLL libraries that could get multiple use, consider adding some delegates as a way to inform your consumer of the progress of your methods.

There you go, a short step by step for delegates in C#. If you think of some new uses for delegates, drop a comment and let us know.