Week 4

Updated on 28 Dec 2018

Writing assignments

When you write a University Assignment, regardless of who writes it or for which unit, the assignment structure remains fairly consistent. That is, for a majority of written assignments you’ll have:

  • an assignment cover sheet
  • title page
  • introduction
  • main content
  • conclusion
  • bibliography

It’s not just the structure that is consistent, but the page layout as well. For example, most written assignments are likely to include the following features within the main content:

  • headers and footers
  • section headings
  • formatting for quoted text

Question:

Do the same principles apply to writing code?

Writing Code

Hungarian Notation A lot of programmer’s get confused by the use of Hungarian notation, however it is merely a part of a coding convention which is still in use today.

There are two types of Hungarian Notation. The original Hungarian Notation, and Systems Hungarian. Systems Hungarian evolved due to a misunderstanding of the original concept and had been spread by Microsoft. Ironically though with the launch of .net, Microsoft are discouraging the use of (systems) Hungarian Notation.

Regardless of whether you abandon Systems Hungarian, you’ll still be using the original Hungarian Notation to some extent whether you know it or not.

Coding Standards is not an exact science, although it can certainly be influenced by what you see in books, on the web or from other peoples’ code.

Questions:

  • Have you started to develop your own coding standards?
  • Why is coding standards important?

Examples that you might see in my code.

//notice the indent after the conditional statement
if(!$logged_in)
  return;

//notice the indent after the for-loop and the begin/end
//keywords on separate lines (all to themselves)
for($i = 0; $i < sizeof($words); $i++)
  {
  $words[$i] = ucfirst($words[$i])
  . . . 
  }

//notice that when the attributes of a HTML tag wrap over
//two lines, the HTML tag always stands out on its own.
<input type="text" name="p_name" 
       maxlength="20" size="20" />

//You’ll notice ‘blank’ lines between different sections 
//of code
case 'angry':
    echo '<p>That is no good.  What\’s wrong?</p>';
break;

case 'so-so':

//Even when I define an array (or any variable).
$myArray = array('S0001234' => 'Smith', 
                 'S0001235' => 'Jones');

Most of the examples shown above concentrated on layout standards. There are also naming conventions that can be defined as well (eg Hungarian).

Notice in my last example I defined an array, and named it myArray. Throughout the code when I use the variable myArray, I know that it is in fact an array.

Internet programming presents its own set of unique circumstances where we can implement naming standards. You should all recognize the following code:

if(isset($_POST['first_name'] && !empty($_POST['first_name']))
  $first_name = $_POST['first_name'];

Question:

Can you think of a naming convention that could identify $first_name as being safe to use for an SQL query, or safe to echo out to the browser?

One goal that you should try to achieve is a coding / naming standard that will really stand out in your code if you write something really silly.

//this is really silly and doesn’t make any sense
$total_price = $first_name * $item_price;

Documentation

These notes predate the use / existance of PHPDocumentor and code editors with an outline window, i.e. the ability to jump from function to function; hence the formatting to make the function definition stand out as you’re scrolling thru the file.

Writing and developing code can be fun. But the fun soon wears off if you have to revisit your code 6 months later to fix a bug or make changes, and you’re spending more time figuring out what the code is doing than actually making the change. It’s even worse if you’re looking at someone else’s code and they don’t have any documentation or understanding of coding standards.

Documentation comes in many flavours. It could be:

  • Word or PDF document (printed or electronic)
  • HTML document with links
  • WinHelp or HTMLHelp application
  • UML Diagrams
  • Programmer comments inside your files.

Questions:

  • Why would documentation be important in a shared programming environment?
  • What about an Audit Trail?
  • Would Documentation also have ‘documentation’ standards?

Documentation Example

The following example shows the very start of a typical PHP script. The documentation shown here is what we call file documentation. That is, the documentation relates to the file as a whole. The next page shows an example of documenting a function.

<?php
#####################################################################
# Filename: config.php
# Location:	../configuration
# Version:  1.00
# Date:     January 2005
# Author:   Brent KNIGGE
# License:  No license available for this software
#
# Description:
# This file is the configuration file for the site.  It starts the
# output buffering, sessions, database connection and contains common
# functions that are used across all pages in this site
#
#####################################################################

if(defined('CONFIG.PHP'))
  return;

define('CONFIG.PHP','CONFIG.PHP');

Questions:

  • Is there any other information that could be included as part of the file documentation?
  • Is there anything that should not be included as part of the file documentation?
  • What do you think the code does, and why is it there?
//*******************************************************************
function CFWordCap($p_text)
//*******************************************************************
{
//-----EXPLANATION START
/*
FILE:
config.php

DECLARATION:
string CFWordCap(string)

DESCRIPTION:
This function takes a string and returns the same string with the start of each word capitialized.

EXAMPLE:
$message = 'Hello this is Mr ed.';
$message = CFWordCap($message);

echo $message;

Output:
Hello This Is Mr Ed.  
*/
//-----EXPLANATION END
                                                            
//-----
//--‘explode’ p_text into an array with a single whitespace as
//--the seperator
//---- 
$wordsArray = explode($p_text, ' ');
//-----

//-----
//--Cycle through each element in the array and capitialise 
//--the first letter of each word!
//-----
for($i = 0; $i < sizeof($wordsArray); $i++)
  $wordsArray[$i] = ucfirst($wordsArray[$i])
//-----

//-----
//--Rejoin the array into a single string, and return back to
//--the user.
//-----
$value = implode(' ', $wordsArray);
return $value;
//-----
}

Stateless Entity

Unlike desktop development, the internet HTTP protocol is a stateless entity. That means when you refresh the page or go to another page, all variable settings are lost! Any user input is also lost.

This type of behaviour can work to our advantage though. Take a look at this example:

if(defined('CONFIG.PHP'))
  return;

define('CONFIG.PHP','CONFIG.PHP');

We are able to include config.php in every webpage because every time we refresh or go to a new page, the definition for the CONFIG.PHP constant is lost! So this is one case where it works for us.

However, the behaviour can work against us in other areas. Here’s an example of where it won’t work very well at all.

if(!$logged_in)
  return;

Question:

What methods are available to have information carry over from one page to another (e.g. $logged_in)?

OOP

Just as procedural programming provided modular design to your code, OOP (Object Orientated Programming) advances the concept of organizational structure via the various programming paradigms available within OOP. The important thing to understand about OOP is that it not only introduces new syntax, but also a new way of solving a problem. Typically it can take many years to fully grasp the concepts of OOP.

Along with new syntax comes new terminology. The two most important are class and object. A class encapsulates data (variables), and methods (functions) that act on that data. An object is an instance of that class, and you can have multiple objects of the same class. For instance I might have an address class, but create one instance (object) of that class for each student.

You could almost relate the concept to functions. You can create a function, but the code within the function doesn’t get executed until you call that function, and you can call the same function multiple times.

Consider these variables:

  • $street_line
  • $suburb
  • $state
  • $postcode

Now consider a function that accepts those variables, and performs some action with them.

function display($street_line, $suburb, $state $postcode);

Even without adding more functions that perform actions on an address, we can see that the structure of our code is going to be somewhat cumbersome. We could also be frustrated because the variables that we are passing around all relate to a common thing, an address, but yet we seem stuck with something that doesn’t quite look right.

Remember that I said a class encapsulates data (variables), and methods (functions) that act on that data? Lets see if we can create more elegant code (using OOP), and in the process learn some new terminology.

Questions:

What other functions might we consider for an ‘Address’ class?

Constructs of a Basic class

class Address
{
private $street_line;
private $suburb;
private $state;
private $postcode;

public function display()
{
echo "<p>$this->street_line<br />
      <strong>$this->suburb $this->state 
              $this->postcode</strong></p>"; 
}

}; //--end of the class (don’t forget the semi-colon)

The above code has introduced 4 new keywords. this, class, private and public. The class keyword denotes a class, and it is used for the definition of the class (similar as you would with a function).

I said ‘an object is an instance of that class, and you can have multiple objects of the same class’. Also recall that the code above is merely a blueprint, so with this in mind hopefully it makes sense that $this points to the current object. So, $this->street_line could be interpreted as ‘with the street_line variable of the current object…’.

Question:

If we had to call a function within the class, would we also need to use $this?

Creating an object

The other two keywords used in the previous code sample are access modifiers, but before we discuss those let’s have a look at how we can use the class.

$myAddress = new Address();
$myAddress->display();

Keep in mind that the class is not very good at the moment because we haven’t provided a means to set the properties (variables), but we do have a working example of how to instantiate a class and invoke one of its methods.

The first line creates an Address object which we put into $myAddress. The second line shows how to invoke a method (function) of that class via the use of the indirection operator ->. Properties can also be accessed via the indirection operator.

Questions:

  • Can we access the properties of this Address class via the indirection operator?
  • Why do I refer to methods and properties?
  • If we used new to create the object, what do we use to ‘delete’ the object?

Access Modifiers

Access modifiers are used on properties and methods. They are used in a class to tell the compiler how those properties or methods can be accessed. public is the most visible, meaning that it can be accessed from within the class, its descendants, and from outside the class (i.e. from an instantiated object). In the case of the previous code sample, the display method was accessed from outside the class (it was accessed from the instantiated object).

If you are accessing properties or methods from inside a class, then that means that the code must be within the beginning and end curly brackets of the class!

The private modifier is the most restrictive. It means that you can only access that property or method from inside that class. So in the case of $street_line, it can be accessed from the display method because the method is within the class, but it can’t be accessed via the $myAddress object because the object is outside the class!

//--this gives an error because $street_line is private.
echo $myAddress->street_line;

Constructors

In our Address class we declared 4 variables. However we didn’t assign any default values to them. Assigning values to properties is done in a constructor; a special method of a class that is automatically invoked when an object is created (using the new keyword). An example of a constructor (which would appear within the class definition) is shown below.

public function __construct()
{
$this->streetline = '';
$this->suburb = '';
$this->postcode = '';
$this->state = '';
}

The following paragraph relates to Inheritance, which is covered in Advanced OOP for COMP307.

A constructor in a descendant class such as a SchoolAddress class would typically call the parent constructor first before setting any of its own properties.

public function __construct()
{
parent::__construct();
$this->SchoolName = '';
}

Destructors

The opposite of a constructor is a destructor. The destructor is called when the object is destroyed (which occurs automatically at the end of the script), or when you explicitly unset the object.

Destructors are useful for freeing up resources or un-initializing variables / properties. In languages that have automatic garbage collection, destructors are seldom used and some languages (Java) don’t even provide them.

Destructors do differ from constructors and other methods in that they cannot take any arguments.

public function __destruct()
{
//time to unset some variables...
parent::__destruct();
}