Saturday, January 30, 2010

Polymorphism

The best and most concise definition I've heard for polymorphism is that it is functionality that allows old code to call new code. This is arguably the biggest benefit of object-oriented programming because it allows you to extend or enhance your system without modifying or breaking existing code.
Let's say you write a method that needs to iterate through a collection of Employee objects, calling each object's CalculatePay method. That works fine when your company has one employee type because you can then insert the exact object type into the collection. However, what happens when you start hiring other employee types? For example, if you have a class called Employee and it implements the functionality of a salaried employee, what do you do when you start hiring contract employees whose salaries have to be computed differently? Well, in a procedural language, you would modify the function to handle the new employee type, since old code can't possibly know how to handle new code. An object-oriented solution handles differences like this through polymorphism.-
Using our example, you would define a base class called Employee. You then define a derived class for each employee type (as we've seen previously). Each derived employee class would then have its own implementation of the CalculatePay method. Here's where the magic occurs. With polymorphism, when you have an upcasted pointer to an object and you call that object's method, the language's runtime will ensure that the correct version of the method is called. Here's the code to illustrate what I'm talking about: -
using System;

class Employee
{
    public Employee(string firstName, string lastName,
                    int age, double payRate)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.payRate = payRate;
    }

    protected string firstName;
    protected string lastName;
    protected int age;
    protected double payRate;

    public virtual double CalculatePay(int hoursWorked)
    {
        Console.WriteLine("Employee.CalculatePay");
        return 42; // bogus value
    }
}

class SalariedEmployee : Employee
{
    public SalariedEmployee(string firstName, string lastName,
                            int age, double payRate)
    : base(firstName, lastName, age, payRate)
    {}

    public override double CalculatePay(int hoursWorked)
    {
        Console.WriteLine("SalariedEmployee.CalculatePay");
        return 42; // bogus value
    }
}


class ContractorEmployee : Employee
{
    public ContractorEmployee(string firstName, string lastName,
                              int age, double payRate)
    : base(firstName, lastName, age, payRate)
    {}

    public override double CalculatePay(int hoursWorked)
    {
        Console.WriteLine("ContractorEmployee.CalculatePay");
        return 42; // bogus value
    }
}

class HourlyEmployee : Employee
{
    public HourlyEmployee(string firstName, string lastName,
                          int age, double payRate)
    : base(firstName, lastName, age, payRate)
    {}

    public override double CalculatePay(int hoursWorked)
    {
        Console.WriteLine("HourlyEmployee.CalculatePay");
        return 42; // bogus value
    }
}

class PolyApp
{
    protected Employee[] employees;

    protected void LoadEmployees()
    {
        Console.WriteLine("Loading employees...");

        // In a real application, we'd probably get this
        // from a database.
        employees = new Employee[3];

        employees[0] = new SalariedEmployee ("Amy", "Anderson", 28, 100);
        employees[1] = new ContractorEmployee ("John", "Maffei", 35, 110);
        employees[2] = new HourlyEmployee ("Lani", "Ota", 2000, 5);

        Console.WriteLine("\n");
    }


    protected void CalculatePay()
    {
        foreach(Employee emp in employees)
        {
            emp.CalculatePay(40);
        }
    }

    public static void Main()
    {
        PolyApp app = new PolyApp();

        app.LoadEmployees();
        app.CalculatePay();
    }
}
Compiling and running this application will yield the following results: -
c:\>PolyApp

Loading employees...

SalariedEmployee.CalculatePay
ContractorEmployee.CalculatePay
HourlyEmployee.CalculatePay
Note that polymorphism provides at least two benefits. First, it gives you the ability to group objects that have a common base class and treat them consistently. In the example above, although technically I have three different object types-SalariedEmployee, ContractorEmployee,and HourlyEmployee-I can treat them all as Employee objects because they all derive from the Employee base class. This is how I can stuff them in an array that is defined as an array of Employee objects. Because of polymorphism, when I call one of those object's methods, the runtime will ensure that the correct derived object's method is called.
The second advantage is the one I mentioned at the beginning of this section: old code can use new code. Notice that the PolyApp.CalculatePay method iterates through its member array of Employee objects. Because this method extracts the objects as implicitly upcasted Employee objects and the runtime's implementation of polymorphism ensures that the correct derived class's method is called, I can add other derived employee types to the system, insert them into the Employee object array, and all my code continues working without me having to change any of my original code! -

Defining Proper Inheritance

To address the all-important issue of proper inheritance, I'll use a term from Marshall Cline and Greg Lomow's C++ FAQs (Addison-Wesley, 1998): substitutability.Substitutability means that the advertised behavior of the derived class is substitutable for the base class. Think about that statement for a moment-it's the single most important rule you'll learn regarding building class hierarchies that work. (By "work," I mean stand the test of time and deliver on the OOP promises of reusable and extendable code.) -
Another rule of thumb to keep in mind when creating your class hierarchies is that a derived class should require no more and promise no less than its base class on any inherited interfaces. Not adhering to this rule breaks existing code. A class's interface is a binding contract between itself and programmers using the class. When a programmer has a reference to a derived class, the programmer can always treat that class as though it is the base class. This is called upcasting. In our example, if a client has a reference to a ContractEmployee object, it also has an implicit reference to that object's base, an Employee object. Therefore, by definition, ContractEmployee should always be able to function as its base class. Please note that this rule applies to base class functionality only. A derived class can choose to add behavior that is more restrictive regarding its requirements and promises as little as it wants. Therefore, this rule applies only to inherited members because existing code will have a contract with only those members.

Inheritance

Inheritance relates to the programmer's ability to specify that one class has a kind-of relationship with another class. Through inheritance, you can create (or derive) a new class that's based on an existing class. You can then modify the class the way that you want and create new objects of the derived type. This ability is the essence of creating a class hierarchy. Outside of abstraction, inheritance is the most significant part of a system's overall design. A derived class is the new class being created, and the base class is the one from which the new class is derived. The newly derived class inherits all the members of the base class, thereby enabling you to reuse previous work.
NOTE
In C#, the issue of which base class members are inherited is controlled by the access modifiers used to define the member . I'll get into that level of detail in Chapter 5. For the purposes of this discussion, you can assume that a derived class will inherit all its base class members.
As an example of when and how to use inheritance, let's look back at our EmployeeApp example. In that example, we would almost certainly have different types of employees, such as salaried, contractor, and hourly. While all of these Employee objects would have a similar interface, they would in many cases function differently internally. For instance, the CalculatePay method would work differently for a salaried employee than it would for a contractor. However, you want the same CalculatePay interface for your users regardless of employee type.
If you're new to object-oriented programming, you might be wondering, "Why do I even need objects here? Why can't I simply have an EMPLOYEE structure with an employee type member and then have a function similar to this?" -
Double CalculatePay(EMPLOYEE* pEmployee, int iHoursWorked)
{
    // Validate pEmployee pointer.

    if (pEmployee->type == SALARIED)
    {
        // Do W-2 employee processing.
    }
    else if (pEmployee->type == CONTRACTOR)
    {
        // Do 1099 processing.
    }
    else if (pEmployee-> == HOURLY)

    {
        // Do hourly processing.
    }
    else
    {
        // Do corp-to-corp processing.
    }

    // Return the value from one of the
    // compound statements above.
}
This code has a couple of problems. First, the success of the CalculatePay function is tightly linked to the EMPLOYEE structure. As I mentioned earlier, tight coupling like this is a problem because any modification to the EMPLOYEE structure will break this code. As an object-oriented programmer, the last thing you want to do is burden the users of your class with needing to know the intricate details of your class's design. That would be like a vending machine manufacturer requiring you to understand the internal mechanics of the vending machine before you can purchase a soda.
Second, the code doesn't promote reuse. Once you begin to see how inheritance promotes reuse, you realize that classes and objects are good things. In this case, you would simply define all the members for the base class that would function the same regardless of employee type. Any derived class would then inherit this functionality and change anything necessary. Here's how that would look in C#: -
class Employee
{
    public Employee(string firstName, string lastName,
                    int age, double payRate)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.payRate = payRate;
    }

    protected string firstName;
    protected string lastName;
    protected int age;
    protected double payRate;

    public double CalculatePay(int hoursWorked)
    {
        // Calculate pay here.
        return (payRate * (double)hoursWorked);
    }
}

class SalariedEmployee : Employee
{
    public string SocialSecurityNumber;

    public void CalculatePay (int hoursWorked)
    {
        // Calculate pay for a W-2 employee.
    }
}

class ContractEmployee : Employee
{
    public string FederalTaxId;

    public void CalculatePay (int hoursWorked)
    {
        // Calculate pay for a contract employee.
    }
}
Three features of the preceding example are worth noting: -
  • The base class, Employee, defines a string called EmployeeId that is inherited by both the SalariedEmployee and the ContractEmployee classes. The two derived classes do nothing to get this member-they inherit it automatically as a by-product of being derived from the Employee class.
  • Both derived classes implement their own versions of CalculatePay. However, you'll notice that they both inherited the interface, and although they changed the internals to suit their specific needs, the user's code remains the same.
  • Both derived classes added members to the members that were inherited from the base class. The SalariedEmployee class defines a SocialSecurityNumber string, and the ContractEmployee class includes a definition for a FederalTaxId member.
You've seen in this small example that inheritance enables you to reuse code by inheriting functionality from base classes. And it goes even further, allowing you to extend the class above and beyond that point by adding your own variables and methods.

Benefits of Good Abstraction

Designing the abstraction of your classes in a way most useful to the programmers using them is paramount in developing reusable software. If you can develop a stable, static interface that persists across implementation changes, less of your application will need modification over time. For example, think of our earlier payroll example code. In the case of an Employee object and the payroll functionality, only a few methods are going to be relevant, such as CalculatePay, GetAddress, and GetEmployeeType. If you know the problem domain of a payroll application, you can easily determine, to a fairly high degree, the methods that the users of this class are going to need. Having said that, if you combine intimate knowledge of the problem domain with forethought and planning in the design of this class, you can be reasonably assured that the majority of your interface for this class will remain unchanged despite future changes in the actual implementation of the class. After all, from a user's perspective, it's only an Employee class. From the user's vantage point, almost nothing should change from version to version.
The decoupling of user and implementation detail is what makes an entire system easier to understand and therefore easier to maintain. Contrast this with procedural languages such as C, in which each module needs to explicitly name and access the members of a given structure. In that case, each time the structure's members change, every single line of code referring to the structure must also change.

Designing Abstractions

An abstraction refers to how a given problem is represented in the program space. Programming languages themselves provide abstractions. Think about it like this: When was the last time you had to worry about the CPU's registers and stack? Even if you initially learned how to program in assembler, I'll bet it's been a long time since you had to worry about such low-level, machine specific details. The reason is that most programming languages abstract you from those details such that you can focus on the problem domain.
Object-oriented languages enable you to declare classes whose names and interfaces closely mimic real-world problem domain entities such that using theobjects have a more natural "feel" to them. The result of removing the elements not directly related to solving the problem at hand is that you're able to focus specifically on the problem and greater productivity. In fact, paraphrasing Bruce Eckel in Thinking in Java (Prentice Hall Computer Books, 2000), the ability to solve most problems will generally come down to the quality of the abstraction being used.
However, that's one level of abstraction. If you take that a step further, as a class developer you need to think in terms of how you can best design abstractions for your class's clients to allow the client to focus on the task at hand and not be mired in the details of how your class works. At this point, a good question might be, "How does a class's interface relate to abstraction?" The class's interface is the implementation of the abstraction.
I'll use a somewhat familiar analogy from programming courses to help crystallize these concepts: the internal workings of vending machines. The internals of a vending machine are actually quite involved. To fulfill its responsibilities, the machine has to accept cash and coinage, make change, and dispense the selected item. However, the vending machine has a finite set of functions it needs to express to its users. This interface is expressed through a coin slot, buttons for selecting the desired item, a lever to request change, a slot that holds the returned change, and a shoot to dispense the selected item. Each of these items represents a part of the machine's interface. Vending machines have, by and large, remained much the same since their invention. This is because despite the fact that the internals have changed as technology has evolved, the basic interface has not needed to change much. An integral part of designing a class's interface is having a deep enough understanding of the problem domain. This understanding will help you create an interface that gives the user access to the information and methods that they need yet insulates them from the internal workings of the class. You need to design an interface not only to solve today's problems but also to abstract sufficiently from the class's internals so that private class members can undergo unlimited changes without affecting existing code.
Another equally important aspect of designing a class's abstraction is keeping the client programmer in mind at all times. Imagine that you're writing a generic database engine. If you're a database guru, you might be perfectly comfortable with terms like cursors, commitment control, and tuples. However, most developers who haven't done a lot of database programming aren't going to be as knowledgeable about these terms. By using terms that are foreign to your class's clients, you have defeated the entire purpose of abstraction-to increase programmer productivity by representing the problem domain in natural terms.-
Another example of when to think about the client would be when determining which class members should be publicly accessible. Once again, a little knowledge of the problem domain and your class's clients should make this obvious. In our database engine example, you'd probably not want your clients to be able to directly access members representing internal data buffers. How these data buffers are defined could easily change in the future. In addition, because these buffers are critical to the overall operation of your engine, you'd want to make sure that they are modified through your methods only. That way you can be assured that any necessary precautions are taken.
NOTE
You might think that object-oriented systems are designed primarily to make it easier to create classes. Although this feature does provide for short-term productivity gains, long-term gains come only after realizing that OOP exists to make programming easier for the class's clients. Always consider the programmer who is going to instantiate or derive from the classes that you create when designing your classes.