My struggles in understanding and learning about Object Oriented design, and the tools and knowledge I've taken from them.

Saturday, October 25, 2008

.NET Delegates Part 1

One of the things I've struggled with in OOP is how to take concepts I learned in college, post-college learnings in OOP, and use them in a way that creates good code. I really believe that there is no perfect way to do code, because there are nearly an infinite amount of ways of solving the same problem; however, I do believe that there is a difference between good code and bad code. Furthermore, I believe that bad code can be created, regardless of whether or not proper elements of coding have been followed. I think that good code can be described as having the following characteristics:

1. Extensible - The code is capable of being expanded for future growth.
2. Properly Engineered - Code should match the job. Overengineering doesn't help anyone if the project doesn't call for it. Overly verbose code ends up destroying agility, which hinders the programmer's ability to solve a problem quickly.
3. Efficiency - The fastest processing code with the smallest amount of lines of code is the name of the game. It's the programmer's dilemma, and it's one of the reasons I love programming.

There's probably more nuances in good code, but I think that the above 3 characteristics describe good code, and lack of the above characteristics describe bad code.

Delegates are one concept in code that gets at all 3 of the above characteristics. A delegate is not all that easy to explain, but I'll do my best, given my experience with them, and the value I find in them, at a practical level.

A delegate can do many things, but the first thing that all the tutorials talk about with the application of delegates is to "Encapsulate a method." In a nutshell, that means delegates provide another form of abstraction. Below is an example:


delegate void GenericMessage(string message);

class MyClass
{
    ///Notice that this method is type void
    ///just like the delegate. Also has the
    ///same parameter types as the delegate
    private void realMessageWriter(string theMessage)
    {
        Console.WriteLine(message);
    }

    ///The entry method for this class
    public void Entry()
    {
        ///Notice variable _Message is of type
        ///GenericMessage - which is the delegate
        ///Similar functionality could be done
        ///with an abstract class or an interface
        GenericMessage _Message = realMessageWriter;
        _Message("Hey dude");
    }
}

This is a very simple code example, but I think it demonstrates the point, that delegates provide a way to hide a method, as long as the method shares a similar "fingerprint" as the delegate. In the above example, the method that is being hidden (realMessageWriter()) is of type VOID, and accepts a string parameter.

This is the foundation of a delegate. There is a curve ball that delegates present, when you take into account that they are the foundation for events, which could allow you to fire code in the event that something happens without proactively coding for that scenario after each iteration of some action, but I think that falls into Delegates Part 2.

Tuesday, October 14, 2008

Layers of Programming 2 - Data Access Layer

I love the data access layer. That may sound a little weird, but it really is my favorite layer. The reason for this is simple: with the data access layer, you set it, and forget it. The data access layer, if done right, I think, is the smallest layer, in terms of lines of code. My methods in the data access layer tend to get pretty big, and encompassing, but there's often only a few methods that I ever need to put into the data access layer.

Maybe it's just me, but being able to reuse a method or a class hundreds of times, and have it provide a wide array of functionality really epitomizes what programming is all about. I just love it whenever I can work smart, instead of working hard.

So, let me throw out an example of a data access layer I've used in the past.

It's a lot of code, so I'll break it up into logically separated sections:

public class DatabaseConnectionParameters
{
   private const string _ConfigurationFile = "config.ini";
   FileIO.FileIO _File = new FileIO.FileIO();

   private string _Server, _Database, _User, _Password;
   public string Server
   {
      get
      {
         _Server = _File.GetSetting(_ConfigurationFile, "Server");
         return _Server;
      }
      set { _Server = value; }
   }

   public string Database
   {
      get
      {
         _Database = _File.GetSetting(_ConfigurationFile, "Database");
         return _Database;
      }
      set { _Database = value; }
   }

   public string User
   {
      get
      {
         _User = _File.GetSetting(_ConfigurationFile, "User");
         return _User;
      }
      set { _User = value; }
   }

   public string Password
   {
      get
      {
         _Password = _File.GetSetting(_ConfigurationFile, "Password");
         return _Password;
      }
      set { _Password = value; }
   }
   
}

The above is basically a parameter storage class. It has access to a class called FileIO, that I use to get settings from a config file. I'll omit that class here, because it's fairly simple, yet space-consuming, and I'm kind of lazy :). But overall, the above class doesn't really do anything, except act as a more organized way for me to store settings.

Next comes the actual Data access layer class. In this class, I do what anyone would expect me to do, as far as incorporating .Net libraries. I use SqlConnection, SqlDataReader, and SqlCommand to allow me to interact with my database. I also instantiate my FileIO class again, to allow me to log events (notice that my FileIO, at least in this application serves 2 similar purposes - it reads from a text file to get settings and it writes to text files to log events. If one were really to follow a single responsibility principle, one may separate these two things (reading and writing). I happen to think that is overboard, but I'm just "some guy."

My main method in DAL is ProcessStoredProcedure(). Basically, all it does is:
1. Calls handleConnectionState() to ensure that the connection is not currently open to the database. This is a strategy I use, but not necessarily industry standard. There are a lot of strategies in OLTP datab ases that allow multiple things going on at the same time (perhaps with threads, or other neat-sounding things), but I don't need to be that extensible with my apps, and single database transactions at once is not necessarily a "kiss of death" when it comes to creating a good application.
2. Opens a connection to the database
3. Call a stored procedure
4. Attach parameters to the stored procedure based on the contents of the ArrayList I pass to it
5. Execute a DataReader, and attach it to a Datatable, and return it

public class DAL
{
   SqlConnection _Connection;
   SqlDataReader _Reader;
   SqlCommand _Command;
   DatabaseConnectionParameters _Parameters = new DatabaseConnectionParameters();
   FileIO.FileIO _File = new FileIO.FileIO();

   public DAL()
   {
      _Connection = new
         SqlConnection("Server=" + _Parameters.Server + ";" +
                   "DataBase=" + _Parameters.Database + ";" +
                   "uid=" + _Parameters.User + ";" +
                   "pwd=" + _Parameters.Password);
   }

   public DataTable ProcessStoredProcedure(string procedureName, ArrayList parameters)
   {
      DataTable assembledProcedureResults = new DataTable();
               
      if (arrayListCountIsEven(parameters))
      {            
         handleConnectionState();
         _Connection.Open();

         _Command = new SqlCommand(procedureName, _Connection);
         _Command.CommandType = CommandType.StoredProcedure;
         assembleStoredProcedureParameters(parameters);
         _Reader = _Command.ExecuteReader();
         assembledProcedureResults.Load(_Reader);
         _Connection.Close();
         _Command = null;
         return assembledProcedureResults;
      }
      else
      {
         _File.LogEvent(true, "Encountered an unexpected count of parameters in ProcessStoredProcedure()");
         return null;
      }
   }

   private void assembleStoredProcedureParameters(ArrayList parameters)
   {
      if (parameters != null)
      {
         int counter = 0;
         string parameterName = "";
         string parameterValue = "";
         foreach (string item in parameters)
         {
            if (counter == 0)
               parameterName = item;
            else
               parameterValue = item;
            counter++;
            if (counter > 1)
            {
               counter = 0;
               _Command.Parameters.Add(new SqlParameter(parameterName, parameterValue));
            }
         }
      }
      
   }

   private void handleConnectionState()
   {
      if (_Connection.State != ConnectionState.Closed)
      {
         try
         {
            _Connection.Close();
         }
         catch
         {
            try
            {
               _File.LogEvent(true, "Encountered error closing unexpected open connection. Retrying");
               _Connection.Close();
            }
            catch
            {
               _File.LogEvent(true, "Encountered error closing unexpected open connection. Unable to recover");
            }
         }
      }
   }

   private bool arrayListCountIsEven(ArrayList list)
   {
      if (list == null)
      {
         return true;
      }
      else if (list.Count == 0 || list.Count % 2 == 0 )
      {
         return true;
      }
      else
      {
         return false;
      }
   }

}

What this allows me to do is separate any database activity with any application logic or user interface stuff. This is the way I like to do things, because it keeps me closer to "Single Responsibility" and it ends up making for better looking code.

Encapsulation

Coming from PHP, one of my struggles in learning OOP was figuring out what good Encapsulation did. I mean, if you make everything publicly accessible from anywhere, then you can accomplish everything you want.

That is a brute force mentality, and doesn't work if you need to maintain a large amount of code, or you need to work with other people.

There are a few reasons for this:
1. Some code never needs to be accessed outside of the class.
2. Some code never should be accessed outside of the class
3. If you're working with a lot of code and a lot of classes, you don't want to have to remember which method (or property) is the most important, from outside of the class. Some classes may have only 1 or 2 methods that need to be accessed from outside of the class, so why would you publicly expose all the other methods that you don't care about?

Consider a common example. Humans speak. Human is the noun, speak is the verb, therefore Human is the class, and speak is the method. A lot of the body systems of a human are required to do something in order for the Human to speak. The person or object a Human is speaking to does not care about the synapses that need to fire in the brain for the Human to speak, nor does the other object care about what the lungs need to do, what the vocal chords need to do, or what the mouth needs to do. Therefore, it would make sense to publicly expose Human's Speak() method, and make those other things private. That is encapsulation in a nutshell.

The concept of encapsulation is particularly important in a development environment like .NET's, because .NET's development environment provides a lot of functionality to make life easier, such as dropdown boxes that appear (I believe this feature is called "Completion List"), to make it easier and faster for you to select the methods or properties available from the class. If you get the dropdown list of all the availble members of an object, you don't want to have to scroll through 20 pages of irrelevant methods in order to find the right method.

I think overall, the main value of encapsulation comes with its ability to help you organize your apps, and to provide an extra layer of safety, in that if you only allow a very small subset of your code to accomplish certain functionality, then you reduce the risk (and the detective work afterwards) of non-authorized code to perform tasks it shouldn't be performing.

Digg It

Monday, October 13, 2008

Layers of Programming (Part 1)

One of the struggles I've had in OOP is figuring out how to separate the user interface from the data access.

**EDIT: I've posted a better blog on this concept. It can be found here. Check it out if you're interested.

When I was coding on a fairly regular basis in PHP, my user interface and data access layer, along with the business logic, were all over the place.

Now, if you're just doing brute-force programming, by definition, it doesn't really matter how you solve problems with programming, as long as you solve the problem. Note, if you have to maintain the code, brute force programming is basically an invitation to the requirement of redoing work you've already done. If anyone else has to maintain your code, their likely conclusion will be that they'll have to replace your code.

But if you have to program at a somewhat more professional level, or if you're a code-junkie like me, you're going to have to get proper separation of various layers of your application.

I've found that there are a number of ways to solve this problem. One way is to simply follow the axiom that one class does one thing (also referred to as the "Single Responsibility Principle"). There are also pre-written design patterns like MVC (Model View Controller) that solve these problems.

I'm a more literal type of guy. I've always found MVC to be overly complicated for what I want to do.

My solution to the problem of layer separation is to simply focus my classes to fit into one of three layers: user interface, business logic, and data access layer.

I'll speak to each of these layers in subsequent posts, but I'll give a few principles that each of these layers follow:

Data Access Layer: Anytime the application has to leave itself to fetch data from some source, whether it be a text file, XML file, or database, the business logic layer asks for the data, in some way, shape or form, from the Data Access Layer. Certainly, if I did happen to have data access from multiple sources, I would separate these into separate classes, perhaps using inheritance or abstraction.
One of the other principles I follow is to make the Data Access Layer as simple as possible, often reusing the same 1, 2, or 3 methods hundreds of times.

Business Logic Layer: Far and away, the most bloated layer. And it makes sense that this is so. The data access layer, and in a lot of ways, the user interface layer, are often interchangable throughout applications, if you build the business logic layer correct, and are consistent in your coding style. But Business Logic really defines the application, and may be comprised of anywhere from 1 to 1000s of classes, depending on the complexity of your application. One nice thing though is that, if the data coming back from the data access layer is in consistent, predictable format, you can take opportunities to reuse code to provide a large range of functionality. It really comes down to well-thought-out design.

User Interface Layer: I've been trying to come up with deas of how to minimize the user interface layer, as far as number of lines of code required to make it happen, and I keep coming back to the idea of having configurable forms, and the storage of those forms stored in a database. This way, you have an extensible (low effort to make changes and advance the layer) layer, that is ready to deal with all the different views you want to present to the end-user.

The ideas of how to separate these layers, and the eloquence of the solutions really come down to style. I'm ok with not having the most elegant solution in this respect, because it works, and it keeps my code maintainable, and easy to read.

Digg It

Sunday, October 12, 2008

Abstraction, Abstract Classes, and Interfaces

One of my struggles in figuring out OOP has been getting a grasp on the concept of ABSTRACTION. ABSTRACTION is a fundamental concept that differentiates OOP from procedural programming, because it cannot be used if there is no concept of classes and objects.

It's been my experience that there are 2 main ways of implementing abstraction in OOP: ABSTRACT CLASSES and INTERFACES.

Each of the above has their own advantages and implementations, and they can certainly overlap, but I would say that the chief difference between ABSTRACT CLASSES and INTERFACES is that, by definition, when a class inherits from an ABSTRACT CLASS, the inheriting class has a "IS-A" relationship with the ABSTRACT CLASS, and it also has a "CAN-DO" relationship with the ABSTRACT CLASS.

A class that implements an INTERFACE simply has a "CAN-DO" relationship with the interface it is implementing, in that the methods in the class that implements an INTERFACE must correspond to the methods defined in the interface (same name, same parameters, etc).
Another way of describing the difference between an ABSTRACT CLASS and an INTERFACE is that an ABSTRACT CLASS could possibly have an implementation, but an INTERFACE does not (by the way, when I say that something could or could not have an implementation, what I mean is that it can or cannot be instantiated as an object).

I'll give a code example, so I can describe these differences better. Remember that an ABSTRACT CLASS and an INTERFACE can be interchangable at times, so I'll give an example where this is true. Consider the oldie-but-goodie example of a shape. The concept of a shape is abstract, in that a shape could mean many things (does the shape have sides? How many sides? What is the area of the shape? How does the shape get drawn?). Consider the following:

abstract class Shape
{
   ///Notice I'm not implementing anything
   ///with this method. It's basically a
   ///shopping list item
   public abstract void Draw();
}

///The class Square inherits from
///the abstract class Shape
public class Square: Shape
{
   ///Notice I use the keyword override
   ///I'm overriding the non-implemented
   ///method Draw() that is inherited
   ///from the Shape abstract class
   public override void Draw()
   {
      ///Do stuff that draws the square
   }
}

Notice how Square inherits from the Shape class. The effect of this is that the Shape class gives some structure to the concept of actual shapes in your application. There may be a dozen or so classes that implement Shape (Square, Circle, Rectangle, Triangle, etc). The value in doing this falls into a concept that I have come to find very important in OOP: one class shouldn't know too much about the world.

You may look at that statement and think that I have an overly-sentimental attachment to code, but I think it's very important, especially if you'll be working on the same code base for a long time. One class should serve 1-and-only-1 purpose. If a class starts to do too many things, you lose the versatility that OOP affords, and it simply becomes procedural. More on fundamental concepts like these later.

INTERFACES
INTERFACES are a little different than ABSTRACT CLASSES, in that INTERFACES do not have an implementation. In the above example, the abstract class was not necessarily an implementable class (because the only method in it was abstract), but that is not always necessarily true that an abstract class can have no implementation. INTERFACES never have an implementation, and that has advantages and disadvantages. The main disadvantage is that it is a little slower than an ABSTRACT CLASS. One advantage is that it's a little purer of an abstraction. When the rubber meets the road, ABSTRACT CLASSES and INTERFACES are used in combination to get the best of both worlds.

An INTERFACE would have just about the same syntax as the above example, except for the keywords:


Interface IShape
{
   ///Notice I'm not implementing anything
   ///with this method. It's basically a
   ///shopping list item
   public abstract void Draw();
}

///The class Square inherits from
///the Interface Shape
public class Square: IShape
{
   ///Notice I don't use the keyword
   /// override. I don't have to
   ///override, because interfaces
   ///have no implementation to
   ///override
   ///In this definition, interfaces
   ///simply provide a "contract"
   ///between classes that implement them
   public void Draw()
   {
      ///Do stuff that draws the square
   }
}

I'll have to be honest, in my own experience, I tend to use interfaces more than abstract classes, simply because I feel more comfortable with them, but both interfaces and abstract classes provide functionality that is vitally important:

1. They create a contract between classes that implement them. This is important if there are multiple people working on different parts of the application, and a bridge needs to be built between different people's work. (BTW, I tend to use the phrase "shopping list" to describe these non-implementable pieces. Because it really is just a list of things a class "CAN-DO.")
2. It creates the ability to reuse a lot of code, because you can take advantage of the "is" keyword in many OOP languages, such as C#, and this falls into another axiom in programming: Reusability is important. The more you can reuse a method, the less likely it is to break code down the line.

Speaking of #2 above, consider the following example:

public void Draw(IShape shape)
{
   ///Notice that I use the "is"
   ///keyword here. I've been
   ///told this is reminiscent
   ///of a "factory" design pattern
   ///in that I can use if or switch
   ///statements to add bunches
   ///of logic to this method to
   ///make it very reusable
   if(shape is Circle)
   {
      ///Do stuff from Circle class
      ///to draw the circle
   }
   
   else if(shape is Square)
   {
      ///Do stuff from Square class
      ///to draw the square
   }
}

I find myself doing the above type of thing a lot, and I'm quite ok with that, because I just pass in some object that implements the specified interface (in this case, IShape), and let the method do the processing for me.

Digg It

Friday, October 10, 2008

OOP Architecture

OOP is necessary. If you have any aspirations of doing programming as a career, or in any sort of non-amateur way, especially in a way that interacts with other programmers, you must know OOP.

One of my struggles in OOP has been getting past the technical concepts, and figuring out how to apply OOP to make an application OOP.

One of the conclusions I came to after years (literally) of working to figure this stuff out, is that an application is not OOP until it has multiple classes/objects that interact with one another.

So, consider an example of a human who has a dog. Suppose one of the things that the dog does is get the paper for its human. There are things to consider, as far as what makes the human inclined to have a paper, and what makes the dog inclined to fetch the paper. Then there's the question of how those 2 things interact to create a situation where the dog fetches the paper for the human.

So, I'll throw a few things out there, as far as what I would expect could influence a dog's willingness to get a paper for its human:

1. The human wants to read a paper
2. The dog's life contentment is high (it gets fed, it gets petted, etc)
3. There is some sort of incentive to the dog (for instance, the dog gets a treat if it gets the paper)

There are really a lot of other things that could influence these things, but I won't get into them, because I don't want to create a 10,000 line application. But just to kind of keep them in mind, we may have also considered things like how far the dog had to travel to get the paper, whether or not there are distractions the dog has that would limit its willingness to get the paper, the thickness of the paper, and the current mood of the dog that may trump the dog's overall life contentment, or even immediate incentives for the dog.

So, let's build the classes. As I see it, there are 2 nouns (dog and human), and therefore, a need for 2 classes. There are the above properties we need to consider (human's want to read paper, dog's life contentment, dog's incentive). Then there are a few actions that would need to occur in order to mechanize the dog getting the human a paper. Let's iterate them:

1. Human asks dog for the paper
2. Dog fetches the paper
3. Dog brings paper to human
4. Human gives dog a treat

Each of the above 4 things are actions, and therefore would constitute our methods. The methods interact with the above properties to affect the likelihood that each of these methods would fire off another method, or influence the value of some property.

So, let's write dog, first:

class Dog
{
    //Notice that _contentmentInLife is private, and it's
    //accessed via the public property ContentmentInLife
    private int _contentmentInLife;
    public int ContentmentInLife
    {
       get { return _contentmentInLife; }
       set { _contentmentInLife = value; }
    }

    //This is the incentive the dog has to fetch the paper
    //It is true or false (boolean), so if it is true,
    //the dog has incentive
    //to get the human a paper
    private bool _currentIncentive;
    public bool CurrentIncentive
    {
       get { return _currentIncentive; }
       set { _currentIncentive = value; }
    }

    ///This is the publicly exposed method that
    ///allows outside classes to get an object of Dog
    ///To bring a paper

    public void FetchPaper()
    {
       if(this.CurrentIncentive && this.ContentmentInLife > 3)
       {
           Console.WriteLine("The dog fetches the paper");
           bringPaperToHuman();
       }
    }

    ///bringPaperToHuman() is not accessible from outside of
    ///the Dog class - this is an example of encapsulation
    ///This is called by the publicly exposed
    ///method FetchPaper(),
    ///FetchPaper() determines whether or not to call
    ///bringPaperToHuman()
    ///based on the values of CurrentIncentive and     ///ContentmentInLife
    private void bringPaperToHuman()
    {
       Console.WriteLine("The dog brings the paper to the human");
    }

    //When the dog receives a treat, its contentment in life increases
    public void ReceiveTreat()
    {
         this.ContentmentInLife++;
    }
}

Notice that the above example is quite simple, but I think it gives a good example of what classes end up looking like when they're done.

On to human:

class Human
{
    private bool _wantsToReadPaper;
    public bool WantsToReadPaper
    {
       get { return _wantsToReadPaper; }
       set
       {
       _wantsToReadPaper = value;

       }
    }

    private bool _hasPaper;
    public bool HasPaper
    {
       get { return _hasPaper; }
       set { _hasPaper = value; }
    }

    //Note that this returns true if the human wants to read the paper
    //and does not already have the paper
    public bool IncentivizeDog()
    {
       ///If the human wants a paper, and
       ///doesn't already have a paper
       ///then human will proceed to ask the
       ///dog for a paper
       if(this.WantsToReadPaper && !this.HasPaper)
       {
           Console.WriteLine("Human says: Dog, give me a paper, and I'll give you a treat");
           return true;
       }
       //If the human either already has a paper, or they don't want
       //the paper, return false;
       else
       {
         Console.WriteLine("Human says: I don't want a paper, dog");
         return false;
       }
    }

    //Another boolean, because they're a good tool to manage
    //Interaction between classes - as demonstrated below
    //Only give dog a treat if human has paper
    public bool GiveDogATreat()
    {
       if(this.HasPaper)
       {
         Console.WriteLine("Here you go, dog. Here's a treat");
         return true;
       }
       else
       {
         Console.WriteLine("No treat for you!");
         return false;
       }
    }
}

The next step in the process, once we have the "architecture" is to instantiate the objects and have them interact:

class RealLife
{
    //StartLife simply starts the process of instantiation and usage
    public void StartLife()
    {
       //Instantiate our dog and human
       Dog Fido = new Dog();
       Human Tim = new Human();

       //Set base properties
       Fido.ContentmentInLife = 4;
       Tim.HasPaper = false;
       Tim.WantsToReadPaper = true;

       if(Tim.IncentivizeDog())
       {
         Fido.CurrentIncentive = true;
         Fido.FetchPaper();
         Tim.GiveDogATreat();
         Fido.ReceiveTreat();    
       }    
    }
}

The RealLife class makes this application come to life. It sets the preconditions of how happy the dog is, whether the human wants a paper, and then it proceeds to have the human incentivize Fido, and then tells Fido to fetch the paper, has Tim give Fido a treat, and has Fido receive a treat.

One thing you may notice about the RealLife class is that it is facilitating, and actually controlling the interaction between Human and Dog. In fact, Human and Dog have absolutely no knowlege of one another, and at present, have no capacity to know anything about one another. This is one strategy of getting classes to communicate with each other.

One of my struggles in learning OOP is figuring out the best way to get classes to communicate with one another, and in my quest to write the best code possible, I've come across all kinds of strategies to solve this problem, and it speaks to concepts like COUPLING, COHESION, and is often solved by implementing strategies like DESIGN PATTERNS.

Digg It

Thursday, October 9, 2008

Object Oriented Programming (Part 2)

In part 1 of the Object Oriented Programming post, I talked about CLASSES, OBJECTS, METHODS, and PROPERTIES. There's another side of object oriented programming (hereafter referred to as OOP), and it speaks directly to concepts in OOP, versus implementations of it. Specifically, the technical concepts that make up OOP are ABSTRACTION, ENCAPSULATION, and POLYMORPHISM. One could probably include a couple more concepts to make up OOP, but I think the above three, along with the implementation concepts of CLASSES, OBJECTS (and the instantiation of them), METHODS, and PROPERTIES, adequately describe OOP.

This post will discuss ABSTRACTION, ENCAPSULATION, and POLYMORPHISM at an overview level.

ABSTRACTION
ABSTRACTION
speaks directly to the concept of "generic." Anything that is an abstract concept of something more specific is an abstraction. For instance, a shape is an abstract idea (notice a shape is also a noun, and therefore a candidate of a CLASS), and a shape can be implemented more specifically as a circle, square, triangle, etc. Similarly, a Mammal is generally an abstract concept, and a Human, Dog, Cat, or Whale is more specific.

In my experience, ABSTRACTION is implemented in 1 of 2 ways: either an ABSTRACT CLASS or INTERFACE. I won't really go into code examples right now, but think of both ABSTRACT CLASSES and INTERFACES as shopping lists (some people refer to them as contracts between classes). When a class is abstract, it looks an awful lot like an interface, where there is no real instantiation of the thing itself, but rather, other classes use them to have a framework from which to work. More on ABSTRACTION in the next post.

ENCAPSULATION
ENCAPSULATION
is the process of assembling smaller parts into a bigger part...well, that's part of it. The other part is making various components of the class accessible to the "outside world." Words like PUBLIC and PRIVATE are often used to describe this concept. A METHOD or PROPERTY is PUBLIC if it can be accessed from the outside world. A METHOD is PRIVATE if it can only be accessed from within the class.

This is a foreign concept in procedural programming, because everything is sort of working from within a big silo. There is no concept of protecting data from another location. This is really the key concept in OOP.

An example of ENCAPSULATION would be: a driver (Human) can drive a car. The driver needs to know about the steering wheel, the gas pedal, the brake pedal, the shifter, and how to interoperate with all these concepts. The driver does not need to know about how the transmission responds to speed, or the explosions that need to happen in the engine for the car to move, or how the engine gets air and gas injected into it to perform the explosions to make the car move. So the pedals, steering wheel, and shifter are PUBLIC within the car class, and exposed to the driver, and the transmission, injection system, and components of the engine are PRIVATE, and only accessible internal to the car.

POLYMORPHISM
POLYMORPHISM
is a concept that requires some prerequisite understanding of OOP, particularly INHERITANCE, so I will speak to that a bit.
INHERITANCE is the process of one class inheriting methods and properties from a parent class. Logically, you could think that anything more specific than something else is a child of the more abstract concept.

For example, a Human is more specific than a Mammal, so it would follow that a Human would inherit from a Mammal (fur bearing, lungs, eyes, etc). It also follows that a Firefighter or Police Officer could inherit from Human. These are simple examples, but that's the idea.

POLYMORPHISM speaks to the concept of similar behaviors by different classes doing different things. For instance, a Human and a Dog could both inherit from Mammal the capacity to speak, but when Human implements Speak(), it is much different than the way Dog implements Speak() [where Human and Dog are the classes, and Speak is the method].

I'll post on each of these concepts in time, but I wanted the first few posts in this blog to be more conceptual than incorporating real world examples...there's plenty of time for that later.



Digg

Object Oriented Programming (Part 1)

As I've mentioned, Object Oriented programming is a paradigm, or a way of thinking. This is in comparison to procedural oriented programming, where you have a bunch of variables and functions (methods), and they may or may not interact with one another. Procedural oriented programming is quite chaotic, because there's not necessarily any organization or modularity (big pieces broken into smaller pieces).
I took a lot of philosophy courses in college, and one of my favorite philosophical quotes is by Rene DesCartes (you know, the "I think, therefore I am" dude?). The quote is "Divide each difficulty into as many parts as is feasible and necessary to resolve it." I think this quote is exactly what Object Oriented design achieves. Things that are logically different are stored in a different place.

For example, a human is different than a dog. Behavior, or actions, of a human is different than that of a dog. The properties of a human are different than a dog. To get more specific, a dog walks on 4 legs, where a human walks on 2. A dog eats without using its hands, where a human eats using his or her hands. A dog has a tail, and a human does not. A human goes to work, can buy a house, can drive a car, etc.

So, to lay it out in more general terms, object oriented programming is characterized by its implementation of CLASSES.

Think of a CLASS like a noun. A noun is something. For example, a human is a noun, a dog is a noun, a car is a noun, and a house is a noun. All of these "nouns" can be represented by a CLASS.

CLASSES are INSTANTIATED. An INSTANTIATED CLASS is called an OBJECT, hence the phrase Object Oriented Programming.

Think of an OBJECT as a more specific CLASS. They're both nouns. One of the examples I see a lot is comparing Dog and Lassie. The CLASS is Dog, and the OBJECT is Lassie.

For instance, this could be represented with the following code:

class Dog
{
    //Properties and methods go in here
}

Dog Lassie = new Dog();



Notice in the above example that I put a comment in the Dog class to indicate that PROPERTIES and METHODS go inside the class. I did this because a CLASS is made up of PROPERTIES and METHODS.

METHODS
Think of a METHOD as a verb. METHODS are things that an object can do. For instance, a Human OBJECT can generally Walk(). Human beings, also can generally Talk(). The verbs Walk and Talk represent the METHODS that the class Human can implement.

PROPERTIES
The other side of the coin is PROPERTIES. A PROPERTY is generally a characteristic (please note that a property can be more than just a characteristic). For instance, a Human can have hair and hair color. A Human can also have some number of fingers, ranging from 0 to 10, with a default value of 10.

So, before I start explaining too many properties and methods a human can have, I'll put a code example that describes the above examples:

class Human
{
    //Private members of the class
    private string _hairColor;
    private int _numberOfFingers;

    //Properties of Human Class
    public string HairColor
    {
      get { return _hairColor; }
      set { _hairColor = value; }
    }

    public int NumberOfFingers
    {
       get { return _numberOfFingers; }
       set { _numberOfFingers = value; }
    }

    //Methods of Human Class
    public void Talk(string words)
    {
      Console.WriteLine(words);
    }

    public void Walk()
    {
      Console.WriteLine("Human is walking, now");
    }
}

//Instantiation
Human Tim = new Human(); //Class Human is instantiated as "Tim"
Tim.HairColor = "Light Brown";
Tim.NumberOfFingers = 10;
Tim.Walk();
Tim.Talk("Hey man, I'm instantiated");


The above is a very simple example, and please don't get too bogged down in the syntax or implementation of the properties I used. I'll go on to explain these concepts in later posts.

My Struggles in Object Oriented Programming

Object Oriented Programming is a paradigm. If you don't like the corporate-speak of the first statement, then consider it a framework, or way of thinking. I was not formally trained in programming, and therefore, object oriented programming has always been a challenge for me to understand. In college (circa 1999-2003), I learned about several programming languages, like C, Visual Basic, and Java; but because I was not a programming major, the concept of object oriented design alluded me. I worked entirely within the procedural oriented programming paradigm, which is basically just a bunch of functions, interacting together, to solve a problem: brute force.

As time has gone by, I've realized that I love programming. I don't just love the mechanism of writing methods/functions to solve a problem. I love solving problems in a way that is reusable, eloquent, and highly valuable.

My first interactions with any sort of object oriented design came with PHP. Now, don't get me wrong; PHP is not truly object oriented, but it's pretty close, and the PHP-hardcores out there design with object oriented concepts in mind.

I programmed for years in PHP, occassionaly encountering concepts in OOP, but remained consistent in my procedural oriented programming paradigm. Then one day, I decided I'd "learn" C#. It was all over.

C# is entirely object oriented, and it's quite difficult to design quality applications without understanding OOP.

Along the way, I've come to realize that the tools that I gained in college allow me to solve problems in a brute force fashion, but there are better tools available these days for almost any problem I'm trying to solve.

The purpose of this blog is to share the tools and concepts I've found in the effort to help people like me, who are total computer nerds, but are not the super genius type who do this sort of stuff in their sleep.

Followers

Search This Blog

Powered by Blogger.