Tuesday, July 26, 2011

At the July 20 meeting of the Great Lakes Area .NET User Group, Steve Bohlen presented Refactoring to a SOLID Foundation. In this presentation, Steve describes each of the 5 SOLID principles of object-oriented programming and refactors his code to meet these principles.

Here is that presentation.

OOP | Video
Tuesday, July 26, 2011 8:40:47 AM (Eastern Standard Time, UTC-05:00)
 Wednesday, December 09, 2009

Tomorrow evening - Thursday December 10 - I will speaking at the Flint .Net User Group. My topic is An Introduction to Object-Oriented Programming, a talk I've done twice before.

More information is available here.

This will probably be my final presentation for 2009.

Wednesday, December 09, 2009 2:20:07 AM (Eastern Standard Time, UTC-05:00)
 Thursday, August 20, 2009

I will be presenting "An Introduction To Object Oriented Programming" at the Findlay Area .Net User Group August 25 (next Tuesday) in Findlay, OH. For more information visit the group's web site at http://fanug.org

This is actually my second time speaking at this group but it's the first time since 2002, so they have probably forgotten.

If you are in Northwest Ohio or central west Ohio, please come.

Thursday, August 20, 2009 7:52:59 PM (Eastern Standard Time, UTC-05:00)
 Thursday, August 06, 2009

Back To Basics

This series of articles provides an introduction to the concepts used in Object Oriented Prorgramming and OOP code samples in C#.

Part 1: What is OOP?

Part 2: Understanding Objects

Part 3: Object Oriented concepts

 

Thursday, August 06, 2009 9:15:45 PM (Eastern Standard Time, UTC-05:00)

Back To Basics

In this section, we will discuss the key concepts important to Object Oriented Programming (OOP). An object-oriented system has the following characteristics

  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
  • Decoupling

Some systems (and some languages) don’t fully support all the above constructs and still refer to themselves as “object-oriented”. This is a matter of some debate, but it is my opinion that a language or system must implement each of the above concepts in some way in order to be considered object oriented.

Inheritance

Inheritance is the ability to create a class based on an existing class. In this model, the existing class is known as the “parent class”, or “base class” and the new class is known as the “child class” or “derived class”. By default, a child class will inherit all properties and methods of its parent class.

In C#, we inherit a class from a parent class by adding appending a colon and the name of the parent class to the child class definition, as in the following example:

public void ChildClass : ParentClass {} 

Marking a method as virtual in a parent class allows it to be overridden in a child class. This means that the method can be replaced in the child class with new code.

public virtual Int32 DoMath (Int32 num1, Int32 num2) 
{ 
  return num1 + num2; 
} 

We can then use the “override” keyword in the child class’s method to replace the code in the parent’s class method, as shown below

public override Int32 DoMath (Int32 num1, Int32 num2) 
{ 
  return num1 - num2; 
} 

It is possible to have multiple child classes that inherit from the same parent class. In some languages (but not in C#), it is also possible for a child class to inherit from multiple parent classes.

As a general rule, if I find myself writing a lot of conditional logic in a class’s methods – depending on how the object is created or the environment, the class runs one of several blocks of code – I will consider refactoring that class into a number of subclasses. Each class will inherit from a common parent class but the conditional logic is eliminated because each subclass contains only the code relevant to how it is created.

Interface Inheritance

Inheriting from an interface is similar to inheriting from a class, except the parent class does not contain any implementation, so each subclass contains all method code it needs to run. This is useful if a set of subclasses need to share the same public members but do not have any code in common. Interfaces also have the advantage that a single class can inherit from more than one interface.

Polymorphism

Earlier, we said that objects communicate by passing messages via their public interface.

Polymorphism is the ability for different objects to respond to the same messages in a different, but appropriate, way. In OOP, this is done using inheritance. Because a child class inherits properties, fields and methods from a parent class, we can have several different child classes sharing the same public members. Each of these classes would therefore accept the same message types. However, each base class may override some of the behavior of the base class and may do so in a way appropriate to itself.

For example, we may create a Vehicle class that has a method Drive() that accepts no parameters.

We can derive two child classes - Car and Airplane - from Vehicle and they will each inherit the Drive method. But driving a car is not like driving an airplane, so each of these methods would be overridden and the overridden child methods would be very different from one another. Calling the Car’s Drive method would cause the axels to turn and rotate the four wheels beneath the car. Calling the Airplane’s Drive method would explode jet fuel and propel the airplane through the sky at a high velocity.

This is an example of two objects (Car and Airplane) that accept the same message (Drive) and respond differently but appropriately.

The C# code for this set of classes would look similar to the following

public class Vehicle 
{ 
  public virtual void Drive() 
  { 
    Console.WriteLine(“Driving…”); 
  } 
} 

public class Automobile: Vehicle 
{ 
  public override void Drive() 
  { 
    Console.WriteLine(“Turn axel and wheels and tires…”); 
  } 
} 

public class Airplane: Vehicle 
{ 
  public override void Drive() 
  { 
    Console.WriteLine(“Explode jet fuel and propel through the air…”); 
  } 
} 

The picture below shows the hierarchy of classes that inherit from a single parent class.

Abstraction

Abstraction is the process of simplifying an object or system by focusing only on those parts of the system relevant to the current problem. In OOP, abstraction is typically implemented using encapsulation.

Encapsulation

Encapsulation hides implementation details of an object from that outside world. Again, this goes back to our goal of decreasing complexity. We don’t need to understand all the workings of an object in order to use it. Returning to our Automobile example, in order to start a car, I need only know to put the key into the ignition and turn it for a short time. A lot happens inside the car (gasoline is injected, battery is engaged, sparks fly, gas explodes) but I don’t need to the details of any of that in order to start the car. In fact, it’s easier for me to focus on starting the car if I ignore the other things going on within the automobile.

Decoupling

Finally, decoupling is a key point of object oriented programming that simplifies a system. In a decoupled system, the dependencies between objects are minimized. Encapsulation helps with this because external objects cannot change the internal attributes of an object if they cannot access it.

However, the responsibility for decoupling ultimately rests with the developer. Use messages to communicate between objects and maintain as little state as possible. Expose only those attributes needed by others and avoid coding side effects in your object’s methods.

In my experience, decoupling is the OOP concept that is ignored the most by people trying to build object oriented systems.

Summary

As we stated in part 1 of this series, the goal of Object Oriented Programming is to manage complexity. We do this by modeling our application as many people see their real world systems – as a set of loosely coupled objects that interact with one another. This helps us to split a complex problem into a number of more manageable objects. It also allows us to simplify the management of those objects by encapsulating complexity, maximizing flexibility through inheritance, and keeping the objects independent of one another.


Thanks to Chris Woodruff, who contributed to this article.

Thursday, August 06, 2009 6:53:29 AM (Eastern Standard Time, UTC-05:00)
 Wednesday, August 05, 2009

Back To Basics

Key Object Concepts

Objects are essentially a collection of structured data stored in memory. An object is based on a class that defines how to create an object.

In this section, I will describe the following concepts.

  • Classes
  • Class members
    • Properties and Fields
    • Methods
    • Events
  • Instances
  • Static Types
  • Interfaces
  • Message Passing

Because all these terms are interrelated, it is difficult to discuss one without mentioning the others. So be patient if I mention a term before I define it – I will get to the definition shortly.

Classes

A class is a definition for an object. It describes the attributes, such as properties, fields and methods (more on this later) of an object. It may also set default values and implementations for these attributes. Think of a class as a blueprint we can use to help us build an object. Generally, we work with classes only at design-time, defining the attributes appropriate for that class. In most cases, we do not work directly with classes while a program is running.

In C#, a class is defined with the following code

public class <CLASSNAME>{} 

So to create a class named MyClass, we use the declaration:

public class MyClass{} 

Public Members

A class (and an object) exposes a finite set of publicly-exposed members. Members are methods, properties and fields (defined below). This public interface is how you interact with an object. An object may be capable of far more than what it exposes by its public interface, but these other capabilities are not seen directly by the outside world. Keeping object interfaces simple is one way that an object can help simplify a complex system.

Properties and Fields

Properties and fields describe static data associated with a class. In C#, fields are implemented with the following syntax:

public <DATETYPE> <FIELDNAME> = ,VALUE; 

as in the sample code below:

public string Color = “White”; 

You can access this property with syntax like the following

obj.Color = “Black”; 
string thisColor = obj.Color; 

A property is similar to a field, but a property provides a “Getter” and “Setter” – methods that run when you attempt access the value of a property. This allows a developer to add code that will automatically run whenever a field’s value is retrieved or assigned. This code might perform validation or calculate a value on the fly. The C# syntax for fields looks like the following

private string _color; 
public string Color 
  { 
  get 
    { 
    return _color: 
    } 
  set 
    { 
    _color = value; 
    } 
  }

 Beginning with C# 3.0, this syntax can be shortened to

public string Color{get; set; }

The syntax for working with a property is identical to that for working with a field.

Methods

A method is a discrete section of code that is associated with a class and therefore with an object. Some methods return a value; others just run code and return nothing. In C#, sample syntax for a method that returns nothing is shown below.

public void WriteSomething(string messageToWrite) 
{ 
Console.WriteLine (messageToWrite); 
}

To return a value, in place of “void” in the method declaration, we specify the data type returned. Below is an example. 

public Int32 AddNumber(Int32 num1, Int32 num2) 
{ 
Int32 sumOfNumbers = num1 + num2; 
return sumOfNumbers; 
}

We can call a method of an object with syntax like the following

obj1.WriteSomething(“Hello World”); 
Int32 sum = obj1.AddNumbers(2,2);

Instances

So far, we’ve been talking about objects without defining what an object is. An object is an instance of a class – it represents a specific set of data.

We said before that a class is like a blueprint. Think of an object as the house, machine or other device built from that blueprint. Methods, properties and fields defined in a class become methods, properties and fields in any object based on that class.

It is possible to produce more than one house from the same blueprint. Similarly, it is possible to create multiple objects from the same class.

To instantiate an object in C#, we use the following syntax

<OBJECTTYPE> <OBJECTNAME> = new <OBJECTTYPE>();

In the Methods sample above, assume the methods were defined in a class named MyMathClass. Before calling the object's methods, we would first instantiate the object like this:

MyMathClass obj1 = new MyMathClass();

Static Types

It is possible to instantiate a class without explicitly creating an instance of that class. You can do this if the class is defined as “static”, as in the following example.

It is possible to instantiate a class without explicitly creating an instance of that class. You can do this if the class is defined as “static”, as in the following example.

public static class Math
{
  public static Int32 MultiplyNumbers(Int32 num1, Int32 num2)
  {
    return num1 * num2;
  }
}

Call this method with the following syntax

Int32 product = Math.MultiplyNumbers(2, 4);

Notice that we did not need to explicitly instantiate an object of type Math.  For static classes, the .Net framework takes care of this for us.

Constructors

A constructor is a special type of method that runs when an object is first created. This is a good place to put initialization code for your object. In C#, a constructor is written by creating a method with the same name as the class.

public class MyClass 
{
   public MyClass()
   {
   // Initialization code goes here
   }
}

You may create constructors that accept parameters, such as in the following C# code

public class MyClass 
{
   public MyClass(string x, string y)
   {
      // Initialization code goes here
   }
}

Events

An event is a notification by an object that something has happened. This something might be user input, such as a mouse-click on a form or it can be something less tangible, such as a customer exceeding his credit limit. Other objects may or may not respond to these events. Generally the object raising an event does not know how it will be consumed.

Interfaces

An interface looks like a class in that it can have properties, fields and methods. The difference is that the properties and methods contain no implementation code. Interfaces are used only to define the public members of a class. A class implementing an interface inherits all the public members of that interface and it is up to the class to provide implementation.

Below is sample syntax for creating an interface

interace IPerson 
{ 
  string FirstName {get; set;} 
  string LastName {get; set;} 
  Order GetAllOrders(); 
}

Use code like the following to create a class that implements an interface

class Customer: IPerson 
{ 
  public string FirstName {get; set;} 
  public string LastName {get; set;} 
  public Order GetAllOrders() 
  { 
    Order ord = new Order(); 
    // Code omitted for brevity 
    return ord; 
  } 
} 

Message Passing

Objects communicate by passing messages. These messages can be primitive data types, such as strings and integers; they can be XML; or they can be other objects.  Generally speaking objects expose public members to accept these messages. This helps to simplify the communication between objects.

In this section, we learned the basics of objects, their definitions, their members and how to work with them. In the next section, we’ll introduce Object Oriented Programming constructs and how these concepts are implemented using objects.


Thanks to Chris Woodruff, who contributed to this article.

Tuesday, August 04, 2009 11:36:25 PM (Eastern Standard Time, UTC-05:00)
 Tuesday, August 04, 2009

Back To Basics

What is OOP?

Most people think of their business systems in terms of the interactions of people, institutions and systems. When describing a system, they often speak in terms of these interactions between entities. For example, they may describe how a customer communicates order information to a salesperson that inputs this information into an Order Processing program. Describing entities and defining how those entities interact with one another maps very well to Object Oriented Programming (OOP). OOP is a programming paradigm that focuses on the objects in a software system and the messages passed between those objects.

Object Oriented Programming is not a new concept. The ideas behind it were first published in the 1960s and the SmallTalk language, developed in the 1970s, formalized many of the programming constructs used in this paradigm. However, OOP gained popularity in the 1990’s with the increased use of the C++ and the last ten years have seen an explosion in object-oriented languages C#, Visual Basic.Net and Java.

In earlier programming models, a program was viewed as a set of methods or subroutines. A main method would call one or more subroutines that might each in turn call other subroutines. Each subroutine would complete its task and return control to the method that called it. Using this approach, developers viewed their programs as a set of tasks. These tasks became central to their application design.

Managing Complex Systems

It was difficult to manage complexity in this task-oriented approach to programming.

For example, one couldn’t be certain that a subroutine would not substantially change variables, files and other parts of the environment. The only way to know for sure was to examine that subroutine in detail to learn how it worked. In fact, you would need to also examine any subroutines called by that subroutine, to verify that they didn’t cause any unexpected side effects.

Another complexity arises because there tends to be a tight coupling between the subroutines. Changes to a subroutine often require changes to any routine that called it, making maintenance difficult.

Often in such systems, you find code duplicated in multiple places. Making a fundamental change to how a rule is implemented requires changing code several times – another maintenance difficulty that adds to complexity.

The Development process itself adds to the complexity of writing software. On most projects, we need to consider how to divide development tasks among team members; merge this code together; manage code deployment; test code modules independently and together; deploy updates to our application; and fix errors as they are found. The entire process can be quite complex, particularly if all our modules are tightly bound together.

Finally, we cannot ignore the fact that many of the problems we are trying to solve are complex. This complexity is often our motivation to automate these problems in the first place. Anything we can do to mitigate that complexity – such as splitting a problem into manageable components – will assist us in building a solution.

OOP attempts to address these challenges by focusing on objects instead of tasks. The whole goal of OOP is to manage complexity. This is done by splitting a complex system into manageable, independent pieces and only exposing enough of each piece to allow other objects to work with it. Much of the complexity of the object can be hidden from the outside world, making the system as a whole easier to understand.

The following basic principles help to accomplish OOP’s goal of managing complexity.

  • Inheritance
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Decoupling

The above concepts are interrelated in that some are used to accomplish others. In a later article, we will dive into more detail about each.

Before we can do that, it’s important to understand the basics of objects before you can grasp Object Oriented Programming.

Next: Intro to OOP, Part 2: Understanding Objects 


Thanks to Chris Woodruff, who contributed to this article.

Tuesday, August 04, 2009 8:23:52 AM (Eastern Standard Time, UTC-05:00)