Search This Blog

Monday, February 15, 2010

Designing PHP Program Logic

There are many ways to set about building an application, but a step-by-step approach can save time and reduce frustration. One good method is to start by defining the problem (problem statement), then write pseudo code (computer instructions similar to actual programming language code but in plain English) based on the problem statement, and finally write the actual PHP code based on the pseudo code. The pseudo code often serves as the basis for comments, something that will be discussed much more in Chapter 5.

Problem Statement

For example, if you intend to build an application for clients of a mortgage company, and one of the features is a mortgage calculator, it's very likely that one of the expected outcomes is mortgage payment amounts. The calculation for mortgage payments amounts is dependent upon the interest rate, term, and initial balance of the loan, so you'd also expect that your application would have to gather these data from some source (possibly the user, or perhaps an online source of current interest rates).


Unless you happen to be using a canned application or Web Service to generate payment amounts and due dates, your application will be generating these answers. The processing methodology of this feature could be expressed in logical terms completely unrelated to any programming language: "Accept as input values the loan balance, interest rate, and loan term. Assume equal monthly payments starting on the first of the month and recurring for the life of the loan. Calculate each payment amount and due date and generate HTML code to display the data to the user. Repeat calculation until all payments are accounted for, and then return the HTML to the user in the form of a Web page."


This statement of the problem, although not quite pseudo code, is a good start at defining the inputs, processing, and outputs required of the feature you are about to program. Once you've done this step, you could easily write pseudo code from the problem statement, and then actual code from the pseudo code.

Writing Pseudo Code

What is pseudo code? There's really not a hard and fast definition, here's a general definition that works well and makes the term easier to understand: Pseudo code is a series of statements in plain language that are logically structured much like the code in the program will be.


Of course, to write pseudo code effectively you must have some knowledge of the way the language you intend to use works, because pseudo code is meant to be similar enough to the actual programming code statements required that you can very quickly convert it directly to programming code.


Pseudo code for the preceding problem statement, written to be converted to PHP5, could be something like the following:


//Validate incoming values for loan balance, interest rate, and loan term
using validation functions
//Set a variable for payment amount to the result of the calculation for
payment amounts based on incoming values
//Set a variable for payment dates as an array, and iterate through the
payment date calculation the number of times equivalent to the number of
payments required
//Set a variable equal to a string containing HTML to display payment
amounts and dates, and insert payment dates and amount each time through the
loop above. Add the next HTML, payment date, and amount to the string each
time through
//Calculate total number of payments and total payment amount by setting
variables equal to these values each time through the loop and incrementing
them
//Set a variable equal to a string containing HTML for displaying totals
//Send back to the user the HMTL and values generated.

In addition to demonstrating some basic pseudo code writing techniques, you'll notice that the technique of repeating calculations (or other data processing) is common. In fact, this technique of looping through the same calculations over and over is very common. The point of this discussion is that many of the programming language structures you'll use are simply control-flow structures in which decisions are made based on values found or created dynamically (while the application is running), and often the decision-making structures are coupled with loops so the calculations are repeated over and over until the final answer has been found. Just about every kind of data processing relies on the same control-flow structures and loops, no matter what the language.

Boolean Logic

Boolean logic is very important to control-flow structures because Boolean values are often used to express the "condition" that determines which set of processing instructions is followed (essentially, what decision is made). Boolean logic gets its name from George Boole, who devised Boolean algebra. Extraordinary work, overall, but for the purposes of this chapter, only the simplest knowledge of his work will serve.

Boolean Terms

You've probably used Boolean logic while looking up something on a search engine. For example, putting the word "and" in search terms means "retrieve documents containing this A and that". And is a Boolean term, and so are or and not. These are terms used in everyday life all the time, and everyone implicitly understand what they mean. There is also a special term—xor—that means "if either are true, but not both." There are also special operators that mimic or and and (|| and &&) but have a higher level of precedence (Chapter 2 contains more background on this subject).


If you think of them in terms of the results of a search, you can see that including or in a search gives the broadest possible result, although xor, not, and and each successively narrow the search more. Try it on your favorite search engine (if it supports Boolean logic).


When constructing a piece of data processing logic, you can use Boolean terms to set the conditions under which processing takes place. For example, in an if..then...else..end if control-flow structure, the if is followed by an expression that is either true or false (true and false are called Boolean values). If true, the code immediately after the if part of the block is processed. If false, processing bypasses these statements and goes directly to the else, and if there is no else processing bypasses the rest of the control-flow structure entirely.

Boolean Values

The Boolean values true and false are represented by TRUE and FALSE. Although you can convert to Boolean values, in most cases you don't need to for your expression to trigger the appropriate action within a control-flow structure. The following values are taken as Boolean FALSE:
  • The integer zero (0)
  • The float zero.zero (0.0)
  • An empty string (" ")
  • The string zero ("0")
  • An array with zero elements
  • An object with zero member variables
  • The special type NULL (including any unset variables)
All other values are considered TRUE. Keep in mind that whether an expression is true or false depends on the outcome of the evaluation, not on the values being compared. For example, if value A is 20 and value B is 30, and the comparison asks whether value A is less than value B, the outcome would be TRUE. For decision-making purposes there can be only two possible outcomes: true or false. There is no maybe allowed in these structures.
Previously your variables could hold numbers or text, but Boolean values are held in a third type of variable, which can hold one of two absolute values: true or false. You can set any variable to one of these two values:


$Variable = true;

However, if you then display the value on the screen, you see a numeric value:
1

So you can see that Boolean values have both numeric and literal values. On its own, this isn't particularly interesting, but once you start needing to make decisions based on the outcome of situations, and having to say either a given condition is true or false (or, equivalently, evaluates to 1 or 0), you'll find that you use Boolean values a lot.

Using Boolean Terms and Values

An expression can simply evaluate to a value that is then compared to some other value to determine whether the expression is true or false. It can also evaluate to a set of values (in the form: this and that, this or that, or this not that), each of which is tested, and these statements can be connected by the Boolean operators named and, or, and xor. Not is represented by the ! operator in PHP.


When using sets of values as a condition, if the first expression is true and the second is false, and the two are connected by and, the entire condition is false, and processing bypasses the first set of processing statements. Conversely, if both expressions are true and connected by and, the entire condition is true and statements in the first block of code are processed. The other sets of statements also cause a decision to be made based on the Boolean value returned after processing all statements.


A table of outcomes for a simple control-flow block using if..then..else/elseif..end if can illustrate how these conditions work. (Note that then and end if are represented by curly braces in PHP; the if statement is covered in much more detail later in this chapter.) Here's the code (the ANDs and OR are uppercase to highlight them; these terms are case-insensitive):


$my_var = 27;
$my_var02 = 30;
if ($my_var == $my_var02) {
   //do these lines of code
} elseif ($my_var + 3 == $my_var02) {
   //do these lines of code
} elseif ($my_var + 3 == $my_var02 AND $my_var == $my_var02) {
   //do these lines of code
} elseif ($my_var == $my_var02 OR $my_var == $my_var02-3) {
   //do these lines of code
} elseif ($my_var == $my_var02 AND !$my_var == $my_var02-3) {
   //do these lines of code
}

The following table shows the possible outcomes:
Condition
Outcome(s)
$my_var = $my_var02
The only true outcome here is if both variables contain an exactly equivalent value. All other cases are false
$my_var + 3 == $my_var02
The result of the expression $my_var + 3 is evaluated first, and then the comparison takes place
$my_var + 3 == $my_var02 AND $my_var == $my_var02
The outcome is determined after both expressions are evaluated, and is only true if both expressions are, true
$my_var = $my_var02 OR $my_var == $my_var02 - 3
Both expressions must be evaluated, but now if either of them are true the outcome is true, obviously a broader condition than if both are required to be true,
$my_var == $my_var02 - 3 AND ! ($my_var == $my_var02)
The first expression must be true and the second must be false in order for the entire set of conditions to be met, in which case the whole thing is true. Remember, the second expression must be false because that is the only case where the ! operator would return tale


As you can see, you can choose conditions that fit just about any circumstances. For example, you might write a control-flow structure that looks for a particular value being submitted by the user. If you write the condition so that one and only one value turns the code in the structure "on", there are many, many possibilities to miss that one value and never execute the code. Sometimes that's what you want. Other times, you want to make sure the code almost always executes, except in a very specific case. You might write a condition such that the code executes unless a particular value is submitted, like this:


if ($submitted_value !== $my_internal value) {
//do this code
}

Using control-flow structures by themselves, in combination, and together with loops offers many means to make your program do the things you want it to do. Instead of simply executing all lines of the program one after the other, a control-flow structure gives you the ability to choose whether you want to execute a particular line of code, and it enables you to make comparisons between different variables and values to make those decisions.