Object-Oriented Concepts

14th May, 2006 @ 11:20pm BST

Development, JavaScript, PHP, Web / 18 Comments

Object-oriented programming is still a relatively new technology in the world of web development; and, as such, some of the concepts are widely misunderstood by many capable web developers. This can be best illustrated by the recent boom of interest in the Javascript object literal.

As Senior Web Developer at Rentokil Initial, I am required to be technical lead within the team. This also means making sure the technology is understood and used correctly. With this in mind, I’ve recently noticed that many of my team-mates obviously don’t understand the underlying concepts of OOP. For this reason, I’ve prepared this short tutorial on the concepts - to be followed by more detailed posts on execution in Javascript and in PHP.

What is Object-Oriented programming?

Object-oriented programming can best be describe as a programming paradigm; a methodology of programming adopted by a programmer. Another example of a programming paradigm would be procedural (or sometimes, imperative) programming.

Procedural programming involves viewing a computer program as a sequential list of computational steps (or procedures) to be carried out. In procedural programming, the list of procedures can be further broken down into subroutines and functions (not to be confused with mathematical functions which are used within functional programming).

This is very much an “old skool” approach to programming and is adopted by many high-level languages such as BASIC. It’s also worth pointing out that most Web-based languages, such as PHP, ASP and Javascript, can be written using this approach - in fact when I first started out as a web developer, I was using ASP script, PHP and Javascript in this very manner, blissfully unaware of the OOP potential there-in.

In OOP, a program is seen as comprising a collection of individual modules, or objects, that act on each other. Each of these objects could be seen as an independent program in itself, with a distinct role or responsibility.

OOP provides greater flexibility and easier maintainance across large systems and can sometimes make understanding and analysing complex procedures a lot easier.

It’s worth noting, at this point, that most OOP languages (such as C++ or Java) are stateful where as often procedural programming languages are stateless.

Enemy of the State

In computer science, a “state” is a particular set of instructions which will be executed in response to the machine’s input. An information system or protocol that relies upon state is said to be stateful. One that does not is said to be stateless.

OOP PHP is stateless because each script must be called on a page refresh where as Javascript is stateful because it can make use of event listeners - specific input - and the wonders of XMLHttpRequest - thus negating the need for refreshes.

Phew. That was all quite technical and filled with emphasis wasn’t it? OK, so let’s move on…

Objects and Classes

The term “Object,” that gives OOP it’s name, refers to a conceptual object that represents an item in our program or system. This could be anything from an online form or a computer file, to a real world object such as a car.

This representation consists of attributes - the characteristics of our object; and methods - a set of functions and calculations that are either performed to modify the object itself, or are involved in some external effect.

The term “Class” represents the definition (or classification - class) of our object. For example, if we were to write a class called “car”, we could create any number of instances of that class - say “Porsche”, “Ferrari” and “Jaguar”. Each of these instances is an Object. This illustrates that a class is effectively a set of objects that all share common attributes.

Keeping it “in the family”

One of the greatest advantages to using objects is encapsulation. This basically means that data within an object is only available/modifiable via the object’s methods - this is generally known as the interface of the object.

This resultant limitation of scope allows an object-oriented programmer the freedom to declare attributes, variables and methods without having to worry about clashes with those in other objects.

Encapsulation also means that, as long as we don’t alter the interface, we can change how an object works (to increase performance, add functionality etc) without affecting the rest of our system.

Now let’s take a look at how objects and classes can relate to each other.

Note: From this point on, the concepts are going to get a little more complicated. Please bear in mind that I’m writing an introduction here - I fully intend to go over these concepts again (with examples) whilst applying them to Javascript and PHP in the tutorials to follow.

Characteristics of a Class

When writing a class, there are a number of characteristics that are worth taking into account:

Constructor

The constructor of a class is a special operation that is run upon instantiation - when an object is created. They are often distinguished by having the same name as the class itself. It’s main purpose is to set-up the attributes of a class and to establish the class invariant - to basically make sure that the attributes of the class conform to the class interface. It cannot have a return type.

A properly written constructor should never contain any functionality that could fail, thus leaving the object in an invalid state.

Destructor

The destructor of a class is the opposite of the constructor in that it is run when an object is destroyed. It’s function is to clean up and to free the resources which were used by the object during run-time and unlink it from other objects or resources. This should result in the invalidation of any references in the process.

Relationships

There are a number of relationships that can be used when interaction is needed between objects. These are as follows:

Inheritance

Inheritance allows a (sub)class to inherit all the attributes and methods of a parent class - in effect, extending the parent. It can best be described as an “is a” relationship. For instance, if we had a class of “fruit”, we could extend it by defining classes of “apple”, “orange” and “banana”. Each of these subclasses could be described in the following way:

apple "is a" fruit
orange "is a" fruit
banana "is a" fruit

Because each of our subclasses extends the “fruit” class, it has all the attributes and methods of a “fruit” plus any specific characteristics of it’s own.

Here’s a more web-development-oriented example using form elements and presented in pseudocode:

class formElement
{
  Attributes:
    id
    name
    class
}

class input extends formElement
{
  Attributes:
    value
    type
}

class textarea extends formElement
{
  Attributes:
    cols
    rows
}

In this example the two classes “input” and “textarea” have inherited from “formElement”. This means they inherit formElement’s attributes like so:

input is a formElement

input
{
  Attributes:
    id
    name
    class
    value
    type
}

textarea is a formElement

textarea
{
  Attributes:
    id
    name
    class
    cols
    rows
}

However, as the parent (super) class, formElement stays exactly the same:

formElement
{
  Attributes:
    id
    name
    class
}

As you can imagine, this relationship can be incredibally useful. Some languages even allow multiple inheritance where a class can have more than one parent (super) class. Sadly this isn’t the case in either Javascript or PHP, however it is possible to obtain the same effect using other types of relationship.

Composition - Association and Aggregation

Composition is a slightly different sort of relationship - this is where it could be said that a class was “composed” of other classes. For instance, a wall is “composed” of bricks and a molecule is “composed” of atoms. Neither of these examples could be described as inheritance - the statement, “a wall is a brick” simply isn’t true. Composition can be described as “has a” and “uses a” relationships; a wall “has a” brick or a wall “uses a” brick.

Let’s take a look at a “has a” relationship in pseudocode. Let’s first define some simple classes:

class brick
{
}

class wall
{
  Attributes:
    brick1
    brick2
    brick3
    brick4

  Methods:
    // Constructor
    wall()
    {
      this.brick1 = new brick();
      this.brick2 = new brick();
      this.brick3 = new brick();
      this.brick4 = new brick();
    }
}

You can see that “wall” contains a number of brick attributes. We want each of these attributes to be a “brick” object. To do this we simply instantiate them within the constructor of the “wall” class. Each of these brick classes will function as a normal class but also as an attribute of “wall.” This is known as association.

Now let’s take a look at a “uses a” relationship:

class person
{
}

class car
{
  Attributes:
    driver

  Methods:
    // Constructor
    car(driver)
    {
      this.driver = driver;
    }
}

me = new person();
myMotor = new car(me);

In this example, we can see that the “person” class has been instantiated into the object “me”. This object is then passed into an instantiation of the “car” class. This means that the object “myMotor” (our instantiation of the “car” class) uses the object “me”. This relationship is known as aggregation.

Update: Thanks to Nate Logan for spotting a small error in that last example and emailing me. :-)

The main difference between these two relationships is simple; in association the composing classes are destroyed when the parent is destroyed, however, in aggregation they are not. This ultimately means that, when aggregation is adopted as a relationship, the composing classes and objects can be re-used in other classes and objects within the system.

Polymorphism

An object-oriented programming language must support polymorphism; meaning different classes can have different behaviours for the same attribute or method. This can best be illustrated with an example:

class formElement
{
  Attributes:
    id
    name
    class

  Methods:
    getHtml()
    {
      // returns generic form element HTML
    }
}

class textarea extends formElement
{
  Attributes:
    cols
    rows

  Methods:
    getHtml()
    {
      // returns textarea form element HTML
    }
}

As you can see in the example, both classes have the method “getHtml” but the “textarea” class is a subclass of the “formElement” class. This results in the “getHtml” method being overloaded. Overloading is a good example of polymorphism in action - an object-oriented language must support polymorphism in order to know which “getHtml” method applies to which object.

Polymorphism, at it’s most basic, describes the fact that a given function may have different specifications, depending on the object to which it is applied.

Why use Object-Oriented programming?

Object-orientation can help keep projects simple by breaking them down in to managable chunks. Those chunks can then be re-used in other projects, thus saving time in the long-run. In fact, adopting an object-oriented approach can be the foundation of a truly successful team environment; through promoting modularity, an object-oriented environment breeds improved code reusability and maintainability.

But don’t just take my word on this; try it for yourself! To better help you to do that, I’m going to follow up this introduction to object-oriented programming with tutorials on it’s use within Javascript and PHP.

So in closing, I hope you’ve learnt something new from this overview. Please feel free to post comments and questions and I’ll endeavour to reply to the best of my ability.

Like this post? Digg it, Del.icio.us it, Ma.gnolia it!

Comments (18)

Skip to the comment form…

  1. Gravatar Image Steve Tucker May 15, 2006 @ 12:04 am

    Good article. I, like everyone else, found OOP pretty challenging at first, but it’s a piece of piss once you get used to it. Now virtually all my work involves this programming style. It is definitely the way to go.

  2. Gravatar Image Matthew Pennell May 16, 2006 @ 12:53 pm

    Another great article (although you might want to fix the typos - ‘unctions’ is a new concept to me…) ;)

    Is there any reason why you talk about attributes instead of properties? I’ve always referred to the methods and properties of an object.

  3. Gravatar Image Tim May 16, 2006 @ 1:03 pm

    @Matthew:

    DOH! Must remember to spell-check before I publish…

    As regards the attributes of the object; there’s no particular reason - in fact, in the last few days I’ve read many articles where methods are sometimes called operations or functions.

    Having had a quick look through some of my reference books, it seems some of them do indeed call them properties where as others call them attributes. I’m really not fussy over which I use (although I hope I don’t start alternating half way through a blog post now)…

  4. Gravatar Image Rich Pav May 25, 2006 @ 4:48 am

    I’m pretty thick-headed when it comes to learning new concepts. I have to read a dozen or so different explanations of it before I finally get a grasp. Thanks for offering yours, and I look forward to more.

    BTW, “it’s” is a contraction of “it is”. When you’re talking about something belonging to “it” the appropriate word is “its.”

  5. Gravatar Image Rich Pav May 25, 2006 @ 4:53 am

    You know, I’ve always wondered about your company’s name. On the wall of every train station restroom in Japan, there’s a Rentokil plastic doodad thing that I assume is supposed to neutralize the piss fumes. If it actually works, I’d hate to find out what restrooms without one smell like.

  6. Gravatar Image Tim May 25, 2006 @ 10:45 am

    @Rich Pav: Thanks for the English lesson ;-) - I’m always making that mistake.

    As for Rentokil’s Washroom Services division, you should see the female urinals that R&D came up with…

    … you think I’m joking too…

  7. Gravatar Image E.T. October 27, 2006 @ 1:16 pm

    What happened to the tutorial? Just when it started into the good stuff, the comments section overwrites it! The last thing I see is the “ENEMY OF THE STATE” heading and the next line. Then it dissappears. Can you make it re-appear it can be seen?

    Thanks

  8. Gravatar Image E.T. October 27, 2006 @ 1:17 pm

    Never mind…now it appears after I posted the last comment.

  9. Gravatar Image E.T. October 27, 2006 @ 1:19 pm

    Then I posted the second comment and it disappeared again! Agggggghhhh!

  10. Gravatar Image Tim October 27, 2006 @ 1:20 pm

    @ E.T.: Sounds like something peculiar is happening with the stylesheet. I’ll have a look into it now - incidentally, what browser are you using?

    Update: Ok, have tested in a number of Windows browsers (IE7, IE6, IE5.5, FF2, FF1.5, Opera) and everything seems fine - but just in case, I’ve updated a small issue I was aware might be a problem in IE7 (even though it didn’t appear to be during testing). Let me know if you’re still having problems!

  11. Gravatar Image Dustin Diaz November 9, 2006 @ 8:44 am

    It’s good just to see examples of these concepts no matter what language. Even if represented in UML - it’s a good gesture to put this out here :)

  12. Gravatar Image Matthijs November 10, 2006 @ 8:18 am

    Tim, this must be one of the best articles I’ve read so far explaining OOP concepts. Very clear. Now I’m off reading the other articles.

    Thanks.

  13. Gravatar Image Aravind Parandhaman July 18, 2007 @ 4:53 am

    Good one.

    Concepts are clearly explained.

  14. Gravatar Image Tony Barbarich October 31, 2007 @ 9:36 pm

    This is a very good post; however, it seems that you may have contracted your explanation of literal objects. You mentioned that a literal object is an object defined literally. And that another instance of a literal object must be invoked with the new operator.

    But it is my understanding that an object literal-with out a constructor-is an expression that creates and initializes a new and distinct object each time it is evaluated. That is, a single object literal can create many new objects if it appears within the body of a loop in a function that is called repeatedly.

    Please respond back
    qualarc.com
    dev. Tony Barbarich

  15. Gravatar Image Tim November 1, 2007 @ 10:32 am

    @Tony: I assume you’re referring to my explanation of the object literal in my companion post about OO JavaScript…

    You are correct in your understanding of the object literal — and creating new objects within a loop would work as you expect; using the new operator, however, would definitely be a little more elegant since you’re not having to do all that definition code over and over in memory.

  16. Gravatar Image Whatever-ishere November 21, 2007 @ 4:43 pm

    thanks for the GREAT post! Very useful…

  17. Gravatar Image Wing Ming Chan December 21, 2007 @ 8:42 pm

    The discussion on polymorphism is not quite complete without mentioning late binding. Method overloading is just the first half of the story. If we understand the following example, then we would have a good grip on polymorphism:

    // base class
    class Car
    {
    	private $name;
    	function __construct($n)
    	{
    		$this->set_name($n);
    	}
    
    	function set_name($n)
    	{
    	  	$this->name = $n;
    	}
    	function get_name()
    	{
    	    return $this->name;
    	}
    	function accelerate()
    	{
    		echo "Now I'm running 10 mile faster\n";
    	}
    }
    
    class SportsCar extends Car
    {
    	function __construct($n)
    	{
    		parent::__construct($n);
    	}
    	function accelerate()
    	{
    		echo "Now I'm running 20 mile faster\n";
    	}
    }
    
    // an array of cars of different types
    $cars = array(new Car("Ford"), new SportsCar("Porche"));
    foreach ($cars as $c) {
    	$c->accelerate(); // polymorphic behaviors
    }
  18. Gravatar Image randrace January 8, 2008 @ 6:40 pm

    Isn’t your example of polymorphism overriding not overloading?

Leave a comment





Categories

Syndication

Technorati

© 2008 Tim Huegdon, All Rights Reserved / Website design and development by Nefarious Designs

Powered by Wordpress 2.3 / Login

Caution: This website may cause headaches and seizures when used incorrectly.