An introduction to OOP

Note: This article has been marked for a quality review and will soon be updated.

Object-orientated programming is a concept that is more likely to pop up when programming desktop applications rather than those for the web. But once you start using OOP you will wonder why you ever used procedural programming (that’s simply using a program that calls a load of functions/procedures), well maybe not completely – OOP has its place on the web, and in this tutorial we will explore a practical usage of the common programming-paradigm. So what is it? Put simply OOP is when programmers create objects in which they can store data, and ask those objects to do certain things. So for an example, we might have a person object for which we can set things like eye colour and height – these values would be stored in variables. We might also have some instructions that we can give to our person object* like “star jump!”, our person would then do a star jump, in our case it might be more like writing something to the screen like “I just did a star jump!”.

So how do we know what variables and instructions we have for any give object? Put simply, with our class. A class is a file which contains all the information about any objects that will be created. The most common analogy for a class is a blue-print – it’s a good one, because our class contains all the information we need to know about anything we make using it. Just as a blueprint for a house tells us the dimensions of the thing, it also shows us how the doors open and where the water comes in. When we actually make our house in the real world we build it, in the world of computers we instantiate it. When we’ve finished building in the real world we say we have a house, in programming we call it an instance of the house class.

Deep breaths people! Let’s move onto the why we might want to program like this.

OOP really re-enforces a number of good programming techniques, and the 4 principles of the paradigm are as follows: A PIE. No, not the tasty treat, but another acronym! Now if your background isn’t in programming the next 4 words might fly over your head – but for the moment I need you to grab a net and get ready to catch them. A PIE stands for Abstraction, Polymorphism, Inheritance, and Encapsulation. Now if you’ve done any programming on the web or otherwise it’s likely you’ve done at least 2 of the above things. So let’s go through them one at a time.

Abstraction

This refers to the technique of taking a problem and focusing on the ‘abstract’ rather than the individual. Take a look at this function:

function addMyNumbers($a, $b){
    return $a + $b;
}

Above is a very basic example of abstraction at work. Instead of writing 4 + 7 directly into our code, we have written a function that adapts to return a value based on what we pass to it. Therefore we have abstracted that concept. In OOP we use abstraction to make classes. For instance, in our person class we might have an instance method of runOneMileThatWay() – a method that does exactly what the name suggests. But the problem with such a method is that it is very specific. If we wanted our person object to run 5 miles instead of 1 (they are very fit by the way), we would either have to write a new method, or call the same method 5 times. The solution to this is to copy our add method above, and pass a value which tells our instance to run $x amount of times. This makes our program more efficient and easier to maintain.

Polymorphism

If any of these words is going to trip you up, this is gonna be the one. Bear with me here. Polymorphism is the term used to describe the idea that variables, objects, and functions can have more than one form. We don’t need to go too deep into why this is important, but let’s take a look at an example where polymorphism comes into play.

$x = (int) 4;
$y = (float) 5.76532;

echo $x + $y;

Perfectly legal right? We’ve declared 2 variables – one integer, and one floating point number, and then added them together. Run this code and you get a number just below 10. But technically this shouldn’t work. Integers and floats are stored using different methods, but thanks to polymorphism PHP knew to simply add the two together as we humans would, instead of complaining about the distinction between integers and floats. And that’s all you really need to know about polymorphism for now.

Inheritance

Nice and simple – your mum has blue eyes, so you have blue eyes right? Well human genetics is a little more complex than what we’re going to be doing, but you get the idea – you inherit (or get) your traits from your parents and general ancestry. In OOP our objects can also inherit things like methods from their super classes. In certain languages you must always tell the world (or rather compiler) what class you are inheriting from. For example in Objective-C – the language used on iOS, the most common class to inherit from is called NSObject. As I said before you can inherit methods which ensures you don’t repeat yourself, and can easily maintain your code. NSObject contains really useful methods such as ‘description’ which can do all kinds of things.

In our example we might have methods such as ‘wake up’ and ‘sleep’, but these behaviours are not limited to humans, all living things do this (I should think), so maybe we could create a class called ‘Animal’. In the animal class we could have methods such as wakeUp and fallAsleep, and then we could sub class it and make our person class inherit from it. Lets see the PHP way of doing just that.

Class Animal {
	private $awake = false;

	public function wakeUp(){
		$this->awake = true;
	}
	
	public function fallAsleep(){
		$this->awake = false;
	}
}

Class Person Extends Animal {
	public $name;
	
	public function starJump(){
		echo $this->name . ' did a star jump!';
	}
}

$me = new Person();

$me->wakeUp();
$me->name = 'Tom';
$me->starJump();

Don’t worry about the syntax too much if you’re not familiar with it; but here we can see that we have 2 classes. Our first is ‘Animal’ which has the methods we said we’d create, and the second is ‘Person’ which allows us to do a star jump – I’ve never seen a monkey do one of those, so I think we’re safe to keep that within our own species for now. We then create a new object based on the person class, and immediately call the ‘wakeUp’ function – but this doesn’t exist in our Person class, so what’s going on?! Well because we used the keyword ‘Extends’ – (syntax varies from language to language) our $me object has access to all the methods implemented in our Animal class. And that’s inheritance.

Encapsulation

Last but not least is this badboy. The term is means when we take the data (instance variables/ivars) and instructions (methods), and put it all within a class. When we do this we make our objects self-sufficient. Think about it like so. Without encapsulation our person class might have to be operated on by another function outside of our class to, say for instance, make a curry. So it might send a bunch of messages (that’s just calling the methods of a class), to our object, and fiddle around with our public instance variables. That way of doing things will get the job done. But, and it’s a big but, it ain’t good practise!

If you were working on a project where your people objects had to be able to make a curry (maybe it’s a restaurant game), and you wrote your curry method outside of your person class it would work. But then what happens if you start a new project, and the people objects in that scenario need the curry shizzle?! Bad things start to happen, that what happens. So let it be known, objects should know what they are doing without needing help (anything beyond variable data), from the rest of your program. Maybe you decide not all people should need to know how to make a curry (plain craziness quite frankly), it would be a better idea to sub-class the Person object to something like a ‘Chef’ class – using your handy friend inheritance .

And with that we have finished with the main concepts of OOP. As you can see above, most of the A PIE concepts work together to create a beautiful paradigm (to a programmer at least), and one that will ensure you consistently write good quality code. Although this has been written from the perspective of web development, should you ever wish to move into complied programming languages such as Objective-C for iOS, you will find that they are heavily class based, so you’ve learnt something that should serve you well in the future – well done you!

* I am by no means suggesting that you objectify men or women.


Posted

in

by