Object Oriented Programming

Teodor Filimon, Gadget Developer
August 2007
"One for all, and all for one"  -  Alexandre Dumas, pere

Introduction

Object Oriented Programming (or OOP) is a programming technique which seeks to solve problems or create applications based on objects and the interaction between them. The programmer's purpose, when using this technique, is to translate real-life aspects into the code of the program, or at least improve the efficiency and readability of the code when dealing with abstract concepts.

Usually, when creating software (or other things) this way, the people who are responsible think of schemes to reflect objects which will be used in the code, and interactions between them. Those schemes should be drawn in a way that every contributor will understand them, so, even though it depends on the project itself, most of the times the Unified Modeling Language (or UML) is used.

This article will show you how to determine possible objects in the problem you need to solve, and how to represent them. We'll also see how to apply object use in Javascript, and how it will help when creating a gadget. I'll try to avoid very scientific terms and constraints for the presented techniques to help you understand OOP and its uses quicker and easier.

OOP Principles

Object Oriented Programming will obviously deal with objects, but to define objects we first need to know their type which we describe in something that's called a class. Objects are actually instances of a certain class, tangible forms of that class' existence - to understand this better, think of the following situation: if you show a painting of an apple to some friends and ask them what it is, the 'most' correct answer would be a painting of an apple, not an apple :) A class, besides a name to differentiate it from other classes, contains methods and attributes.

When defining attributes and methods we also need to know their visibility. Visibility is a pretty complex concept in programming and can help us make the program work more efficiently. The most important operators are: public (accessible from the outside of an object) and private (invisible to the exterior, accessible only for the inner workings of the object; usually helpers or auxiliary to the computations which need to be done in an object). Not all programming languages deal with visibility issues; for example, Javascript lets all methods and attributes be public.

To produce the instances we've been talking about, we use special methods called constructors, which are usually named after the class they construct. Depending on how efficient we want to be, we can also define our own destructor methods.
//constructing the object, an instance of a class
objectInstance = new ObjectClass();

//the constructor can have parameters
//also, there can usually be more than one constructor
salary = 1000000;
me = new Employee(salary);

In the programming world, there has yet to be a convincing OOP definition which everyone will agree upon, but what's important is that certain principles have been formulated to help us understand and use OOP:

Class Diagrams

As i've said, when creating a program using OOP, some planning and organizing is usually done before the actual implementation. So, a class diagram is basically a drawing which shows the program structure, specifically the relations between classes used in that program. Here are some details about often used types of relations:

Here are some tips:

Sequence Diagrams

If class diagrams are static representations (based more on attributes, whether we want it or not :) sequence diagrams show the interaction between objects in a dynamic way. Basically, the objects are placed in the upper part of the diagram, with vertical lines coming down from them. These lines actually represent the time, and we can see the succession of events, triggered by certain actions (methods). Usually, the actions are symbolized through contiguous arrows, while responses, which are sometimes required after query-like methods, are symbolized through dotted arrows. You can see all this below:

Sequence Diagram
Figure 10: Sequence Diagram - as seen in
this Wikipedia article

This example shows us what happens when we click the Send/Receive button from an offline email client. The first action performed by the program is to send unsent email (sendUnsentEmail). Then it 'asks' the server if there is new email (newEmail) and, depending on the response, it will be downloaded; after that, old email is deleted. Notice that when making such a sequence diagram, the methods on the arrows should belong with the object their pointing at (for example, the sendUnsentEmail method belongs to the Server object).

Here are some tips:

OOP for Javascript - how to use in a gadget (Basic concepts)

Chart
Figure 11: What's behind that graph?

This section shows you how to bypass some common problems, how to create class-like entities and how to use them. So, to get to the point, how often have you been put in front of the need to make 2 arrays, with the same length and referring to the same elements? Well it's been too often for me :) and a cool solution is using simple to implement OOP. For example, in my Chart gadget, i condensed the 2 arrays into a single array, containing elements of a certain type, which i define. First, i created a class called Dot to hold the location of a point.

function Dot(xParam,yParam){
	this.x=xParam;
	this.y=yParam;
}

As you can see, the x and y attributes are set when calling the class constructor. You can see an actual call here:

function MakeArray(dataParam){
	//...
	aux=data.split(';');
	for (i=0;i<aux.length;i++) {
		coordinates=aux[i].split(',');
		dots[i]=new Dot(parseInt(coordinates[0],10),parseInt(coordinates[1],10));
	}
}

After i get the exact value of the coordinates, which are initially separated by the comma character in a string, i create a dots array containing Dot objects, which are constructed as seen. Here's a snippet of code that calculates sizes and positions for the chart lines, based on the previously recorded point coordinates.

for (i=0;i<dots.length-1;i++){
	lines[i]=chart.appendElement("<div height='2' background='#888888'/>");
	lines[i].x=(dots[i].x-minXValue)*xUnit+2;lines[i].y=height-(dots[i].y-minValue)*yUnit-2;
	lines[i].rotation=-Math.atan((dots[i+1].y-dots[i].y)*yUnit/(dots[i+1].x-dots[i].x)/xUnit)*180/3.1415;
	lines[i].width=Math.sqrt(sqr((dots[i+1].y-dots[i].y)*yUnit)+sqr((dots[i+1].x-dots[i].x)*xUnit));
}

The access is intuitive (dots[i].x and dots[i].y) and prevents the need for 2 arrays. You should also note that the encapsulation which results from this relatively simple optimization is a huge helper when debugging :)

OOP for Javascript - how to use in a gadget (Advanced stuff)

Combobox
Figure 12: Combobox created after OOP principles

The controls from the Google Desktop Gadget API (<button>, <img>, etc.) are object oriented - they reflect all the principles detailed in previous sections of the article. I also made a control of my own, having those principles in mind: a combobox. You can include it (freely) in your gadget simply by unzipping this archive into your build directory and including the script inside it.

First, we have to figure out what the targeted behaviour will be. In the case of my combobox, i wanted to be able to do the following in the main.js file:

var a=new Array(3);
a[0]="element0";a[1]="element1";a[2]="element2";

function testClick(x){
	//alert(c.getValue());
}

//creating the combobox
c=new ComboBox(view,50,50,200,3,"testClick",a);

//setting a value
c.setValue("element1");

//self-destruct after 20 seconds
setTimeOut("c=c.destroy();",20000);

Let's see what this snippet of code does. An array is created to have something to work with. After that, we define a function which we want to be launched when the onClick or onChange event is triggered. We then instantiate a combobox into the c variable, using the constructor which has this prototype: ComboBox(parent,x,y,width,maximumNumberOfElementsShown,onClickFunctionToBeTriggeredWrittenAsAString,itemArray); each parameter's meaning is pretty obvious - just notice the flexibility of the object due to the parent parameter. For example, if we want to create the combobox in a <div>, not directly in the <view>, we just write the name of that <div> as the first parameter in the constructor.

We have also have a setValue() method and a getValue function, as well as a destructor function: c.destroy(); we can call it a function because it returns the null pointer. So to empty the c reference we can actually write: c=c.destroy();

But how do we do all this? Well, let's take it one step at a time. We've seen how to simulate attributes (using the object called this) and fully-functional constructors (by writing code in the actual function body). To create methods inside the class, we use similar code; we just have to define them, like this:

this.setValue=setValue;

function setValue(s){
	this.value=s;
	CBedit.value=s;
}

You can include parameters and return objects or values just like you would if you weren't using classes. Basically, we have now covered everything that we need to do; to gain perspective, here's a general look on the ComboBox class:

function ComboBox(parent,x,y,width,numberOfDisplayedItems,onClickFunction,newArray){
	//some variables, not important for our example
	var CBbutton;var auxCBarray=new Array(); var actualNumberOfElements=0;var CBcontentDIV;var CBshape;

	//CONSTRUCTOR
	construct();
	function construct(){
		this.value="";
		//...
		//adding UI elements, calculating positions, etc.
	}
	
	//PUBLIC
	this.setValue=setValue;
	function setValue(s){
		this.value=s;CBedit.value=s;
	}

	//PUBLIC
	this.getValue=getValue;
	function getValue(){
		return (CBedit.value);
	}

	//PUBLIC (DESTRUCTOR)
	this.destroy=destroy;
	function destroy(){
		parent.removeElement(anotherReferenceToCBcontentDIV);
		parent.removeElement(anotherReferencetoCBedit);
		parent.removeElement(anotherReferencetoCBbutton);
		parent.removeElement(AnotherReferencetoCBShape);
		return null;
	}

	//...
}

Here are some helpful tips about OOP in Javascript:

Conclusion

That's probably a long article, but we've gone through everything from basic OOP principles to practical uses. We have learned the potential of an object and of interactions between objects, with samples and tricks in every section of the article. Object Oriented Programming should be studied and exploited by every developer, and we've seen why gadget developers should make no exception :)

Many gadgets, everyone!

Resources


Author Bio

Teodor Filimon

I'm a natural born programmer. My first contact with a techno-gadget was Star Trek (remember those cool sensors?). I used to fill up a whole room with drawings of them when I was only 3 years old. Generally, I find a lot of inspiration for intuitive interfaces in things with "star" in their names (like Star Wars, Stargate,... :-) . I like the border between interface and function—it's the essence of a program, I think. Anyway, I'm a software engineering student now, and you can learn more about me and what I'm thinking and doing at my website or blog. My most popular gadgets are DigiWatch and TV Set.