"Object-oriented programming (OOP) is a programming paradigm that represents concepts as "objects" that have data fields(attributes that describe the object) and associated procedures known as methods. Objects, which are instances of classes, are used to interact with one another to design applications and computer programs." -Wikipedia

Phew... that was a mouthful. Here is how I would define Object Oriented Programming; A programming pattern that allows specific chunks of functionality (objects) to interact with each other through the use of class functions (methods) and store class specific data (properties).

When I first started learning about OOP the sheer amount of knowledge and abstractness of the subject was overwhelming to say the least. There is an entire different set of terminology and language to learn while trying to understand the basic theory.

Some Quick Terminology

As I am a kinesthetic learner I find the best way to learn something is to practice it. So lets walk through an example of OOP using a real world system. The following code examples are written in php but the concepts can be used regardless of language.

A Car is Object Oriented

Think about the following statement, "A car is an object oriented system". What this means is that you can think of a car as a physical object in space. The object accomplishes a specific purpose and has attributes that are specific to it. Learning object oriented programming in the context of a real-world system is also easier to understand than trying to use an abstract programming example. So from now on whenever I say Car think object.

<?php

// Class wrapper

class Car {

}
?>

A Car has Specifications

There are about a million different specifications associated with a car. These are based on the type of car, year, and model. If we look at two cars of the same type, year, and model they should... theoretically... be identical.

For our representation of the Car object lets create the following properties: manufacturer, weight, turned on status, and the current speed.

<?php

// Properties

class Car {

     private $manufacturer = 'Honda';
     private $weight = 2300;
     private $isTurnedOn = FALSE;
     private $speed = 0;

}

// A variable outside the class holding the Car Object

$Car = new Car();

?>

A Car Performs Specific Functions

Cars perform many different methods of function. We will limit ours to the following: Brake, Accelerate, and Start Ignition. What we have just done is provided the structure for our object. We now know exactly the amount of functionality needed and even the names for the methods we will use. Planning out the design of an Object Oriented system from the beginning is important to help keep code efficient and DRY.

Methods

<?php

class Car {

     private $manufacturer = 'Honda';
     private $weight = 2300;
     private $isTurnedOn = FALSE;
     private $speed = 0;

     public function brake ($value) {

     }

     public function accelerate ($value) {

     }

     public function startIgnition () {

     }

}

// A variable outside the class holding the Car Object

$Car = new Car();

?>
Conceptualize: A method such as Repair Car Engine would not be suited for our Car Object. A car would not repair itself. This would be performed by a Mechanic (a potential other object).

Visibility and Encapsulation

You may have noticed the word "public" before the methods. This is what is known as visibility. Visibility refers to how accessible a method or property is to other classes. This is necessary for understanding proper encapsulation.

There are three types of visibility. Public, Protected, and Private. A public method/property is accessible to the class it originates inside, any child class that extends it, as well as other classes. A protected method/property is visible to only the class where it originates and child classes. A private method/property is visible to only the class it originates in.

Best Practice: When trying to decide visibility for methods and properties you should provide only the bare minimum necessary to execute.

Encapsulation is the idea of hiding the implementation of your class and exposing its functionality in a limited way. This prevents overriding of functionality and reduces duplicate code.

In order to properly encapsulate our class we need to set the visibility for each of our properties and methods. Lucky for you it has already been done. Our methods were all listed as public and our properties were labeled private. The properties now are only accessible to the class Car. A common design pattern is to create helper methods called getters and setters.

Getters and Setters

This is actually a fairly straight forward concept. They literally do exactly what they say and nothing more. A getter method returns a property while a setter method sets it. These allow other methods to access the Car objects private variable for manufacturer.

<?php
/**
 * Getter for Manufacturer
**/
public function getManufacturer () {
     return $this->manufacturer;
}

/**
 * Setter for Manufacturer
**/
public function setManufacturer ($value) {
     $this->manufacturer = $value;
}
?>

I have introduced a new keyword called $this. $this refers to the current class it is within so in this instance $this will include all the methods and properties for the Car class. By calling $this->manufacturer inside getManufacturer we return the private variable manufacturer. This will help to differentiate between variables defined within a method (local variables) and a class properties (public, protected, private).

Quick Note: When calling a property using $this you do not use a second dollar sign. $this->$manufacturer will generate an error.

We can now set and get the car's properties on the fly. Getters and Setters may seem tedious and unnecessary (and they sometimes are in smaller applications) but they should help you to provide access points for other classes while forcing you to organize your code. Here's a quick simple example.

<?php
$Car = new Car();

$manufacturer = $Car->getManufacturer();

// Outputs Honda, the default value

echo $manufacturer;

$Car->setManufacturer('Acura');

$manufacturer = $Car->getManufacturer();

// Outputs Acura

echo $manufacturer;
?>

Gentleman, Start Your Engines

Now that we have some of the basics completed, lets move onto some actual functionality. First lets flesh out the startIgnition method. This method will check the isTurnedOn property to see if it is false (turned off) and if so will change it to True.

<?php
public function startIgnition () {

     // Check to see if the car is already turned on

     if (!$this->isTurnedOn) {

          // If the car is off lets turn it on

          $this->isTurnedOn = TRUE;
     }

}
?>

The isTurnedOn property now can be checked before running other methods. We can use this to perform a sanity check on the turned on state of the car. A car wouldn't be able to accelerate or brake if is isn't turned on, right?

<?php
public function accelerate ($value) {

     // Check to see if the car is already turned on

     if ($this->isTurnedOn) {

          // If the car is turned on then add the parameter value

          // from the private speed variable.

          // We are increasing in speed.

          $this->speed += $value;
     }

}

public function brake ($value) {

     // Check to see if the car is already turned on

     if ($this->isTurnedOn) {

          // If the car is turned on then subtract the parameter value

          // from the private speed variable.

          // We are decreasing in speed.

          $this->speed -= $value;
     }

}
?>

Our accelerate and brake methods now will only run if the car is already turned on. This is the expected result. Both methods can have lots of functionality added to them. I'll leave these up to you but here are some questions to get you thinking.

88 MPH

The last piece of our Car class will be to output some information that the user can utilize. This will include a new getter method for the car's speed and an output method to display a string that is user readable.

<?php
public function getSpeed ($value) {
     // Get the current speed

     return $this->speed;
}

public function outputCurrentSpeed () {

     // Set the local variable (output) to equal a string

     // that contains the returned result from the getSpeed method.

     $output = 'You are traveling at ' . $this->getSpeed() . ' mph';

     return $output;
}
?>

Again by using the $this keyword we refer to the current object. Because the object is a Car object we can access the newly created getSpeed method to return the speed of the car. As displayed above this is concatenated into a string for output. With the functionality of our class completed we can now try it out and see it in action.

<?php
$Car = new Car();

// Start the Car

$Car->startIgnition();

// Accelerate to 88 mph

$Car->accelerate(88);

// This will output "You are traveling at 88 mph"

echo $Car->outputCurrentSpeed();

// Lets stop the car

$Car->brake(88);

// This will output "You are traveling at 0 mph"

echo $Car->outputCurrentSpeed();
?>

Summary

There you have it. A working OOP class structure. Feel free to build upon this or add other methods.

« Previous Post
Create a jQuery Twitter plugin from scratch
Next Post »
Responsive Browser Testing with Adobe Edge Inspect

Join the conversation

comments powered by Disqus