Basic terms in object oriented programming.

Object oriented programming (OOP), is a model that can provide structure to complex systems, this allow us to build systems that is maintainable.  Changes can be made to isolated parts of the system without breaking the rest of the system.

This is done by splitting the system up into objects, each object is focused on a single part of the system. This makes working in a team easy because different developers can concentrate on different parts and scopes of the system.

Some of the advantages OOP has over procedural, is the ability to create units that contain both the data and the methods that operates on the data,  in a single unit called an object, this makes code more readable, because data does not need to be passed back and fourth functions that operator on the data. With object’s you are given the ability to reuse code, by allowing one object to inherit methods and properties from another object.

One way to think about objects, is that you can look at practically any items in the real world as a collection of objects. Take a house for example, a house is built from many small individual objects, these object’s represent a single part of the house, Windows, Doors, Kicthen etc, and combined they form a house.

Think of objects as the nouns of your system. where the object methods is the verbs.

class:

A class is a group of methods and properties that describe a blueprint for creating objects.

implementation:

implementation referers to the actual code that defines the program behavior.

<?php
class MyClass
{
    public function myMethod($arg1, $arg2)
    {
        // all code in here is the
        // implementation of the class method myMethod().
    }
}
?>

State:
an object’s state represent the object’s internal value at a given time. Each properties in a object can represent a state, for example a object handling an database connection could have a property called isConnected, this property represents the state of the current connection (is it open or is it closed).

class DatabaseConnection
{
    # the state for the current db connection.
    private $_isConnected = false;
 
    public function setConnected($state)
    {
        $this->_isConnected = $state;
    }
    # getter for accessing the state of the connection.
    public function isConnected()
    {
        return $this->_isConnected;
    }
}

type:

a type is one or more method declarations grouped into an class or an interface.

A object can have multiple types, thru inheritance or implementing interfaces.

# a type called User exposing a method called sayHello().
class User
{
    protected $_username;
 
    public function __construct($username)
    {
        $this->_username = $username;
    }
 
    public function sayHello()
    {
        echo "Hello world";
    }
}
 
# a type called IAuth exposing two methods login() and logout().
interface IAuth
{
    public function login($username, $password);
    public function logout();
}
 
# a type called EditableUser.
class EditableUser extends User implements IAuth
{
    public function login($username, $password)
    {
        echo "logged in";
    }
 
    public function logout()
    {
        echo "logged out";
    }
 
    public function editUsername($username)
    {
        $this->_username = $username;
    }
}

Here we have three different types:

  1. a class named “User” which declares a single method called sayHello().
  2. an interface called “IAuth” which declares two methods, login() and logout().
  3. a class called “EditableUser” which expose all methods inherited by the “User” class, and all  methods declared by the interface “IAuth“, and finaly it declares a single method called editUsername(). This class actually represent three different types, “EditableUser“,  “User“, “IAuth“.

Encapsulation

the main concepts of encapsulation is:

  • allows for safe change in our implementations, by hiding the implemenation behind an interface, this allows us to add changes to the implementation, without affecting the code that uses our object.
  • restrict access to methods, by making them invisible to certain scopes, instead of have helper functions floating in the global scope, we can hide these methods inside an object which will utilize them to help fullfill the purpose of the methods exposed by the object’s interface, this helps simplify our object’s interface to only expose methods relevant for utilizing the object and not how it is utilized. – this comes very much in handy when using a modern IDE with autocompletion.

nka460nw

- An real life example of encapsulation could be a TV remote,  the TV remote expose an interface in a manner of its buttons. We can utilize the buttons without understanding the complexity of how the TV remote signals our TV to switch channel, all we really care about when pushing the “on” button our TV gets turned on by magic. So our TV remote encapsulates the logic for turning on the TV and exposing a button called “On” to us the users.

Abstraction

Is a technique of having a complex task, and splitting the task up into smaller tasks, this enable us to focus on a small part of the system, instead of having to focus on the entire system.

When designing a complex system its important to look at the system from a high perspective. Take a blog for example, what parts would make up a blog?.

  • We need some data persistence so we use a Data Access Layer.
  • We need a admin login so we need some kind of Authentication.
  • Also we need Posts that make up the content of our blog.

This would give us three object’s

class DataAcess
{
    public function connect();
    public function query();
}
 
class Authentication
{
    public function authenticate($username, $password);
}
 
class Posts
{
    public function getLatest();
    public function getMostViewed();
}

This is looking at the system from a high perspective, we don’t specify how to connect to the database, how to validate the user’s criteria or how to prevent XSS and SQL injections, because it is not relevant to the current level of abstraction (detail).

Now we can focus on three different parts of the system individually, lets add some more specifications to the Posts class, the posts class will be responsible for getting lists of posts, each post is encapsulated in a unit called a Post, that will expose a simple CRUD interface

class Post
{
    public function getTitle();
    public function getContent();
 
    public function create($data);
    public function update($data);
    public function delete();
}

Here we’ve abstracted the details in how to store / read / update / delete post data, in the class Post. now its up to the methods in Post to specify how to retreive and update the data of a post.

Inheritance

One way of adding behavior to an class, is with inheritance this is done by extending an existing class. The class being extended is known as the “parent class” while the class the class extending another class i known as the “sub class” or “derived class“.
With inheritance you can easily modify or add behavior to existing classes, without having to do modifications to the “parent class”. This makes it easy to reuse existing code.
Many object oriented languages are restricted to single inheritance, meaning it is possible for a class to extend only one “parent class”.

Extending a parent class creates a tight relationship with the parent class and the derived class this relationship is known as a “is-a” relationship, before extending an existing class ask yourself

is my derived class a parent class

# an example of a bad is-a relationship
class User extends Login
{
}
 
# an example of a good is-a relationship.
class AdminUser extends User
{
}

The first class is a User class extending a Login class, this doesnt make much sense A User is not a Login”, the second example demonstrate a valid example of a is-a relationshipA AdminUser is a User”. The first example would be better off with a “uses-a” relationship. (more about this topic in a future topic)

A great way of using inheritance is to create a “base” class which contains behavior that specialized classes can extend.

Polymorphism

By restricting input objects to a specific type, methods on those objects can be invoked regardless of the concrete implementation.

an example using the already defined IAuth interface.

class DatabaseAuth implements IAuth
{
    private $_dbh;
 
    public function __construct()
    {
        $this->_dbh = new PDO('dsn');
    }
 
    public function login($username, $password)
    {
        $queryString = "SELECT * FROM users WHERE username = ? AND password = ?";
        $loginStmt = $this->_dbh-&gt;prepare($queryString);
        $loginStmt->execute($username, $password);
 
        if ($loginStmt->rowCount() > 0)
        {
            echo "Logged in";
        }
    }
 
    public function logout()
    {
        echo "Logged out";
    }
}
 
class XmlAuth implements IAuth
{
    private $_simpleXml;
 
    public function __construct($filepath)
    {
        $this->_simpleXml = simplexml_load_file($filepath);
        /*
         <users>
             <user>
                 <username>mads</username>
                 <password>test</password>
             </user>
             <user>
                 <username>admin</username>
                 <password>hello</password>
             </user>
         </users>
        */
    }
 
    public function login($username, $password)
    {
        $xpathQuery = '//user[username='.$username.']';
        $userElement = $this->_simpleXml-&gt;xpath($xpathQuery);
 
        if (!empty($userElement) &&
            (string)$userElement[0]->password == $password)
        {
            echo "logged in";
        }
    }
 
    public function logout()
    {
        echo "logged out";
    }
}
 
$databaseAdapter = new DatabaseAuth();
$xmlAdapter = new XmlAuth('path/to/xml.xml');
 
function doLogin($username, $password, IAuth $adapter)
{
    $adapter->login($username, $password);
}

Regardless of the concrete implementation of IAuth interface, the doLogin() function will invoke the method login() on the object, the doLogin() function does not care about how the login details are stored, its up to the concrete implementations of IAuth.

Polymorphism allows for different types to be used the same way, by sharing a common type (IAuth in this example).

Strongly typed language:

There is alot of definitions on what a “type strong language” is, i will write what the definition means to me.

A type strong language requires all variables, return values and method arguments to explicit state their expected value type.

string myName = "Hello world";
 
public bool mayBuyBeer(string username, int age)
{
    if (username == "mads")
    {
        return true;
    }
    return (age > 18);
}

strong typed languages are compiled and not parsed. An advantage of a strong typed language is the compiler can catch errors at compile time, because all variables and return values have explicitly been assigned a type,the compiler can crosscheck that all variables ever assigned and returned will match the expected type, eliminating many of the hard to find runtime bugs that can occur in weakly typed languages.

Weakly typed language:

a language like PHP is weak typed, even though it has a OOP model, the reason is all variables types is implicit resolved by the value assigned to them

$myName = "Hello world";
 
public function mayBuyBeer($username, $age)
{
    if ($username == "mads")
    {
        return true;
    }
    return ($age > 18);
}

PHP also cast types to match the context they are used in, for example a string compared to a integer will attempt to cast the string to a int first and then make the compare.

A weak typed language is said to require less effort for the programmer, because the parser / compiler takes care of all the type handling. This comes with a payoff that the compiler cant catch as many errors, and can result in more runtime errors.

1 Comment
December 28, 2009 in Object oriented programming
Tagged , , ,

One Response

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>