Friday, 23 January 2009

Chunk 8 - Finished

OK - here is the completed Chunk 8.

Feel free to pass comment on it.
Note: the chunk below is not formatted as I have written it in Word, and as such does not visually look very good.



An Introduction to Assignment Statements

If you are new to programming you may be wondering what are Assignment Statements? I should hope so too. If you are a seasoned veteran (or even a relative newbie) you may well (or I should say I would hope) already be familiar with the concept of assignments and it would probably be safe to skip this chunk.

OK so what exactly are assignment statements? Good question. The answer is that an assignment statement takes a value or the result of a calculation and assigns it to a variable. Basically we give it a name. Get the idea? Great! Now move onto the next chapter…Not really, please read on.

The assignment operator is the = (equals) symbol and takes the general form of:

variable = value, expression OR return value of a function

In the context of Java and Processing you would also include a terminating semi-colon at the end of the declaration. But know this already, right?

I would hope by now that you are familiar with the concept of variables. Variables can be likened to pigeon holes in an internal snail mail system, where each employee or department (or whatever) has a pigeon hole in which mail is placed. Essentially the pigeon hole represents the variable (since it can hold…well whatever) and the items placed in the pigeon hole represent the value or expression. The physical act of placing the “whatever” in the pigeon hole is representative of the assignment operator =.

Important note: In Java (and Processing) the assignment operator = should not be confused with the equality (AKA relational) operator == (equals equals). The assignment operator assigns the value on the right of the = to the variable on the left, whereas the equality operator looks to see if two things are the same (see example below).

= and == in action

// using the assignment operator
// declare a variable (day) of type integer (int) and assign the value 5
int day = 5;

// using the equality (relational) operator
// check and see if day is equal to 7
if (day == 7) {
// do something here if day is equal to 7
}

The if statement is covered in depth elsewhere in this book.

In the example above I am using day to store a number (an integer to be exact) but what would happen if I tried to assign the word “Friday” to day. Can you guess?

Hopefully you guessed that this wouldn’t work and the Processing IDE would produce an error. Why? Well we have declared that day can ONLY hold numbers that fall within the range of integers (whole numbers that are in the range –2,147,483,648 à 2,147,483,647). The compiler has detected this mistake and halted compilation. Details of this can be found elsewhere in this book. Suffice to say that the compiler has detected and halted a potentially serious mistake. How cool is that?

Variables can be typecast to be any one of a number of types, including (but not limited to) int, float, char and Boolean. Again details of these can be found elsewhere, but it is worth noting as will (probably) save you hours of error checking for those little insidious mistakes we all make.



A Simple Example

We are now going to construct a simple program which utilises assignments and draws a (very pretty) picture of a (sort of) house.

Hopefully the final output will look like the image to the right:



















I never said I was a talented Architect now did I?

First thing to do is load the Processing IDE and enter the following lines of code into text editing window. We will build the code step by step and at each step you need only enter the lines in bold.

First Stage:
/*
Title: Understanding the assignment operator
Description: My Dream Home
Created: 16th December 2008
Author: Bryan Clifton
*/

// Setup our sketch window and assign a background colour
size (300,300);
background (255);

In the code above all we have done is to setup a small sketch window (300 by 300 pixels in size) and made the background colour white, so nothing particularly exciting is going to happen yet.

In the second stage we will create some variables, assign them values and draw a rather lovely green garden using the rectangle function and just for the fun of it have a bright yellow sun.

Second Stage:
/*
Title: Understanding the assignment operator
Description: My Dream Home
Created: 16th December 2008
Author: Bryan Clifton
*/

// Create some variables and assign values
int xpos;
int ypos;

// Setup our sketch window and assign a background colour
size (300,300);
background (255);

xpos = 0;
ypos = 200; // 1/3 of the sketch window

// Turn off the stroke rendering, as in don’t draw a border
// then draw a green rectangle that fills the lower third of the
// sketch window
noStroke ();
fill(0,128,64);
rect (xpos, ypos, 300, 100);

// Draw a sun in the sky
ypos = ypos - 150;
xpos = 250;
fill (255, 255, 0);
ellipse (xpos, ypos, 50, 50);

So far so beautiful, the perfect scenery!

Can you see some examples of the assignment operator in action? Initially we assign the value of 0 (zero) to xpos and 200 to ypos. Once we have used these to draw the rectangle (strictly speaking we DON’T need to – we could just use the values directly), we modify the value of ypos by subtracting 150 from it in the assignment statement:

ypos = ypos - 150;

This statement simply instructs the program to subtract 150 from whatever value is currently held in ypos. In addition, we reset the value held in xpos to 250.


You may have noticed the fill(…) statement used several times; what does this do? It sets the colour that is to be used during (in this instance) the drawing of the ellipse and rectangle statements; in the case of the ellipsis it sets the colour to a bright yellow using the RGB figures of 255, 255 and 0. A description of RGB (Red, Green and Blue) is beyond the scope of this chunk.

Third Stage:

Add the following lines to the bottom of the code listing (after the draw the sun section)

// Now draw our dream home
xpos = 75;
ypos = 100;
stroke (0); // set the border colour of the house
fill (192, 192, 192); // set the fill colour of the house
rect (xpos, ypos, 100, 100);

// with a roof
fill (128, 128, 64); // light brown - sort of
beginShape (TRIANGLES);
vertex (xpos, ypos);
vertex (xpos + 100, ypos);
vertex (xpos + 50, ypos - 50);
endShape();

// and some windows
fill (255, 255, 255); // white
rect (xpos + 10, ypos + 10, 25, 25);
rect (xpos + 65, ypos + 10, 25, 25);
rect (xpos + 10, ypos + 65, 25, 25);

// and a door
fill (0, 128, 255);
rect (xpos + 65, ypos + 65, 25, 35);

In order to draw our house we reassign the values of xpos and ypos (xpos = 75 and ypos = 100); strictly speaking in this simple example this is unnecessary coding overhead and later in this tome you will learn more about assignment operators and their usage. You may also have noticed that in several places I have used code that looks like:

rect (xpos + 10, ypos + 10, 25, 25)

and wondered what was going on. You may think that this is an assignment operation, but it is not. Although I have used the calculation (for instance) xpos + 10, this does not permanently effect the value of xpos; i.e. it calculates the value of xpos + 10 and returns it, but does not change the value of xpos! For instance if xpos currently held the value 10 then even after the calculation xpos + 10 it still holds the value 10 because we have not explicitly said change the value of xpos.

Again there are several functions in this listing which will be covered elsewhere in the book; namely beginShape();/endShape(); and vertex(…); Suffice to say that this block of code draws a triangle representing our dream houses’ roof.

Once you have entered and executed this code you should see an image similar to that shown in the simple example above – a dream home!

Hopefully you now understand the assignment operator and in addition its difference to the equality (relational) operator, and you should now be able to describe the effect of a simple assignment operator.
A Slightly Less Simple Example

To reinforce what you have studied above we will now create a slightly more complex example which will re-create our perfect dream home but in somewhat more detail.

We are going to make the following modifications to our dream home (feel free to make others if my idea of a dream home is different to yours!):

A chimney (to keep it simple we won’t be doing complex calculations at all – in fact we will cheat a little to achieve our desired effect!);

add a shed (you got to keep the mower somewhere);
add a path to the front door;
a fish pond.

I intend to present the code as a whole; this will be the code developed above with the extra lines shown in bold and then a short discussion afterwards.

Hopefully our completed and very special new abode will look like the house below.



















Important note to self: I really must take some home design courses!

/* Title: Understanding the assignment operator
Description: My Dream Home With Extension and Fish Pond
Created: 16th December 2008
Author: Bryan Clifton
*/

1) // Create some variables and assign values
2) int xpos;
3) int ypos;
4) int fishpondLeft;
5) int fishpondTop;
6) int fishpondWidth;
7) int fishpondHeight;
8)
9) // Setup our sketch window and assign a background colour
10) size (300,300);
11) background (255);
12)
13) xpos = 0;
14) ypos = 200; // 1/3 of the sketch window
15)
16) // Turn off the stroke rendering, as in don’t draw a border
17) // then draw a green rectangle that fills the lower third of the
18) // sketch window
19) noStroke ();
20) fill(0, 128, 64);
21) rect (xpos, ypos, 300, 100);
22)
23) // Draw a sun in the sky
24) ypos = ypos - 150;
25) xpos = 250;
26) fill (255, 255, 0);
27) ellipse (xpos, ypos, 50, 50);
28)
29) // Now draw our dream home
30) xpos = 75;
31) ypos = 100;
32) stroke (0); // set the border colour of the house
33) fill (192, 192, 192); // set the fill colour of the house
34) rect (xpos, ypos, 100, 100);
35)
36) // we are gonna cheat a little so
37) // we will draw the chimney before the roof
38) xpos = xpos + 75;
39) fill (64, 0, 0); // light brown - sort of
40) rect (xpos, ypos - 40, 15, 40);
41) rect (xpos + 5, ypos - 45, 5, 5);
42)
43) // with a roof
44) xpos = xpos - 75;
45) fill (128, 128, 64); // light brown - sort of
46) // don’t worry too much about this bit
47) // suffice to say it draws a triangle
48) beginShape (TRIANGLES);
49) vertex (xpos, ypos);
50) vertex (xpos + 100, ypos);
51) vertex (xpos + 50, ypos - 50);
52) endShape();
53)
54) // and some windows
55) fill (255, 255, 255); // white
56) rect (xpos + 10, ypos + 10, 25, 25);
57) rect (xpos + 65, ypos + 10, 25, 25);
58) rect (xpos + 10, ypos + 65, 25, 25);
59)
60) // with crosses to represent the frames
61) xpos = xpos + 10;
62) ypos = ypos + 10;
63) // first window
64) line (xpos + 13, ypos, xpos + 13, ypos + 25);
65) line (xpos, ypos + 13, xpos + 25, ypos + 13);
66) // second window
67) xpos = xpos + 55;
68) line (xpos + 13, ypos, xpos + 13, ypos + 25);
69) line (xpos, ypos + 13, xpos + 25, ypos + 13);
70) // third window
71) xpos = xpos - 55;
72) ypos = ypos + 55;
73) line (xpos + 13, ypos, xpos + 13, ypos + 25);
74) line (xpos, ypos + 13, xpos + 25, ypos + 13);
75)
76) // and a door
77) xpos = xpos + 55;
78) fill (0, 128, 255);
79) rect (xpos, ypos, 25, 35);
80)
81) // and a window in the door
82) fill (255, 0, 0); // Red
83) rect (xpos + 3, ypos + 3, 19, 19);
84)
85) // with a path
86) ypos = ypos + 36;
87) fill (106, 106, 106);
88) // smooth the lines out so they are less jagged
89) // this technique is known as anti-aliasing
90) smooth ();
91) beginShape ();
92) vertex (xpos, ypos);
93) vertex (xpos - 9, ypos + 100);
94) vertex (xpos + 34, ypos + 100);
95) vertex (xpos + 25, ypos);
96) endShape ();
97)
98) // draw a fish pond
99) fishpondLeft = xpos - 80;
100) fishpondTop = ypos + 40;
101) fishpondWidth = 50;
102) fishpondHeight = 25;
103) fill (0, 0, 255);
104) ellipse (fishpondLeft, fishpondTop, fishpondWidth, fishpondHeight);
105)
106) // now for the shed
107) fill (128, 64, 0);
108) ypos = ypos - 31;
109) xpos = xpos + 35;
110) rect (xpos, ypos, 30, 30);
111) beginShape (TRIANGLES);
112) vertex (xpos, ypos);
113) vertex (xpos + 30, ypos);
114) vertex (xpos, ypos - 20);
115) endShape();

I hope that you now understand the primary concept that this chapter is about; and that is the use of assignment operators. I have shown two methods of using variables and performing (very) basic operations on them:

With an assignment operator:

x = x + 1; In this situation x is assigned the value of itself, with 1 (one) added on;

In-line calculation: line (x, y, x + 10, y + 10); In this situation we reference the variables (x and y), take whatever their value is and add 10 (in this example) to them. This does not have any effect on the value currently held in x and y. If x was equal to 10 (for instance) it still is equal to 10.

Essentially, in my opinion, this is very badly written code! So why did we write it like this? A very good question! Basically it was to demonstrate some very simple assignment operators and that is all! You will have the pleasure of more complex examples later in the book. Although the term more complex is somewhat relative in that the only additional complexity involved in assignment operators is the code that appears on the right hand side of the equals!

For the most part the assignment operators in this example are fairly pointless. Why? Because with this very simple example everything could be drawn by directly referencing points on the sketch surface, rather than assigning values to variables and using these instead. To a certain degree this improves the way the code reads but it is still overkill.



Summary

In this chapter we have taken a cursory glance at the use of assignment operators; essentially giving a name (left hand side of the equals) to a value, result of a calculation or the return value of a function (right hand side of the equals).

The name of the variable can be reused over and over again provided that what you are assigning it is of the right type. For instance you couldn’t assign the value ‘Processing’ to a variable which has been typecast as an integer.

You have also learnt how to differentiate between the assignment operator and the equality (AKA relational) operator. The former meaning assign a given value to a variable, the latter saying “is one thing equal to the other”.



Tuesday, 16 December 2008

Finished - onward and upward!

Having now finished Chunk 59 I am going to (hopefully) have a crack at Chunk 8. Unless anybody else has dibs on it.

Onwards and upwards.

Wednesday, 10 December 2008

My Finished Chunk 59


I have now finished my chunk and here it is.

If you have any suggestions/comments please feel free to post them.







An Introduction to Object Oriented Programming (OOP)

What is OOP?

Traditional programming languages, such as Pascal, COBOL, C and Visual Basic (amongst others) are procedural languages. In a procedural language you develop the code in a linear format, like a shopping list for example. You define your function and procedures in terms of (essentially) a list of instructions, building libraries of functions and procedures that perform specific tasks which allows you (the programmer) to modularise your code.

OOP uses a different paradigm and introduces a whole new plethora of terminology and we will only cover a few of these terms here. The three main terms we will become familiar with are class, method and message. However, we will also discuss properties, instances and inheritance. A few other terms will popup but will only be discussed in very basic detail.

OOP uses the concept of objects that describe “real world” things such as a person, an animal or a shape such as a square. It still employs procedures and functions but these are now called methods (more on this later). In procedural programming you have variables which allow for such things as counting and storage of data, in OOP these are now termed properties (again more on this later). When a function or procedure was called you would issue a command such as foo(some argument [,maybe some more arguments]). In OOP you achieve similar goals by issuing messages to the object.

When an object is created from a class (more shortly) you can pass messages to it, the object can perform calculations and pass messages back which can be processed by other objects. A properly programmed class will know (also known as anthropomorphism) about itself. For instance, a class created to store the details of a person may have the facility to answer how tall it is; i.e. it knows its own height (this is something of an oversimplification; the object has to be told its height in the first place – but I hope you get the gist)!

To interact with the object and call its functions and access it properties you use the objects interface. The interface defines all publicly accessible methods and properties of the class. As with procedural languages where you can create libraries of functions and procedures, you may also create libraries of classes that can be used in different programming projects.

Why would we use classes? Once a class is developed and tested it can be used in many different projects. OOP allows inheritance so if additional requirements are specified the class can be extended and new functionality added without modification to the original class. What does this achieve? Less bugs and a high reusability factor!

The purpose of this short tutorial is to explain various basic concepts of classes with no reference to actual code, be it Java or otherwise. Be rest assured that if you do not understand these terms already that they will be covered in greater detail shortly.


What is a Class?

When programming in OOP you begin by creating a description of the object, this is known as a class and this can be likened to a blueprint that describes everything about the object to be created and contains all the necessary functioning components (i.e. methods and properties) to make the object work. However, classes cannot be directly worked with and instances of the class (discussed later) need to be created.

A very simplistic example could be that of a cookie cutter (no OOP terminology here I really mean a real life cookie cutting implement!). The cookie cutter itself represents the class definition (the shape of a car, or animal, for example), and the resultant piece of cookie dough being an instance of the class. In one sense the act of cooking the dough could be considered a message and condition of the dough could be considered a property (cooked or uncooked); sending the message you are being cooked could change the property from uncooked to cooked!

The class definition can also be used to define and enforce business rules, or rules in general that apply. For instance, if you had a class defining a person, then a rule could be that the persons age must be greater than 0 (zero) or their gender must be male or female.

As previously mentioned a class has an interface. The interface describes how the class’s instances and method’s may be accessed. For instance (excuse the pun!), when creating the Person class you may well define a property which describes the date of birth of the person, dateofbirth, in addition you would define methods (described shortly) that allow the users of the class to both get and set the value of this property, for instance setDob and getDob. The setDob and getDob methods are part of the interface of the class.



Figure 1: Class defining a person


Figure 1 represents the relationship between a class and an object. The “blueprint” image to the left represents the class, which encapsulates all the properties and methods (the interface) of that class, and the figures to the right represent several objects created from the class.

Remember – you can create more than one object from a class.

The actual techniques used to implement classes are discussed in detail in Chunk 60 and 61.
What is a Method?

Methods are the means by which a class can perform tasks. A method is essentially the same as a function or procedure in a procedural language. However, depending on how the method is defined within the class it may or may not be a visible part of the interface (which is beyond the scope of this basic tutorial). Suffice to say that not all methods are accessible to the calling object.
For instance, given the above somewhat simplistic class defining a person, we have a setDob and getDob method which allows the date of birth of the person to be defined and accessed.

What about calculating the age of the person?

We could of course call the getDob method and calculate it manually, but what about a method to calculate and return the person’s age? We could create a method within the class that calculates and returns the person’s age. Perhaps call it getage(). When this method is called it simply calculates the age based on the system clock (or some other influence) and the date of birth stored within the object; passing the result back to the calling object.

One of the important advantages to remember about objects created from a class is that the methods are also created. They are not shared amongst all the objects; each object has its own copy. So for instance if two objects of type people are created and the getage() method is invoked it will return the value relevant to the object it is called upon.

There are exceptions to this rule but that is beyond the scope of this chunk. An in depth discussion of methods and their implementation can be found in Chunks 63 and 64.


What is a Message?

We have methods that are defined in our class and instantiated as part of an object. But how do we use these methods?

As stated previously methods are essentially the same as functions and procedures in procedural programming. However, whereas in procedural programming you would simply call the function/procedure with arguments (if any), in OOP you pass the object a message which may or may not contain arguments (obviously dependant on the definition of the method).

Essentially this is the same as procedural programming. Generally you would use the dot notation to pass the message; i.e. if you have a class named person, from which you have created an object named teamLeader, and a method called setDob which takes an argument of the form date then the calling message would be something like:

teamLeader.setDob(“27/10/1970”)

Objects can also return data to the calling object. Using the teamLeader example if we wanted to return the teamLeader’s age we would use a message of the form:

age = teamLeader.getAge()

Obviously the actual syntax involved would be language specific and this is only a very general description.

Having now covered three of the fundamentals of OOP, class, method and message, we will now move on to cover several other topics, namely properties, instances and inheritance.


Properties

Properties are very much akin to variables in traditional non OOP programming languages. A property can be likened to a “pigeon” hole in a snail-mail system; something is deposited in to the pigeon hole for later access and processing. That something could be a parcel, a letter or a memo for example. Parcel, letter and memo represent examples of different types of properties.
In computing terms properties can take the form of (for example) integers, characters and strings. There are many others to choose from and the type of property chosen obviously depends on the purpose of the property; you wouldn’t have a property that holds a name declared as an integer for instance, this would most likely be a string.

The various types that are available to define the type of property are beyond the scope of this short tutorial and I just want you to appreciate that there are different types to choose from and that careful thought should be given in choosing a type.

Generally speaking when defining a property in a class there would be (at least) two methods of accessing this property and this property would be declared as private (it can’t be seen outside of the class); there would be a get method for accessing the content of the property and a set method for assigning values to the property (these provide a public interface to a private property). Together the get and set methods are known as the accessor pair. This technique also allows you to enforce rules on what can (and can’t) be done with the property.

The syntax for creating properties and techniques involved in using them is covered elsewhere in this book.


Instances

Where we have a class that defines the object to BE created (remember we can’t work on a class directly), the term instance is used to describe the object once it has been created at runtime.

For instance, the simplistic class discussed above describes how the class is constructed in terms of attributes and methods but cannot be worked on directly. You have to create an instance of the class to work on; this is known as instantiation and gives us the object.
Inheritance

Inheritance can be a difficult topic to understand, and hopefully this very simple introduction will assist in clearing the mud from the waters.

The somewhat simplistic class introduced earlier has many attributes missing in relation to defining the properties of a person. For instance, what do ALL people share in common? One important thing would be that of gender; is the person a male or a female (there is a third option androgynous but let’s not go there!).

Admittedly this property would probably have been encapsulated within the Person class had it been properly designed, but for the sake of argument let’s assume it wasn’t a requirement of the original class structure.

The actual implementation details of inheritance are language specific; i.e. each language has its own method of achieving inheritance and I have no intention of detailing any specific method here.

When you as the programmer create a class that is based on another class you are said to inherit the properties and behaviours of the parent class and the class you create is known as a sub-class. This sub-class not only takes on all the functionality of the parent class, but can actually introduce additional properties and behaviour thus extending the class’ capability. Depending on how the parent class is defined it may even be possible to replace the methods (known as overriding) in the parent class (or extend them) in your child class.

So, given the Person class above we could create a sub-class that inherits from Person and maybe call it EnhancedPerson. In this sub-class we could then define a property to hold the gender of the person and create a matching pair of get and set methods to allow access to this property; maybe call them setGender() and getGender().

Can we inherit from multiple classes?

It is possible, with some languages, to perform multiple inheritance; inheriting from more than one class to create a sub-class. However, this tends to be frowned upon as implementation can be difficult and problematic, as can use of the class that has been created via multiple inheritance. I am not going to say anymore about this other than it exists.

What are the advantages of inheritance in OOP?

Code sharing, reduction in bugs in the code and reduced complexity to name some. If a class is sufficiently similar enough to an existing one, then inheritance allows the possibility of extension and modification (not directly – but by the child-class) to allow re-usability.

Assuming the base class has been thoroughly tested, you can be (almost) guaranteed a consistent behaviour, in that you will know what to expect of the called method.

Rapid Application Development (RAD) is another prime example of an advantage. Let’s say you develop software applications that have a similar theme and you seem to always be developing the same code over and over (say code to handle the details of a person). By creating a class that provides the necessary functionality, the code will have been developed and (hopefully) tested, and can be distributed to other programmers for their use, thus saving them development time and reducing development cost.

There are other valid advantages of OOP development but I hope this gives you an appreciation of OOP.

Because we have a taken a cursory glance at the positive sides of OOP, are their any negative aspects (I like playing Devil’s advocate!)?

Some do consider that execution speed of the program can take a hit when OOP techniques are used. In part due to the class specific code being more general purpose than the derived class’s code which is probably more specific and refined. However, using the OOP techniques (to reduce complexity) combined with optimisation techniques (to highlight bottlenecks in the code) can alleviate these concerns.

It is possible that applications developed using OOP may contain more lines of code than if they were developed using procedural techniques. However, due to the cheap (relatively speaking) nature of hardware and specifically RAM these days, application size is less important. Although I would like to add at this point that I still believe that developing tight code which uses less memory is very important. Otherwise we end up with what is commonly referred to as bloatware! In monetary terms though, development in OOP is more than likely a lot cheaper than development in a procedural language.

Overuse of inheritance can create a complex and highly daunting hierarchy of classes. The class structure can become so complex and cumbersome it can be difficult to see what derives from where and finding the relevant required class becomes very difficult.
More examples

To reinforce your understanding of the concepts explained above I would now like you to think about something that you understand that is not a computer program and how you would model this thing in OOP terms (my example will be a bread toaster). When you have a couple of ideas (you can use my own idea if you wish) of what you would like to model and what you think their properties and methods would be, come back and take a look at my example.

Carry on reading when you have thought about this some more.
This table represents my initial thoughts on what properties and methods (representing the interface) would be required to model a toaster in OOP. It may not be exhaustive or indeed accurate and would undoubtedly require additional design considerations before being implemented.

OOP Example


Toaster class:


Properties:


Temperature
Time before ejecting bread
Is bread inserted
Overheating
Turned on/off


Methods (Interface) :


Insert bread
Remove toast
Lower bread
Eject toast
Change temperature
Change ejection time
Switch toaster on/off
Is toaster overheating


Note: The names used above for the properties and methods are for illustration purposes only.

How did I come up with this list? Initially I sat and thought about how you use a toaster and the controls that are on a toasting machine. But there’s more to it than that. Toasters have sensors to (hopefully) prevent the toast from being burnt (after all who likes burnt toast?) and temperature control, etc.

So I figured for a (basic) toaster you need properties that represent when the toaster is turned on or off, its current temperature, is there any bread inserted, how long to cook the bread for before ejecting and whether the toaster is overheating. You may well think of some more but I feel that’s enough for illustrative purposes.

From an interface point of view I initially came up with the methods listed in the table above, you may well come up with some more. Again, thinking about how a toaster works (in the practical sense) provided an idea of potential methods. We would need methods to control the input and output of the toaster (Insert Bread, Eject toast, etc.) and methods to control the state of the toaster (Change temperature, Change ejection time, Is toaster overheating, etc.).

Try and come up with some other examples; for instance think about an ATM (cash machine) and what properties and methods that would require, or perhaps model a car thinking about what properties may be involved (for instance temperature, fuel level, etc.) and methods (accelerator pedal, break pedal, etc.).


Summary

Object Oriented Programming provides a rich and powerful way to develop software. It has many advantages over the traditional procedural methodology; it can also come at a cost if proper design and development is not adhered to.

Despite any negative aspects of OOP, it is a powerful method of software development and well worth learning. I hope this basic discussion has given you an insight into OOP which has convinced you that this is the way forward in software development. At least until the next major software development paradigm is discovered.

One last very important piece of advice on this topic – enjoy it!

Tuesday, 25 November 2008

My 2500 words

Right then - I have written my 2500 words but do not know whether it is of acceptable quality, over detailed or even under detailed and would appreciate some feedback.

Please ignore the graphic - my graphic designer friend is letting me down so I cobbled something together. I hope to improve it (or replace if he gets his act together), or failing that I will rewrite that small section and remove the image.

Please be kind.




An Introduction to Object Oriented Programming (OOP)


What is OOP?

Traditional programming languages, such as Pascal, COBOL, C and Visual Basic (amongst others) are procedural languages. In a procedural language you develop the code in a linear format, like a shopping list for example. You define your function and procedures in terms of (essentially) a list of instructions, building libraries of functions and procedures that perform specific tasks which allows you (the programmer) to modularise your code.

OOP uses a different paradigm and introduces a whole new plethora of terminology and we will only cover a few of these terms here. The three main terms we will become familiar with are class, method and message. However, we will also discuss properties, instances and inheritance. A few other terms will popup but will only be discussed in very basic detail.

OOP uses the concept of objects that describe “real world” things such as a person, an animal or a shape such as a square. It still employs procedures and functions but these are now called methods (more on this later). In procedural programming you have variables which allow for such things as counting and storage of data, in OOP these are now termed properties (again more on this later). When a function or procedure was called you would issue a command such as foo(some argument [,maybe some more arguments]). In OOP you achieve similar goals by issuing messages to the object.

When an object is created from a class (more shortly) you can pass messages to it, the object can perform calculations and pass messages back which can be processed by other objects. A properly programmed class will know (also known as anthropomorphism) about itself. For instance, a class created to store the details of a person may have the facility to answer how tall it is; i.e. it knows its own height (this is something of an oversimplification; the object has to be told its height in the first place – but I hope you get the gist)!

To interact with the object and call its functions and access it properties you use the objects interface. The interface defines all publicly accessible methods and properties of the class. As with procedural languages where you can create libraries of functions and procedures, you may also create libraries of classes that can be used in different programming projects.

Why would we use classes? Once a class is developed and tested it can be used in many different projects. OOP allows inheritance so if additional requirements are required the class can be extended and new functionality added without modification to the original class. What does this achieve? Less bugs and a high reusability factor!

The purpose of this short tutorial is to explain various basic concepts of classes with no reference to actual code, be it Java or otherwise.

What is a Class?

When programming in OOP you begin by creating a description of the object, this is known as a class and this can be likened to a blueprint that describes everything about the object to be created and contains all the necessary functioning components (i.e. methods and properties) to make the object work. However, classes cannot be directly worked with and instances of the class (discussed later) need to be created.

The class definition can also be used to define and enforce business rules, or rules in general that apply. For instance, if you had a class defining a person, then a rule could be that the persons age must be greater than 0 (zero) or their gender must be male or female.

As previously mentioned a class has an interface. The interface describes how the class’s instances and method’s may be accessed. For instance (excuse the pun!), when creating the Person class you may well define a property which describes the date of birth of the person, dateofbirth, in addition you would define methods (described shortly) that allow the users of the class to both get and set the value of this property, for instance setDob and getDob. The setDob and getDob methods are part of the interface of the class.

Figure 1 represents the relationship between a class and an object.




Figure 1: Class defining a person

The “blueprint” image to the left represents the class, which encapsulates all the properties and methods (the interface) of the class, and the image to the right represents an instantiation of the class, i.e. an object created from the class.

The actual techniques used to implement classes are discussed in detail in Chunk 60 and 61.

What is a Method?

Methods are the means by which a class can perform tasks. A method is essentially the same as a function or procedure in a procedural language. However, depending on how the method is defined within the class it may or may not be a visible part of the interface (which is beyond the scope of this basic tutorial). Suffice to say that not all methods are accessible to the calling object.
For instance, given the above somewhat simplistic class defining a person, we have a setDob and getDob method which allows the date of birth of the person to be defined and accessed.

What about calculating the age of the person?

We could of course call the getDob method and calculate it manually, but what about a method to calculate and return the person’s age? We could create a method within the class that calculates and returns the person’s age. Perhaps call it getage(). When this method is called it simply calculates the age based on the system clock (or some other influence) and the date of birth stored within the object. Passing the result back to the calling object.

One of the important advantages to remember about objects created from a class is that the methods are also created. They are not shared amongst all the objects; each object has its own copy. So for instance if two objects of type people are created and the getage() method is invoked it will return the value relevant to the object it is called upon.

There are exceptions to this rule but that is beyond the scope of this chunk. An in depth discussion of methods and their implementation can be found in Chunks 63 and 64.

What is a Message?

We have methods that are defined in our class and instantiated as part of an object. But how do we use these methods?

As stated previously methods are essentially the same as functions and procedures in procedural programming. However, whereas in procedural programming you would simply call the function/procedure with arguments (if any), in OOP you pass the object a message which may or may not contain arguments (obviously dependant on the definition of the method).

Essentially this is the same as procedural programming. Generally you would use the dot notation to pass the message; i.e. if you have a class named person, from which you have created an object named teamLeader, and a method called setDob which takes an argument of the form date then the calling message would be something like:

teamLeader.setDob(“27/10/1970”)

Objects can also return data to the calling object. Using the teamLeader example if we wanted to return the teamLeader’s age we would use a message of the form:

age = teamLeader.getAge()

Obviously the actual syntax involved would be language specific and this is only a very general description.

Having now covered three of the fundamentals of OOP, class, method and message, we will now move on to cover several other topics, namely properties, instances and inheritance.

Properties

Properties are very much akin to variables in traditional non OOP programming languages. A property can be likened to a “pigeon” hole in a snail-mail system; something is deposited in to the pigeon hole for later access and processing. That something could be a parcel, a letter or a memo for example. Parcel, letter and memo represent examples of different types of properties.
In computing terms properties can take the form of (for example) integers, characters and strings. There are many others to choose from and the type of property chosen obviously depends on the purpose of the property; you wouldn’t have a property that holds a name declared as an integer for instance, this would most likely be a string.

The various types that are available to define the type of property are beyond the scope of this short tutorial and I just want you to appreciate that there are different types to choose from and that careful thought should be given in choosing a type.

Generally speaking when defining a property in a class there would be (at least) two methods of accessing this property and this property would be declared as private (it can’t be seen outside of the class); there would be a get method for accessing the content of the property and a set method for assigning values to the property (these provide a public interface to a private property). Together the get and set methods are known as the accessor pair. This technique also allows you to enforce rules on what can (and can’t) be done with the property.

The syntax for creating properties and techniques involved in using them is covered elsewhere in this book.

Instances

Where we have a class that defines the object to BE created (remember we can’t work on a class directly), the term instance is used to describe the object once it has been created at runtime.

For instance, the simplistic class discussed above describes how the class is constructed in terms of attributes and methods but cannot be worked on directly. You have to create an instance of the class to work on; this is known as instantiation and gives us the object.
Inheritance

Inheritance can be a difficult topic to understand, and hopefully this very simple introduction will assist in clearing the mud from the waters.

The somewhat simplistic class introduced earlier has many attributes missing in relation to defining the properties of a person. For instance, what do ALL people share in common? One important thing would be that of gender; is the person a male or a female (there is a third option androgynous but let’s not go there!).

Admittedly this property would probably have been encapsulated within the Person class had it been properly designed, but for the sake of argument let’s assume it wasn’t a requirement of the original class structure.

The actual implementation details of inheritance are language specific; i.e. each language has its own method of achieving inheritance and I have no intention of detailing any specific method here.

When you as the programmer create a class that is based on another class you are said to inherit the properties and behaviours of the parent class and the class you create is known as a sub-class. This sub-class not only takes on all the functionality of the parent class, but can actually introduce additional properties and behaviour thus extending the class’ capability. Depending on how the parent class is defined it may even be possible to replace the methods (known as overriding) in the parent class (or extend them) in your child class.

So, given the Person class above we could create a sub-class that inherits from Person and maybe call it EnhancedPerson. In this sub-class we could then define a property to hold the gender of the person and create a matching pair of get and set methods to allow access to this property; maybe call them setGender() and getGender().

Can we inherit from multiple classes?

It is possible, with some languages, to perform multiple inheritance; inheriting from more than one class to create a sub-class. However, this tends to be frowned upon as implementation can be difficult and problematic, as can use of the class that has been created via multiple inheritance. I am not going to say anymore about this other than it exists.

What are the advantages of inheritance in OOP?

Code sharing, reduction in bugs in the code and reduced complexity to name some. If a class is sufficiently similar enough to a newly required one, then inheritance allows the possibility of extension and modification (not directly – but by the child-class) to allow re-usability.

Assuming the base class has been thoroughly tested, you can be (almost) guaranteed a consistent behaviour, in that you will know what to expect of the called method.

Rapid Application Development (RAD) is another prime example of an advantage. Let’s say you develop software applications that have a similar theme and you seem to always be developing the same code over and over (say code to handle the details of a person). By creating a class that provides the necessary functionality, the code will have been developed and (hopefully) tested, and can be distributed to other programmers for their use, thus saving them development time and reducing development cost.

There are other valid advantages of OOP development but I hope this gives you an appreciation of OOP.

Because we have a taken a cursory glance at the positive sides of OOP, are their any negative aspects (I like playing Devil’s advocate!)?

Some do consider that execution speed of the program can take a hit when OOP techniques are used. In part due to the class specific code being more general purpose than the derived class’s code which is probably more specific and refined. However, using the OOP techniques (to reduce complexity) combined with optimisation techniques (to highlight bottlenecks in the code) can alleviate these concerns.

It is possible that applications developed using OOP may contain more lines of code than if they were developed using procedural techniques. However, due to the cheap (relatively speaking) nature of hardware and specifically RAM these days, application size is less important. Although I would like to add at this point that I still believe that developing tight code which uses less memory is very important. Otherwise we end up with what is commonly referred to as bloatware! In monetary terms though, development in OOP is more than likely a lot cheaper than development in a procedural language.

Overuse of inheritance can create a complex and highly daunting hierarchy of classes. The class structure can become so complex and cumbersome it can be difficult to see what derives from where and finding the relevant required class becomes very difficult.

Summary

Object Oriented Programming provides a rich and powerful way to develop software. It has many advantages over the traditional procedural methodology; it can also come at a cost if proper design and development is not adhered to.

Despite any negative aspects of OOP, it is a powerful method of software development and well worth learning. I hope this basic discussion has given you an insight into OOP which has convinced you that this is the way forward in software development. At least until the next major software development paradigm is discovered.

One last very important piece of advice on this topic – enjoy it!

Monday, 10 November 2008

My First 1200(ish) words...

OK - Here is my first 1200(ish) words. Please ignore the graphic (figure 1), it is obviously wrong. I am waiting on my graphic designer friend/colleague to draw me something here.


Please feel free to be critical of the content.


------------------------------------------------------------------------------------


An Introduction to Object Oriented Programming (OOP)

What is OOP?

Traditional programming languages, such as Pascal, COBOL, C and Visual Basic (amongst others) are procedural languages. In a procedural language you develop the code in a linear format, like a shopping list for example. You define your function and procedures in terms of (essentially) a list of instructions, building libraries of functions and procedures that perform specific tasks which allows you (the programmer) to modularise your code. Thus providing the facilities to create libraries of functions for reuse.

OOP uses a different paradigm and introduces a whole new plethora of terminology and we will only cover a few of these terms here. The three main terms we will become familiar with are class, method and message. However, we will also discuss properties, instances and inheritance. A few other terms will popup but will only be discussed in very basic detail.

OOP uses the concept of objects that describe “real world” things such as a person, an animal or a shape such as a square. It still employs procedures and functions but these are now called methods (more on this later). In procedural programming you have variables which allow for such things as counting, in OOP these are now termed properties (again more on this later). When a function or procedure was called you would issue a command such as foo(some argument [,maybe some more arguments]). In OOP you achieve similar goals by issuing messages to the object.

When an object is created from a class (more shortly) you can pass messages to it, the object can perform calculations and pass messages back which can be processed by other objects. A properly programmed class will know (also known as anthropomorphism) about itself. For instance, a class created to store the details of a person may have the facility to answer how tall it is; i.e. it knows its own height!

To interact with the object and call its functions and access it properties you use the objects interface. The interface defines all publicly accessible methods and properties of the class. As with procedural languages where you can create libraries of functions and procedures, you may also create libraries of classes that can be used in different programming projects.

Why would we use classes? Once a class is developed and tested it can be used in many different projects. OOP allows inheritance so if additional requirements are required the class can be extended and new functionality added without modification to the original class. What does this achieve? Less bugs and a high reusability factor!

The purpose of this short tutorial is to explain various basic concepts of classes with no reference to actual code, be it Java or otherwise.

What is a Class?

When programming in OOP you begin by creating a description of the object, this is known as a class and this can be likened to a blueprint that describes everything about the object to be created and contains all the necessary functioning components (i.e. methods and properties) to make the object work. However, classes cannot be directly worked with and instances of the class (discussed later) need to be created.

The class definition can also be used to define and enforce business rules, or rules in general that apply. For instance, if you had a class defining a person, then a rule could be that the persons age must be greater than zero or their gender must be male or female.

As previously mentioned a class has an interface. The interface describes how the class’s instances and method’s may be accessed. For instance (excuse the pun!), when creating the Person class you may well define a property which describes the date of birth of the person, dateofbirth, in addition you would define methods (described shortly) that allow the users of the class to both get and set the value of this property, for instance setDob and getDob. The setDob and getDob methods are part of the interface of the class.

Figure 1 represents the relationship between a class and an object.

Figure 1: Class defining a person


The “blueprint” image to the left represents the class, which encapsulates all the properties and methods (the interface) to class, and the image to the right represents an instantiation of the class, i.e. an object created from the class.

What is a Method?

Methods are the means by which a class can perform tasks. A method is essentially the same as a function or procedure in a procedural language. However, depending on how the method is defined within the class may or may not be a visible part of the interface (which is beyond the scope of this basic tutorial).

For instance, given the above somewhat simplistic class defining a person, we have a setDob and getDob method which allows the date of birth of the person to be defined and accessed. But what about a method allowing you to access the person to age instead of simply retrieving their date of birth?

We could of course call the getDob method and calculate it manually, but what about a method to return the person’s age? We could create a method within the class that calculates and returns the person’s age. Perhaps call it getage(). When this method is called it simply calculates the age based on the system clock and the date of birth stored within the object.

One of the important advantages to remember about objects created from a class is that the methods are also created. They are not shared amongst all the objects; each object has its own copy. So for instance if two objects of type people are created and the getage method is invoked it will return the value relevant to the object it is called upon.

There are exceptions to this rule but that is beyond the scope of this tutorial.

What is a Message?

We have methods that are defined in our class and instantiated as part of an object. But how do we use these methods?

As stated previously methods are essentially the same as functions and procedures in procedural programming. However, whereas in procedural programming you would simply call the function/procedure with arguments (if any), in OOP you pass the object a message which may or may not contain arguments (obviously dependant on the definition of the method).

Essentially this is the same as procedural programming. Generally you would use the dot notation to pass the message; i.e. if you have a class named person, from which you have created an object named teamLeader, and a method called setDob which takes an argument of the form date then the calling message would be something like:

teamLeader.setDob(“27/10/1970”)

Objects can also return data to the call object. Using the teamLeader example if we wanted to return the teamLeader’s age we would use a message of the form:

age = teamLeader.getAge()

Obviously the actual syntax involved would be language specific and this is only a very general description.

Having now covered three of the fundamentals of OOP, class, method and message, we will now move on to cover several other topics, namely properties, instances and inheritance.

At last...

Yay!!!

I have finally had an email off Waterstones to say my book has been dispatched.

Should hopefully have it then by end of the week.

Tuesday, 4 November 2008

My First 500(ish) Words - Please be kind!!

OK - Here are my first 500(ish) words for Chunk 59.

I would appreciate it if everyone could take a look and be constructively critical of it.

-------------------------------------------------------------------------------------------------------

An Introduction to Object Oriented Programming (OOP)

What is OOP?

Traditional programming languages, such as Pascal, COBOL, C and Visual Basic (amongst others) are procedural languages. In a procedural language you develop the code in a linear format, like a shopping list for example. You define your function and procedures in terms of (essentially) a list of instructions, building libraries of functions and procedures that perform specific tasks which allows you (the programmer) to modularise your code. Thus providing the facilities to create libraries of functions for reuse.

OOP uses a different paradigm and introduces a whole new plethora of terminology and we will only cover a few of these terms here. The three main terms we will become familiar with are class, method and message. However, we will also discuss properties, instances and inheritance. A few other terms will popup but will only be discussed in very basic detail.

OOP uses the concept of objects that describe “real world” things such as a person, an animal or a shape such as a square. It still employs procedures and functions but these are now called methods (more on this later). In procedural programming you have variables which allow for such things as counting, in OOP these are now termed properties (again more on this later). When a function or procedure was called you would issue a command such as foo(some argument [,maybe some more arguments]). In OOP you achieve similar goals by issuing messages to the object.

When an object is created from a class (more shortly) you can pass messages to it, the object can perform calculations and pass messages back which can be processed by other objects. A properly programmed class will know (also known as anthropomorphism) about itself. For instance, a class created to store the details of a person may have the facility to answer how tall it is; i.e. it knows its own height!

To interact with the object and call its functions and access it properties you use the objects interface. The interface defines all publicly accessible methods and properties of the class. As with procedural languages where you can create libraries of functions and procedures, you may also create libraries of classes that can be used in different programming projects.

Why would we use classes? Once a class is developed and tested it can be used in many different projects. OOP allows inheritance so if additional requirements are required the class can be extended and new functionality added with modification to the original class. What does this achieve? Less bugs and a high reusability factor!

The purpose of this short tutorial is to explain various basic concepts of classes with no reference to actual code, be it Java or otherwise.