Tuesday, May 19, 2009

Compter IQ

Making Computers Smart

Do you recall this conversation from the film, 2001: A Space Odyssey?

Hal, the spacecraft computer, killed a crew member by throwing him into space when the crewman went outside to replace the computer unit. Dave, the hero of the film, has just discovered that Hall has also killed the rest of the crew as they slept.

(Dave) "Open the pod bay doors, Hal. Hello Hal, do you read me? Do you read me, Hal? Hello Hal, do you read me? Open the pod bay doors, Hal".

(Hal) "I’m sorry, Dave. I can't do that, Dave ...the mission is too important for me to allow you to jeopardize it".

(Dave) "Ok Hal, I’ll go in through the emergency airlock".

(Hal) "Just what do you think your doing, Dave? I know everything hasn’t been quite right with me, but I can assure you it’s going to be alright again. I feel much better now, I really do."

(Hal) "Look Dave, I can see you are really upset about this. I know I’ve made some very poor decisions lately. I want to help you. Stop, Dave… will you stop, Dave? I’m afraid, Dave..."

This film, plus many before and after, fueled our love-fear relationship with smart machines. While machines like Hal, capable of independent thought and emotions, are science fiction, artificial intelligence is currently combining computer science and engineering to create machines that exhibit intelligent behavior, learn useful skills, and adapt to new situations. These machines are embedded within many everyday appliances and tools in our homes, hospitals, factories, businesses, government agencies, and research facilities. Whole new fields of science and business domains are developing as new applications are invented for the smart computers behind these indispensible machines. And it’s all based upon some rather basic programming concepts which you will come to realize in this lesson, are very human.

AI and Expert Systems

Conventional Artificial Intelligence (AI) is the science of creating computers that mimic what humans refer to as intelligence—the ability to process information and respond appropriately. AI is supported by several types of machine learning technologies including expert systems which apply statistical and reasoning capabilities to huge amounts of data in order to draw conclusions and solve problems.

Expert system - Computer programs that answer questions and draw conclusions by applying statistical rules and logic.

The goal of expert systems is to bring the knowledge of experts to the hands of decision makers who need accurate answers quickly. Computer expert systems are sometimes called knowledge based systems and have been in use since the 1960’s. They are created by first gathering the knowledge of human experts on some specific, narrow field of knowledge. Then, a knowledge engineer organizes the information with rules that help to focus the knowledge toward solving specific problems.

The childhood guessing game in which one child thinks of an animal, and the other child tries to guess it by asking only yes-or-no questions, simulates an expert system. A process of elimination based upon rules guides a series of questions until the correct animal name is guessed. It might go something like this:

“Does it have fur?”

“No”

“Does it have feathers?”

“Yes”

“Can it fly?”

“No”

“Is it black and white?”

“Yes”

“Is it a penguin?”

“Yes”

Expert systems contain information supplied by experts on a single topic and usually involve a “dialog” with the user. This problem-solving system relies upon rules that guide the dialog toward the discovery of the solution that fits all of the responses given by the user. A recent addition to expert systems is the inclusion of “fuzzy logic” which doesn’t rely on definite yes-or-no answers, but rather on conditions of “mostly true” or “mostly false.” These less definite answers result in more realistic “most likely” conclusions.

Fuzzy Logic - A system that relies upon “mostly true” and “mostly false” conditions to arrive at more realistic “most likely” conclusions.

Expert systems are employed quite commonly in:

  • Wizards that help you install software

  • Artificial intelligence of computer games

  • Diagnostic programs for everything from identifying skin diseases to getting help with your computer system

  • Decision making in business, science, engineering, and the military

Computational Intelligence and Artificial Neural Networks

A specialized area of artificial intelligence called computational intelligence includes the application of artificial neural networks. When groups of processing units—sometimes referred to as nodes—are interconnected in a fashion resembling the neurons in the brain, an artificial neural network can be constructed. An artificial neural network “learns” by observing complex relationships between inputs and outputs and inferring from observations. This is particularly useful in applications where the complexity of the data or the difficulty of the task makes traditional program design extremely complicated or impractical. Artificial neural networks are especially useful in tasks such as:

Neural network - A collection of interconnected processing units which resemble brain neurons and are capable of complex analysis of data.

  • Pattern recognition in military radar systems

  • Face identification in Homeland Security operations

  • Sequence recognition in gesture, speech, writing

  • Medical diagnosis with EMR technology

  • Detection of abnormal charges on credit cards

  • Data mining or knowledge discovery in databases

  • Identification of e-mail spam

Robotics and Artificial Intelligence

"The problem with most robots is that they tend to be, well, robotic. They know nothing they aren't programmed to know, and can do nothing they aren't programmed to do. But for many applications where robots could be useful, they need to be more like humans, able to respond as a cooperative partner rather than a mindless machine.”

—Scientific American Frontiers, April 13, 2005 . Alan Alda, host

Today’s robots are simply machines with enough AI to do useful tasks. And the tasks run the gamut from entertainment in the form of Aibo, and the robotic pet, to Roomba, the robotic vacuum cleaner, to Penelope, the surgical assistant. Robots come in all shapes and sizes. Depending upon how you define the word “robot,” you could be talking about the “smart wiper” on your car windshield that is “just a robotic arm” or a machine the size of a vehicle such as the Mars Rover or the trucks in the DARPA Challenge road race.

It appears that robots will definitely be part of our future of smart machines. Analysts estimate that about 4 million Roomba vacuum robots will be in homes by 2007 and some people in Japan foresee 39 million household robots in use by the end of the decade. Add to that the 1.1 million industrial robots in the U.S. and you have a robot population greater than the population of California or Spain!

Research and development in AI and robots includes such projects as:

  • Systems for surgical assistance

  • Solar-powered underwater vehicles

  • Robotic assistants for the elderly

  • Space exploration rovers

  • Bomb-sniffing military robotics

  • Childcare workers

Since the earliest days of computers and AI, great debate has raged over a definition of intelligence and creativity, whether or not a machine can actually understand and be intelligent, and even, if the distinction between human and machine will eventually disappear. Various schemes to distinguish between computer and human intelligence and creativity have appeared over the past several decades. Perhaps you have heard of the Turing Test in which a judge asks questions to an entity in another room. If at some point the judge cannot tell if the answers are coming from a person or a computer, the computer is declared intelligent. And of course, we’ve all heard of the famous computer versus human chess games. While philosophers will continue to explore the distinctions between humans and machines, computer scientists will forge ahead with research and developments of more and more amazing machines. Ultimately, computer IQ comes down to machines following the directions given to it by programmers and engineers.

Get Real

  1. Explore an expert system by visiting The Whale Watcher at http://www.aiinc.ca/demos/whale.html. Does this system employ strict true/false logic or fuzzy logic?

  2. Review the basic characteristics of expert systems, fuzzy logic, neural networks, and robots. Match the tasks on the left with the technology on the left that would best be able to accomplish the task described.

Task to accomplish

Technology

____ Discover the most likely cause of a panic attack

A. Expert systems

____ Identify wild flowers seen on a hike

B. Fuzzy logic

____ Inspect mines for dangerous gases

C. Neural networks

____ Uncover forged artwork

D. Robotics

Here are some possible answers:

  1. After identifying several hypothetical sighting of whales, it appears that this system employs strict true/false logic. All of the response choices are yes/no or either/or.


Task to accomplish

Technology

B, Discover the most likely cause of a panic attack

A. Expert systems

A, Identify wild flowers seen on a hike

B. Fuzzy logic

D, Inspect mines for dangerous gases

C. Neural networks

C, Uncover forged artwork

D. Robotics

Computers are “taught” to display intelligence by making decisions through various coding techniques. Collectively these techniques are called “selection structures”; the lines of code instruct the computer to “select” between various options based upon particular conditions.

If-Statements

The most basic selection structure is the if-statement. In the real-world we process if-statements so often and with such speed that we barely give it any thought at all. You have likely experienced these opportunities to process an “if” decision:

If it’s raining outside, you grab an umbrella.

If steak is on sale, you buy it.

If the traffic signal is red, you stop.

If you see a friend, you shout, “Hi!”

If-statement - A computer instruction that decides upon an action based upon the evaluation of a condition.

In all of these situations, and in dozens more in every hour of every day, you respond to a situation or condition with some action that uniquely fits the specific circumstances. Obviously, we learned the correct responses to unique situations from modeling, training, and trial-and-error. Computers don’t learn quite as easily as humans…or even as easily as dogs for that matter! Computers must be instructed to respond correctly with very specific instructions.

The if-statement is used in computer programs to instruct the computer to carry out specific actions in response to specific conditions.

The if-statement looks like this in pseudo-code:

If then

Think about this situation in a word processing program:

You are writing a letter to your friend, Sara. In order to capitalize Sara’s name you press the shift key while pressing the ‘s’ key. The computer interprets your action like this:

If the shift key is down, then print on the screen the uppercase version of the letter key being pressed at the same time.

Comparison Operators

Sometimes we must evaluate the situation we are experiencing with words like “greater than” or “less than or equal to.”

You might have experienced the need to use these comparisons when writing a check. You likely thought to yourself, “If my checkbook balance is “greater than” the amount of this item, then I can buy it.” Or you might have thought about the situation in reverse, “If the amount of this item is “less than or equal to” my checkbook balance, then I can buy it.

We use these comparisons quite automatically, but the computer must be taught the logic very explicitly. Special symbols, called comparison operators, are used in computer programming to compare values.

Comparison operators - Symbols used to compare the relationship between values such as greater than, less than, equal, or combinations of these relationships.

This is what the purchasing scenario would look like in pseudo-code:

If checkbook balance > price then buy item

Or

If price <= checkbook balance then buy item

You might be familiar with some of these symbols from your experiences in mathematics. These are the comparison operators commonly used in computer programs:

Operator

Description

Example

<

Less than

Height <>

<=

Less than or equal

Age <=16

>

Greater than

Size > 32

>=

Greater than or equal

Length >= 21

==

Equal

Temperature ==32

!=

Not equal

Balance != 0

You might not recognize the last two symbols for equal and not equal. The “==”symbol instructs the computer to check if the values on each side of the symbol are equivalent. This is different than the assignment operator (=) that we learned about in Lesson 3 of this series which stores a value in a variable.

Logical Operators

Sometimes a situation requires more than one comparison of values to arrive at an appropriate response. In the game of volleyball, a team wins if it has scored at least 15 points and has at least 2 more points than the opponent. So, if the Cougars have 15 points and the Vikings have 14 points, no one has yet won and the game is not over. If the Cougars win one more point for a total of 16 points and the Vikings still have 14 points, the game is over and the Cougars win. Putting this logic into a computer requires the use of logical operators. With logical operators, computer programmers (and the rest of us) create powerful comparisons which fine tune the exactness of problem solving.

In pseudo-code the volleyball scoring comparison would look like this:

If team A score >= 15

and team A score >= Team B score +2

then winner = Team A.

You constantly use logical operators in your daily life. When you get dressed in the morning you probably check the weather. If the day is going to be cool you take a light jacket. So when you listen to the weather report, you likely say to yourself, “If the temperature is greater than 40° but less than 70°, I’ll take a light jacket.”

Logical Operators - Symbols used to combine the logic of comparison operators into more complex comparisons.

Deciding to take a jacket that would look like this in pseudo-code:

If temperature > 40 and temperature <>then garment = light jacket

Special symbols are used to express this logic in computer programs:

Operator

Description

Example

&&

AND

Both conditions must be true to make the whole expression true.

(snow >=4) && (temperature <= 0)

||

OR

At least one of the conditions must be true to make the whole expression true.

(age >= 21) || (gender = male)

!

NOT

Changes a true expression to false and a false expression to true.

!(on)

where on is a Boolean (true/false) variable

HINT: Avoid confusion over the exact meanings of “&&” or “||” by thinking about each like this:

When you see “&&” say to yourself, “Both condition 1 and condition 2 must be true in order for the action to be carried out.”

When you see “||” say to yourself, “Either condition 1 or condition 2 must be true in order for the action to be carried out.”

Logical operators are very powerful for programming “almost” conditions. Sometimes computers evaluate when a situation is “almost” at a critical point. Your home thermostat operates on this principal of “almost.” If you set the thermostat at 68° you want the heater to turn on when the room temperature falls to “almost” 68° so that by the time the burner is hot and the fan is ready to kick in, the room temperature hasn’t fallen too much below 68°. You also want the heater to turn off a bit above 68° so that when the fan finally turns off, the room is within a comfortable range. If the condition for turning the furnace on and off is exactly 68°, the furnace will continually turn on and off and the room will never be very comfortable.

Comparing Objects

For a moment, think back to Lesson 2 where you learned about object-oriented design and programming. You will recall that objects have properties and methods. Properties are the objects characteristics and methods are their behaviors. Because of the manner in which an object is stored in memory, a direct comparison between objects is not usually meaningful when you want to evaluate if one object has the exact same property values as another object. You can not write a pseudo-code statement like this:

If myPetObject == yourPetObject then declare them twins

To evaluate if any given property or all of the properties of two objects are the same a special method must be written into the class. The name of the method is always compareTo. Within this method, the programmer defines what it means for two objects to be equal dependent upon the values of their respective properties. Based upon the goals for the program, it might mean that two pets are “equal” if they share the same parents and birthday. In another program it might mean the two pets are equal if they are of the same breed and similar weight. The point is that comparing objects for equality, or with any of the comparison operators, is very different than comparing other data types. You will learn more about the specifics of comparing objects when you learn a specific computer programming language.

compareTo - The name given to a class method for comparing the properties of objects.

If-then-else

For the wide range of decision-making we expect of computers, several other comparison strategies are necessary. In addition to the basic if-statement, programmers can use an if-else statement. This statement adds an additional level of sophistication with which you are already very familiar. It’s rare that you are faced with a situation for which there is only a single possible reaction. Let’s revisit the situations from earlier in this lesson and add more realistic outcomes.

If it’s raining outside, grab an umbrella, else grab sunglasses.

If steak is on sale, buy it, else buy hotdogs.

If the traffic signal is red, stop your car, else proceed with caution.

If you meet a friend on the street, shout “Hi!”, else smile and walk on.

Computers commonly use if-else logic. If you fail to click “OK” in some dialog boxes, the computer beeps a warning. The pseudo-code for this situation might look like this:

If reply = “OK” then close dialog box else beep

You will encounter many if-else scenarios while shopping online. Sometimes the price for an item depends upon a special coupon code or membership in an organization. Renting an automobile definitely falls into this category. If you belong to the American Automobile Association (AAA) you might get discount on a car rental. The pseudo-code for a car rental by an AAA member might look like this:

If membership == yes then price = 72 else price = 80

If-else-if ladder

Another selection strategy is called an if-else ladder. In this technique, only one outcome action is allowed. As soon as a condition is found to be true on one “rung” of the ladder, the process of evaluating conditions stops. It looks like this in pseudo-code:

If temperature >= 90 then get ice cream

else if temperature >= 70 then go to the beach

else if temperature >= 50 then go to the movies

else get hot chocolate

The trick in understanding this type of logic is to remember:

  • You start at the top

  • Only one action can occur

  • Once a selection based upon the temperature is made, the process stops

Try your hand at the process with this example: What happens if the temperature is 60°?

Is the temperature >= 90? No. Go to the next rung of the ladder.

Is the temperature >= 70? No. Go to the next rung of the ladder.

Is the temperature >= 50? Yes. Go to the movies.

Stop the selection process.

Complex modern problems can be solved with combinations of comparison and logical operators. The power of the computer is that it can process the complexity at blinding speed and remember the multitude of possibilities far beyond our human capability. Whether in a chess match, a flight reservation system, or weather predictions, the if statement is a key component. There are many more variations of the “if” selection strategy to discover when you begin learning a specific programming language. The general rule is to always choose the most efficient strategy available to fit the goals of the problem.

Get Real

  1. Practice using comparison operators by writing if-statements pseudo-code for these situations.

    1. To receive a passing grade, a student must earn a grade of 60 percent or better.

    2. A gas credit card will allow no more than a $75 charge.

    3. The first 200 customers receive a 10% discount on merchandise purchased.

  2. Determine the result of the following logical statements giving the following facts.

    Age = 20, gender = male, traffic tickets = 2, vehicle = car

    1. Age <= 21 && gender == male

    2. Traffic tickets > 2 && vehicle == motorcycle

    3. Gender == female || vehicle == car

    4. Tickets <=2 || gender == female

    5. Vehicle != truck && age >= 30

  3. Imagine playing the game “Rock, Paper, Scissors.” Write the if-else pseudo-code for all of the possible outcomes of one round of the game. The first one is completed for you. How many are required to evaluate all of the possible outcomes?

    If player 1 == “Rock” and player 2 == “Scissors” then player 1 wins.

  4. Consider this if-else-if ladder of directions for cooking meat.

    If temperature >= 170 then the meat is well done

    else if temperature >= 165 then the meat is medium-well

    else if temperature >= 160 then the meat is medium

    else if temperature >= 145 then the meat is medium-rare

    else if temperature >= 140 then the meat is rare

    else the meat is not ready to eat

    Classify meat prepared to these temperatures:

    1. 150

    2. 135

    3. 162

    4. 173

Your answers will likely be similar to these:

    1. If grade>= 60 then student passes

    2. If charge == 75 then turn off the pump

    3. If customer number <= 200 then discount = 10%

    1. True

    2. False

    3. False

    4. False

    5. True

  1. If player 1 == “Rock” and player 2 == “Scissors” then player 1 wins.

    If player 1 == “Rock” and player 2 == “Paper” then player 2 wins.

    If player 1 == “Rock” and player 2 == “Rock” then it’s a tie.

    If player 1 == “Paper” and player 2 == “Scissors” then player 2 wins.

    If player 1 == “Paper” and player 2 == “Rock” then player 1 wins.

    If player 1 == “Paper” and player 2 == “Paper” then it’s a tie.

    If player 1 == “Scissors” and player 2 == “Paper” then player 1 wins.

    If player 1 == “Scissors” and player 2 == “Rock” then player 2 wins.

    If player 1 == “Scissors” and player 2 == “Scissors” then it’s a tie.

    1. 150 medium-rare

    2. 135 not ready to eat

    3. 162 medium

    4. 173 well-done

The repetition of sequences in technology is a familiar experience for technology users.

  • Remember back to the last time a program or a website required a password that you just couldn’t recall. The dialog box accepted your password attempt over and over and when you failed on the fifth try, it closed you out. How does that happen?

  • Picture the little “busy” icon that cycles through three or four graphics, on and on, until a task is completed. How does that happen?

  • Remember (as if you could forget this one!) the background music on some website that plays but never ends. How does that happen?

All of these scenarios are the result of program looping strategies called repetition. Repetition provides the power to create programs that can flow in smooth, natural sequences of computer/human interaction. The computer can be told to repeat a set number of times as in the password situation, repeat until something happens as in the “busy” icon scenario, or to repeat forever, as in the background music scenario. Each of these situations is the result of specific programming strategies. Let’s look at each one a bit more closely.

Repetition - A programming strategy that repeats a set of actions a specified number of times, until a condition is met, or without end.

Counter-controlled Loops

The password example from above, uses what is called a counter-controlled loop. Basically, the computer is told to repeat something a specific number of times. This type of loop is used when the number of repetitions is known before the action begins. In this password example, there is an additional feature that causes the program to escape the repetition if the password is entered correctly. You might have experienced counter-controlled loops in the animation or the sound effects of video games; the rabbit jumps three times for each correct answer or the sound of a cannon is exactly bang—bang—bang—bang. Sending two copies of a letter to your printer creates a counter-controlled loop also. While the exact syntax of each of these repetition loops is dependent upon the specific programming language being used, the pseudo-code can be generalized in order for you to understand the instructions given to a computer. The pseudo-code for a counter-controlled loop looks like this:

Repeat cannon sound 4 times

Sentinel-controlled Loops

The changing “busy” icon is a sentinel-controlled loop. The word “sentinel” in this situation means “controller.” The loop that shows each of three or four slightly changed icons continues until something occurs to make it stop. In this situation, the sentinel is the completion of the task being performed by the computer. You encounter sentinel-controlled loops in video games when the “Game Over” message is displayed after you earn a set number of points, you are destroyed by the enemy, or you run out of time. The program used by a credit card company might contain a sentinel loop; you will continue to receive a bill until the balance due is zero.

The pseudo-code for a sentinel-controlled loop looks like this:

Until the balance == 0 repeat sending a bill

Forever Loops

The annoying background music is the result of a “forever” loop—sometimes called an “infinite” loop. In addition to being annoying, “forever” loops are generally considered poor programming style and should be avoided. Amateur web designers sometimes use a “forever” loop to animate little mailboxes or silly smiley faces. Ugh!

The pseudo-code of a forever loop looks like this:

Repeat playing annoying music

Notice that there is nothing to stop the action in this type of repetition.

Get Real

  1. Study the scenarios below and identify the repetition strategy you would use to solve the problem. Explain your answer.

    1. A text finding feature in Word.

    2. A banner message on a webpage.

    3. A packaging robot that puts 10 candy bars in a package.

    4. The gate on a $2.00 toll booth

    5. The noise of your car alarm.

    6. A ringing, but unanswered telephone.

Here are some possible answers:

    1. The repetition strategy used is a sentinel-controlled loop because it continues to search until is reaches the end of the document.

    2. This is likely a forever loop because it typically goes on and on.

    3. This robot uses a counter-controlled loop to place exactly 10 bars in a package every time.

    4. This is another sentinel-controlled loop. The gate is not raised until you have deposited exactly $2.00.

    5. If your car alarm is like mine it sounds for about 8 or 9 repetitions before stopping or until I turn the key. That would make it a counter-controlled loop with a sentinel-controlled condition. If it sounds forever, you would likely return to a dead battery or at least angry neighbors!

    6. My telephone works with a counter-controlled loop. The caller is asked to leave a message after 4 rings. This is one of the counter-controlled loops I control through programming my own phone.

Artificial Intelligence (AI) is the science of creating computers that mimic human abilities to process information and respond appropriately in given situations. Expert systems and neural networks are two forms of AI. Expert systems contain information supplied by experts on a single topic and usually involve a “dialog” with the user that relies upon true/false rules to identify the correct answer. “Fuzzy logic” evaluates conditions of “mostly true” or “mostly false” to determine the “most likely” correct answer. Neural networks are formed from interconnected processing units which resemble the structure of brain neurons. They are particularly useful in applications that analyze complex data. Robotic technology employs AI strategies and is increasing being used to perform a wide variety of tasks that are either difficult or dangerous for humans.

The “intelligence” of computers is the result of programming and engineering. The basic programming strategies which create machine intelligence are selection structures and repetition. Selection structures include variations of if-statements which direct the computer to select the appropriate action for specific conditions. The most basic if-statements take the form of:

  • If

  • If-else

  • If-else ladders

If-statements rely upon comparison and logical operators in order to evaluate conditions. Comparison operators include:

  • < (less than)

  • <= (less than or equal)

  • > (greater than)

  • >= (greater than or equal)

  • == (equal)

  • != (not equal)

Logical operators combine and clarify comparisons with these symbols:

  • && (and)

  • || (or)

  • ! (not)

Repetition strategies are used to repeat actions within a program. The basic repetition formats include:

  • Counter-controlled loops which repeat a set number of times.

  • Sentinel-controlled loops which repeat until some condition occurs.

  • Forever loops which never stop repeating.

Life before Mice

GUIs to the Rescue

Challenge: Create a tool for completing tasks such as producing a report, balancing a budget, searching and learning, communicating with friends and colleagues, and crafting opportunities for fun and recreation.

Solution 1967: A device that barely gets the job done and requires expert knowledge, patience, and plenty of time.

Solution 2007: A device that meets the challenge and much more by responding to the wishes of the user as if it were an extension of the user.

“The human mind does not work that way. It operates by association. With one item in its grasp, it snaps instantly to the next that is suggested by the association of thoughts, in accordance with some intricate web of trails carried by the cells of the brain…Yet the speed of action, the intricacy of trails, the detail of mental pictures, is awe-inspiring beyond all else in nature.”

As We May Think by Vannevar Bush The Atlantic Monthly July 1945

Before the development of Graphic User Interfaces (GUI)) in operating systems such as Microsoft Windows and programs such as Microsoft Office or Internet Explorer, computer users communicated with computers through unnatural and unfriendly exchanges. The first computers required instructions to be manually wired. Later developments lead to the use of punch cards or tapes to interact with the computer. Even as late as 1980, interfacing with a computer was achieved almost exclusively through the keyboard using obtuse code which required considerable skill, knowledge, and patience on the part of the operator.

Today, it’s pretty much a given that using a computer means interacting with a graphical interface. We launch programs with a click on an icon, arrange the view with click and drag actions, and directly manipulate the contents of our work by pointing and selecting. It hasn’t always been so easy nor felt so natural.

Just for fun—if you know your way around DOS—try to locate a file on your computer or copy a file to your backup folder the old-fashioned way. Use only the keyboard and fight the urge to reach for the mouse. Good luck! If you ever needed proof of the power of graphical interfacing this exercise should provide it.

Similar to the way in which the early foundations of programming were conceived by Ada Lovelace long before the technology was available to build a computer, some of the ideas for a GUI computer were anticipated and dreamed of before it was possible to build such a machine. In the early 1930s, a gentleman named Vannevar Bush described a device he called the "Memex." He envisioned it as a desk with two touch screen graphical displays, a keyboard, and a scanner. His dream machine included connections similar to today’s hyperlinks which could access all human knowledge. The digital computer had not yet been invented, so the “Memex” remained just a dream. While his ideas were not widely read or discussed at the time, he made an impression on Douglas Englebart, who is credited with the invention of the mouse many years later and has become known as the “Father of the GUI.” The trail that has led us to the present state of GUI design has been a long and twisted path. Many enterprising companies and inspired individuals refined the designs of others and added their own unique contributions, and in so doing, paved the way for yet more future innovations.

A few highlights of the GUI heritage

1930 Vannevar Bush describes the Memex as a machine with graphical displays, a keyboard and a scanner.

1950’s Punch cards and rolls are used for input, processing, and data storage.

1956 At MIT, researchers begin experimentation on direct keyboard input.

1968 Douglas Englebart demonstrates technology similar to modern graphical CAD software complete with a mouse.

1973 Palo Alto Research Center (PARC) develops Alto with a display the size and orientation of a printed page and featured full raster-based, bitmapped graphics.

1981 Windows 1.0 showcases a graphical interface and multitasking support.

1984 The Macintosh debuts. The idea of "drag-and-drop" is also invented at this time.

1995 Windows 95 is released. Scrollbars, window control widgets, and menus become common place.

2007 Windows Vista is released with a refined GUI for enhancing the user’s experience.

A graphical user interface (or GUI, often pronounced "gooey") involves interacting with a computer through the manipulation of graphic elements and text, often with a mouse or touch-screen input device.

Everyday GUIs

Virtually every interaction you have with electronic devices is a GUI interaction. Let’s retrace your steps today to get a sense of the extent and diversity of the GUIs in your life. Think of all of the technological choosing, touching, and clicking you did to get through your day.

6 AM: Turn on your PocketPC to check your email and the local weather.

7 AM: On the way to work, select a “wax” option on the touch screen at the car wash

8 AM: Check the movie schedule for the weekend on your smart watch

10 AM: Check for voice mail on your cell phone and add a new contact

11 AM: Order lunch online from the deli down the street

Noon: Relax with a sandwich and a round of your favorite video game

2 PM: Search with MSN.com for your mother’s birthday gift

3 PM: Get directions to a client through your vehicle navigation system

6 PM: Warm the meatloaf with the Quick-touch mode of the microwave

7 PM: Check your child’s attendance record and homework details on the school website

8 PM: Reprogram the satellite television recording system

10 PM: Change the landscape irrigation

11 PM: Check the home security system before turning in for the night

If it weren’t for the ease and speed of GUIs in the software of nearly everything you touch, you likely would have never made it to lunch!

So how does the wonder of GUI happen?

In an enterprise setting, building GUI software usually involves a Graphic Designer or Usability Expert who creates a mock-up design of the GUI for a specific application or computer program. Then the developer, who actually builds the application, adds the functionality for the processes required to accomplish the tasks. Modern programming environments called Integrated Development Environments (IDE), such as Visual Studio, streamline the process of adding GUI features such as buttons, menus, and icons to software applications.

Reality Check

  1. List 5 GUIs you interacted with today. What other tasks did you perform that you wish were somehow more GUI capable?

Your answers will be likely be different from mine, but today I interacted with technology through a GUI to:

  • Check out of a hotel

  • Get an airline boarding pass

  • Accept a package delivery

  • Check on an online purchase delivery

  • Download photos from my camera

I wish renting a car and ordering a medical prescription from my pharmacy were more GUI capable.

Manipulating objects on the screen is the underlying premise of a GUI and is based upon what we know about how our brain processes communication. Spoken and written language is more abstract than pictures and they require us to interpret the abstractions in order to decipher meaning. The brain works more efficiently with pictures and graphical forms and so these visual elements ease the communication process. GUI design builds upon this knowledge of human cognition.

What makes up a GUI?

Recall back to Lesson 2 when you learned about object-oriented design (OOD). You will remember that abstract objects are created with properties or characteristics, as well as methods or behaviors. GUI is the epitome of OOD; all of the “objects” you see on the computer screen or other display device are indeed “objects” in the sense of OOD. They all have properties and behaviors. It’s easy to think about OOD in the form of GUI because you can “see” most of these objects.

Typically, the objects used to build a GUI are referred to as controls. Let’s examine some of the common GUI control objects by analyzing their role in a GUI application designed to calculate the monthly payment amount for an auto loan. The payment is calculated based upon the amount of the loan, the number of payments to be made, and the interest rate being charged for the loan.

Control - Objects which make up the design of a Graphic User Interface such as buttons, graphics, menus and labels.

Display controls

Display controls are those GUI elements which create the basic structure of the screen design and communicate the organization and processes of the software to the user. These elements include the form and layout of the design, labels, and graphics. It is important to know that many controls can serve several functions within an application. Some, such as an icon, can communicate instructions to the user, as well as respond to instructions when clicked. The chart below lists only the most basic function of each control. With experience and creativity, you will find many additional uses.

Example

Control

Basic use

Form

The window in which a Windows application is presented is called a Form. It serves as the container to hold all of the controls needed to interact with the user.

Label

Labels are used to identify other controls and to give instructions to the user. The user cannot directly change the text in a label.

PictureBox

Graphics can add to the GUI experience and are inserted into the form with a PictureBox.

Here is the beginning design of the Auto Loan Calculator application with its Form, Labels, and a PictureBox.

Input controls

Input controls enable users to interact with the software of device. While there are many controls that communicate the wishes of the user to the application or device, we will look at a few of the more common controls.

Example

Control

Basic use

Button

Clicking a button triggers an event as a way of saying to the computer ‘Go do something!’

TextBox

A Textbox is used to get user input or data such as their name, address or phone number. In our example, the loan amount is entered with a TextBox.

  • Color

  • Grayscale

RadioButton

Radio buttons are used to offer multiple choices from which the user may select only 1. Either/or choices are well represented by radio buttons.

  • Heated seats

  • Remote locks

  • Sunroof

CheckBox

Check boxes allow the user to make choices and allow for more than one option to be included such as in selecting options for a new car.

ListBox

A list box allows users to select from a list of choices by clicking on a line. This is ideal for short lists of choices.

ComboBox

A ComboBox is a combination of a text box and a drop-down list of choices. You’ve encountered a ComboBox when selecting a state or country to complete your address for online shopping.

Here is the Auto Loan Calculator application with the addition of a ListBox, a TextBox, a ComboBox, and a Button.

Output controls

Depending upon the purpose of an application, the output given to the user can be presented in almost unlimited ways using almost any control; pictures can be changed, RadioButtons and Checkboxes can be selected, dialog boxes made to appear, new forms generated, and more. Labels are a common output control for presenting the results of simple applications. They are typically used to report the result of computations such as the payment amount in our example of the Auto Loan Calculator.

Creating a GUI

Software developers or programmers typically create GUI applications by using a development tool such as Microsoft Visual Studio. Microsoft Visual Studio is called an Integrated Development Environment (IDE) because developers can create software through all of the development stages from design and coding to testing and debugging. Developers place these controls on forms by selecting them from a toolbox in the development software tool or IDE. Amazingly, the IDE is also a GUI that allows developers to click and drag in order to select and position the controls needed for the design.

This is what the Microsoft Visual Basic 2005 Express Edition IDE looks like. Notice the Toolbox on the left side of the graphic. You can see that we barely scratched the surface of possible tool choices in the Auto Loan Calculator application. In addition to the tools in the expanded section of “Common Controls,” there are several collapsed sections such as “Containers,” ”Menus and Toolbars,” “Dialogs”, and others.

A GUI would be of no value whatsoever without events and event handlers. It is the interaction between users and the controls on the forms which create events in the form of mouse clicking, dragging, or hovering actions. All Windows applications are event-driven. This means that every time you click a button or highlight text or choose a menu item, you create an event within the program or within the system. The entire time your computer is on, it is running what is called an “infinite event-loop;” it’s just waiting for an event to occur. When the computer perceives an event—one of those “Ah-ha, something happened” moments—it passes the event along to any event handler that has been programmed in the software to process that specific event. There are even events that are created by external sources. You have experienced the creation of an event on your computer from an external source during a chat with a friend in MSN Messenger. A message, sent by your friend over the Internet to you, creates an event on your computer.

In the Auto Loan Calculator program, the user indicates the length of the loan by clicking on one of the choices in the ListBox, entering the amount of the loan in the TextBox, and selecting the interest rate from the list of choices in the ComboBox. The Calculate button has been coded with an event handler to intercept a mouse click on the button. The event handler gathers the details entered in the ListBox, ComboBox, and TextBox, and performs the calculations to determine the payment amount of a loan of $20.500 for 5 years at 6.75%.

A graphical user interface in and of itself does not create a user-friendly experience however. Just as in other media, a GUI is most efficient when it follows good design principles that lead the user toward completing his or her work in the most intuitive manner and with as little frustration as possible.

Here are a few guidelines to follow when designing a GUI:

  1. Make the actions required of the user as obvious and intuitive as possible. Use icons that are easily recognized. Give complete directions as necessary. Using Visa or MasterCard logos on buttons for users to indicate a payment method is a good example of this.

  2. Choose icons and words carefully so that they express the exact meaning you intend. Be consistent. Create a comfortable setting with no surprises.

  3. Avoid sounds and animation unless they are critical to the function of your program. Cute sounds and flashing icons become annoying very quickly.

  4. Line up the buttons, textboxes and other controls in rows and columns or group related items together in group boxes to create order and control.

  5. Place buttons and other controls in the order, from left to right and top to bottom, in which users will likely read or use them, or by order of importance and frequency of use. Avoid unnecessary hunting for the user.

  6. Create a color palette that is pleasing. Limit the colors to 3 or 4.

  7. Be consistent in the size of the controls and fonts you select.

  8. Most of all, remember that cute and clever are seldom synonyms for easy and efficient.

Reality Check

  1. Using controls described in this lesson, sketch a design for a sandwich shop GUI that allows users to select from a menu of 5 different basic sandwiches, choose a small or large sandwich size, and select additional fixings such as lettuce, tomato, mustard, onion, relish, and mayonnaise.

  2. Describe how your design implements the design principles for effective GUIs.

Your sketch might be different, but this is one possible design.

A Combobox is used to list the sandwich fillings, RadioButtons are used for the choice of either small or large, and CheckBoxes permit the user to select as many fixings as desired. The cost of the sandwich is calculated as the choices are made and the button to place the order is the last control on the form.

This design follows the design principles by:

  • The controls being arranged in the order to be used.

  • Colors are limited to just a few.

  • Fonts and sizes are consistent.

Graphic User Interface (GUI) is a manner of interacting with a computer through manipulation of graphic elements, often with the use of a mouse. In the 1930s, Vannevar Bush envisioned a GUI which he described in a futuristic device called the "Memex."

Douglas Englebart is credited with the invention of the mouse and has become known as the “Father of the GUI.” Many enterprising companies and inspired individuals refined the designs of others and added their own unique contributions to create today’s GUI designs.

Building GUI software usually involves a Graphic Designer or Usability Expert who creates a mock-up design of the GUI for an application. The developer creates the GUI and adds the code required. Modern programming environments called Integrated Development Environments (IDE) streamline the process of adding features such as buttons, menus, and icons.

GUI is an example of object-oriented design (OOD). The objects you see on the computer screen or other display device are “objects” in the sense of OOD with properties and behaviors.

The elements of GUI are called controls and can serve several functions within an application. While there are many, many controls, these are a few of the common controls:

  • Forms

  • Labels

  • Picture boxes

  • Various types of buttons

  • Textboxes

  • List boxes

  • Menus

All Windows applications are event-driven. Every action by the user, or sometimes from external sources, creates an event. If the computer finds an event handler that matches the event, some action occurs within the program.

Follow simple design principles to create clean and more intuitive interfaces.

  • Make the actions required of the user obvious and intuitive.

  • Be consistent with designs, fonts, and instructions to the user.

  • Avoid unnecessary sounds and animation.

  • Create order with the arrangement of controls.

  • Limit the colors to 3 or 4.

Wednesday, July 30, 2008

The Data Game

The amount of information the average person deals with on a daily basis is mind boggling. You are inundated with news and events from television, radio, and the Web. You receive enough emails and snail-mail to overflow your inbox and mailbox on a weekly basis. Add to that weblogs, magazines, announcements, and telephone messages, and it is no wonder we sometimes feel like we are losing the battle of the data bulge. As overwhelming as this is, the amount of personal data generated and collected is miniscule compared with the production of data from companies and research institutions. Knowledge discovery and generation through research and business activities generate a doubling of stored data every nine months! Luckily computers have come to the rescue for many of the tasks of handling all of this data. They are the perfect device for storing, organizing, and in general, managing the deluge.

To better appreciate how computers can process the data that we, as humans, just can’t get a handle on, it’s useful to understand data from the ground up and in the most elementary form—this is the form that computers can crunch on!

In lesson 2, we explored object-oriented design and programming. That’s a challenging concept to wrap your brain around. But actually, you have already learned quite a bit about computer data from that experience. You learned that an object is a complex data type used to store information about complex entities such as vehicle registrations or inventory items. In lesson 3, we are going to step back a bit, break the big ideas of representing and storing data into some very basic concepts, and explore the incredible power and flexibility of electronic data storage.

So let’s start at the beginning and discuss how data is electronically represented.

Electronic data can be represented, stored, and managed in 2 ways; it can be handled as analog data or as digital data. Analog data is a continuous flow of data. A telephone conversation and transmission is typically an analog form of data. The sound waves fluctuate up and down in smooth waves and are transmitted by changing waves of voltage and then received by your telephone and converted back into sound waves. An old fashioned tape recording, or vinyl records, record and store sound as analog data.

Analog - Data that is represented, transmitted, or stored in a continuous stream or wave format.

Contrast this to digital information such as sound stored on a CD. Sound stored digitally is broken into tiny time-segmented pieces and is stored by numbers that represent the intensity and pitch of the sound in each piece or sampling. The data is digitized—turned into digits or numbers.

Digital - Data that is represented, transmitted, or stored in discrete pieces with numerical values.

Your computer is a digital machine. It represents data in small segments that can be represented by numbers. You have likely had a hint of this if you have ever closely observed the values representing colors as you customized the color of text in a Word document. Each hue of red, green, and blue can have 256 values—0 to 255. Many of the colors of the rainbow are possible by mixing these RGB (Red-Blue-Green) values.

Counting on Two Fingers

While you and I count using a decimal system with the numerals 0 to 9, computers use a binary system with the numerals of 0 and 1. While this is hard to imagine because we are so accustomed to the decimal system, it’s really a very efficient and simple method. It’s simple because computers are electrical devices composed of switches. These switches are either “on” or “off” creating obvious and totally unambiguous conditions. Think of a computer as a huge collection of millions of switches that are either on or off. Each of these switches is called a bit. It’s the combination of “on” or “off” switches called bits that creates the magic.

Bit - The basic electronic data storage element of an electronic switch with 2 states—“on” and “off.”

If we focus on just one of these bits we realize it can be “on” or “off”; “on” represent a “1” and “off” represents a “0”(zero). 1 and 0 are the 2 digits used to represent all numerical values in this base-2 number system. Generally speaking, as we need to represent greater and greater values we use more and more bits. Let’s look at the numerical value possibilities of having 2 bits.

Don’t fall into your comfort zone and call these representations zero, one, ten, and eleven. 10 is called “one-zero” and 11 is “one-one.”

With these 4 values or 2 bits we could represent the directions of north, south, east, and west or the stages of a 4-stroke engine.

As we add more bits we increase the number of values that can be represented. 3 bits can represent 8 values: 000, 001, 010, 011, 100, 101, 110, and 111. 4 bits can represent 16 values (2ˆ4) and 5 bits can represent 32 values (2ˆ5). You’re starting to see a pattern here. The more switches or bits the greater the capacity to represent data.

Putting Bits to Use in Your Computer

The quantity of data your computer can store is represented in measurements of these units. Data is stored in computers in connected memory locations made up of 8 bits. These connected 8 bits are referred to as a byte. If you do the math you will see that 8 bits, or 1 byte, can represent 256 values (2ˆ8). Now you understand the significance of the RGB color scheme of 256 values for each of red, green, and blue. The size of a document you are working on is measured in kilobytes (KB); a KB is approximately 1000 bytes. The storage capacity of your computer’s memory is usually expressed in megabytes of approximately 1,000,000 bytes. The storage of your hard drive is expressed in gigabytes of approximately 1,000,000,000 bytes. The actual number of bytes in each of these measurements can be seen in the chart below.

Byte - An electronic storage unit comprised of 8 connected memory locations called bits which can represent 256 values.

Unit

Symbol

Number of Bytes

byte


2ˆ0 = 1

megabyte

MB

2ˆ10= 1024

kilobyte

KB

2ˆ20 = 1,048,576

gigabyte

GB

2ˆ30 = 1,073,741,824

Everything in the digital world is measured in bits and bytes which are the building blocks for data & code – hence the name of this learning series: “Bits & Bytes”!

Get Real

  1. Open Microsoft Word. Type a few lines of text. Highlight a section and choose to change the color by using the pull down menu in the Formatting menu—A. Select “More Colors.” Select the “Custom” tab. In this dialog box, be sure RGB is selected as the format. Experiment with the up and down arrows to the right of Red, Green, and Blue and the slider on the right of the color display to lighten or darken the hue. Observe as the RGB values change for each hue. You can also enter any value from 0 to 255 for each hue and observe the changes in the color display. How does the color change as you increase the value of any given hue? What happens when you assign 255 to all three hues? What happens when you assign 0 to all three hues? How do you get the purest blue you can imagine?

  2. Think of another place where you may have encountered this magic number 256.

  3. Refer to the advertisements for computers in any newspaper. Record the memory capacity of various hardware devices expressed in KB, MB, or GB.

Here are some possible answers:

  1. As the value for any hue is increased the hue becomes darker. If each RGB value is set to 255, the resulting color is black. If the RGB value is set to 0, the resulting color is white. To get the purest color of any hue set, set its value to a midrange of about 128 and the hue value of the other 2 colors to 0.

  2. You might have seen or heard the number 256 in reference to 256-bit wireless encryption standards, the ASCII character set, or memory upgrade units. Perhaps you recall seeing the number 512 in reference to computer processors or hardware. The significance of 512 is that it is 2 × 256!

  3. In today’s newspaper, I found an advertisement for a 256 MB memory card, a 512 MB thumb drive, a 30 GB media player, and a 160 GB hard drive. KB generally represents document measurements, not hardware. On my hard drive I found 14 KB graphic and a 176 KB Word document

“So how does this apply to computer programming”, you ask? For as simple as a series of on-and-off switches sounds, there is obviously a great deal more to it. Programmers rely upon the capacity of computers to remember or store data as engineered through computer design. The creation of machines capable of storing and manipulating data is the work of computer and hardware engineers. Programmers depend upon the expertise of these engineers to create machines capable of responding to the commands written in programs. A program that can’t “remember” a series of values to be added, or the properties of a newly created vehicle registration object is useless! It is this ability to store data that gives computers real power. In order to store data in a computer, the programmer must follow the rules, or syntax, of a specific computer programming language that dictates how memory space is allocated and the data to be stored.

Certainly in your own experiences with computers, you have discovered that “exactness” is the name of the game. For all of their power, computers must be told exactly what to do; they are not particularly good at assuming much of anything. In dealing with data, a computer must be told more than just what data to store, but also how and where to store it. Thanks to modern programming languages, much of the behind-the-scenes details of bits and bytes are taken care of. However, programmers still need to give some very specific directions to the computer about the type of data to store and how to arrange it. In the rest of this lesson we will look at some of the details programmers must communicate to the computer in terms of the type of data to be stored and how to arrange this data for use by computer programs.

Numerical Values as a type of data

Numerical values constitute one form of data. They can come in various “sizes” and with a variety of “exactness.” One size doesn’t fit every computing need and one degree of exactness doesn’t fit every statistical situation. Let’s analyze the concept of “size” first.

Think about the numbers needed to represent these situations:

  • Degrees on your home thermostat or number of stars in the heavens

  • Dollars allocated in the national budget or given for your child’s allowance

These two examples illustrate the property of numbers referred to as a “range.” A range can be thought of as the “size” of a value—how small or big it might be. The numbers on a thermostat expressed as the degree markers have a range from 50 to 100 and the numerical values required to count the stars in the heavens range from 0 to 1,000,000,000,000,000,000,000. The range of the numerical values needed in a computer program to make calculations for solving a problem determine the amount of memory or bytes required to store the values.

Contrast these two values:

  • The exact value in your piggy bank or the exact value of the natural logarithm (2.718281828459)

The coins in your piggy bank can likely be expressed with about 5 digits of precision. If you count $327.76, there are 5 digits required to express the exact amount. With the value of the natural logarithm (a value used in calculus) 13 or more digits of precision are required to express the value. Again, the precision required of the numerical values needed in a computer program also determine the amount of memory, or bytes required to store the values.

Both range and precision are important considerations in planning for the accuracy of the data you wish to represent in a computer. The range and precision are also important from an efficiency perspective; the greater the range and the greater the precision, the more memory in bytes is required to store and process the values. It makes no sense to allocate more memory than is needed to solve the problem than it does to allocate the entire garage to store your tricycle!

To make it easier for programmers (and the rest of us), specific data types have been defined that take these details into consideration. As programmers design and write programs, they select from these types based upon the range and accuracy needed for the problem at hand and they indicate the chosen type to the computer through program statements. The data type chosen determines the amount of memory used by the computer to solve the problem.

Type - A designation used to describe the kinds of values to be stored in a computer. The data type determines the amount of storage required.

Let’s imagine that a computer programmer is designing an application for children to practice their arithmetic skills. The programmer wants these tasks to be performed by the “Math Bam” game:

  • Ask for the child’s name

  • Present easy addition and subtraction problems

  • Reward the child for correct answers with praise

  • Keep track of the correct answers

  • Report the percentage of correct answers

  • Give the child a letter grade for their success

There are many computing steps that would eventually need to be programmed to create the game in this example, but we are going to forget about that for now and concentrate on the information, or data that needs to be represented and stored in this program.

Let’s start with the “numbers” that must be stored.

Here is a typical problem for the “Math Bam” game: 3 + 2 = ?

Integer

The values in this problem, 2, 3 and 5, are described as “whole” numbers in common language, but technically they are called “integers.” Integers can be positive (greater than 0) or negative (less than 0) or 0 itself. Integers typically range from -2,147,483,648 to 2,147,483,647 and can occupy 2 to 4 bytes of storage capacity.

Double

Calculating the percentage of correct answers might result in a decimal or floating point values such as 2.5, 33.33333 or 16.04. These decimal numbers which are called doubles in tech-speak, can store values up to 1.8e308 and occupy 8 bytes of memory.

Boolean

Storing the result of each problem in terms of “right” or “wrong” would require another powerful and efficient data type called Boolean. A Boolean value stores only 2 values, true or false. Boolean values are typically used in programs that store conditions such as on/off, yes/no, or true/false. They require only 1 bit of memory.

Character

Storing the letter-grade score in “Math Bam” uses another data type. You recall that all data is stored in a numerical form in the computer; this is true for all kinds of non-number data also. Letters, or characters as they are called in technology, are stored as numbers. There is a numerical value for every letter of the alphabet, both upper and lower case, as well as every key board symbol such as ‘!’ or ‘&’. The numerical values used to represent the characters from ‘A’ to ‘Z’ range from 65 to 90. The values used to represent the characters from ‘a’ to ‘z’ range from 97 to 122. There are even numerical representations for invisible characters such as tab (value 9) and enter (value 13). Perhaps you have heard of ASCII code (American Standard Code for Information Interchange). This code contains the universally accepted values for all characters created by keyboards. A newer, more comprehensive coding system called Unicode has been created to provide a unique number for every character, on any platform, in any program, and in any language.

String

There is one more data type needed by the “Math Bam” game. The child’s name must be stored. The data type that stores words is called a String – a string of characters. This data type is more complex because it uses a series of bytes held sequentially in the computer memory. A String is actually an object in modern, object-oriented languages. Strings have properties such as its length and methods for manipulating the string such as ToUpper or ToLower which are used to change the case of the characters in the string.

Sometimes what looks like a number is really a String. A telephone number such as 123-4567 is a String. The classification of a series of digits as a value is reserved for such combinations of digits that would be treated as a value for addition, division, and other mathematical operations. Since there would be no valid reason to add telephone numbers together and expect a meaningful result, they, and other identifier-type combinations of digits such as social security numbers, should be classified as Strings. These “number-look-alikes” are really just labels for telephone connections or citizens.

There are other specialized data types including the Date type which is obviously used to store a calendar date. Different programming languages support unique sets of complex data types in addition to the basic types described above.

In fact, if you remember from Lesson 2, creating a class in object-oriented programming creates a new user-defined data type which can be customized to represent complex forms of data. When a class is defined, the specific properties used to describe the objects to be created are generally specified as one of the data types discussed here. In Lesson 2 of this series, we designed a Pet class for a program to be used in managing a pet show. Each of the properties of a Pet would reference data of one of the types discussed above. The chart below shows possible properties of a Pet class and the type of data to be stored for each property.

Property

Data type

Pet name

String

Birth date

Date

Weight

integer

Owner

String

Prize money

double

Types Dictate Operations

Selecting a data type that fits the values used in a program reflects more than just range and accuracy. Each data type supports various operations. Integers and doubles are number values which support typical number operations such as addition and subtraction. Each type however, has some unique operations which offer additional power to knowledgeable programmers.

For instance, you would likely expect that a computer programmed to solve the math expression 5 / 2 would yield 2.5. This result is only accurate if the values 5 and 2 are of type double – meaning decimal. If 5 and 2 are described in the program as being of type integer – whole numbers, the result is 2 (since the integer type does not allow decimals). While many operations for both integers and doubles result in expected values, there are a few exceptions that can take the programming novice by surprise.

Other data types also make unique use of common operators. For instance, if the + operator is used between strings the result is a combining of the strings like this:

bat + man = batman

That is very different than the use of the + operator with integers or doubles:

7.3 + 1.2 = 8.5

Get Real

  1. Select the best data type to store the values likely to be used in these situations:

    1. Grocery list

    2. Report card

    3. Restaurant bill

  2. Translate your name into ASCII code. Visit this Website for help.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/_pluslang_ascii_character_codes_chart_1.asp

  3. Complete this chart identifying the appropriate data type to use for the properties in a vehicle registration object.

Property

Value

Type

Vehicle Identification number

1F7KB54Y1WU7734


Year of manufacture

2005


Owner’s first name

Kim


Owner’s middle initial

J


Registration fee

378.50


Here are some possible answers:

  1. A grocery list would likely include words such as milk, eggs, and bananas. They would be stored in variables of type String. A report card would likely include words such as the student name. It would be stored in a variable of type String. The letter grades earned would be stored in variables of type char. A restaurant bill would include the cost of chosen menu items in dollars and cents and it would likely be expressed as decimal numbers. This data would be stored in variables of type double.

  2. The name Marc Brown translated into ASCII code:

    Character

    M

    a

    r

    c

    B

    r

    o

    w

    n

    ASCII

    77

    97

    114

    99

    32

    66

    114

    111

    119

    110

  3. Vehicle registration properties, values, and data types:

    Property

    Value

    Data Type

    Vehicle Identification number

    1F7KB54Y1WU7734

    String(this is an identifier value, not a numerical value)

    Year of manufacture

    2005

    integer

    Owner’s first name

    Kim

    String

    Owner’s middle initial

    J

    character

    Registration fee

    378.50

    double

Storing and using values from within a computer program requires the use of special “storage containers” called variables. A variable is a named memory location which stores the values or data used in a program. Each variable holds a specific data type such as an integer, double, String, or others. The type of variable is indicated by the programmer when the code is written.

A variable identified to hold data of one type cannot hold data of a different type without generating an error or producing inaccurate results. For example, a variable designated to hold a character cannot be used to hold data of type double (decimal).

Think of this as a child’s peg game where each uniquely shaped peg will only fit in a hole of the same shape. Circle pegs fit into circle holes and square pegs fit into square holes. Character type data fits into character variables and double type data fits into double variables.

Naming your data

The program data stored in variables are accessed by names referred to as identifiers. An identifier is a word chosen by the programmer for use in accessing the stored data. It is simply the act of naming the information so that you can get to it when you want to use it. I guess this is the same reason we name children and pets – we want to get the right child or dog when we shout their name!

Identifier - The one-word name given to a stored data element so that it can be referred to and used within a program.

If I were creating a program for the telephone company I might choose “customer_Name” as the variable identifier to label a telephone customer’s name. I would likely use “street”, “city”, “state” and “zip” as variables identifiers to label the separate elements of the customer’s address. All of these would be of type String because they are words. I would also choose “balance_Due” as the variable identifier to label the amount of money owed. This would be of type double because it is a numerical value using 2 decimal places for storing dollars and cents. This step of naming the variable tells the computer to associate a particular word—an identifier, with data of a specific type. The actual storage of the data in the computer memory comes a bit later. This first step of selecting variable identifiers and giving them a data type is equivalent to writing the address on an envelope, but not yet putting the letter inside.

There are rules for selecting identifiers. Generally speaking, identifiers must begin with a letter and contain only letters, digits, and the underscore (_) character. Spaces, periods, and other characters cannot be used.

Here is an example of creating variables to hold data of various types in pseudo-code (human-readable words):

customer_Name as String

street as String

balance_Due as double

Storing your data

The next step is to actually store some item of data in a variable or memory location. This occurs with an assignment statement. An assignment statement assigns some value to a variable; this is the step where the values are actually put into memory locations.

Variable - A named computer memory location used to store data of various types.

Here is an example of assigning values to variables in pseudo-code:

customer_Name = “Kim Lee”

street = “401 S. Main”

balance_Due = 78.55

You are probably wondering why some pieces of data appear between quotes and some do not. Strings are enclosed in quotes to indicate that the words found between the quotes make up the actual string of characters which are assigned to the variable. These words in quotations are not to be confused with the identifier (name) given to another variable.

Get Real

  1. Let’s create variables and identifiers for the “Math Bam” game. Complete the chart below by providing the likely data type and an appropriate identifier for each data element listed.

    Data Element

    Value

    Type

    Identifier

    The child’s name




    Number of correct answers




    Percentage correct answers




    A letter grade




  2. Write a pseudo-code statement to create a variable for each data element in the chart above. Use this format: as

  3. Write another pseudo-code statement to store a value in each of the variables you just created. Use this format: = .

Here are some possible answers:

  1. Data Element

    Value

    Type

    Identifier

    The child’s name

    Lee Singh

    String

    student_Name

    Number of correct answers

    15

    integer

    number_Correct

    Percentage correct answers

    83.7

    double

    percentage

    A letter grade

    B

    character

    grade

  2. student_Name as String

    number_Correct as integer

    percentage as double

    grade as character

  3. student_Name = “Lee Singh”

    number_Correct = 15

    percentage = 83.7

    grade = ‘B’

While the data types described in this lesson and the objects you learned about in Lesson 2 are the basis of storing and manipulating the information in computers, they can only go so far in meeting today’s needs. Many other schemes for storing data have been designed by computer scientists, including arrays and databases.

Arrays

Up to this point we have discussed variables as memory containers that hold only one piece of information. It would take many variables to hold all of the names of the players on your baseball team or all of your bowling scores. A more efficient method for storing all of that data and being able to access each unique name or score in the collection is to store the data in an array.

Array - A list of sequentially numbered variables with the same name.

An array uses a single variable name that is numbered, or indexed, to refer to each separately stored data element. Think of it like the mail boxes in an apartment building. The apartment address is analogous to the variable name, such as 7284 Venice Boulevard. Each apartment number is analogous to the indexing value, such apartment 1, 2, 3, etc. Unlike apartments, however, the numbering of arrays starts with the number 0 instead of the number 1.

An array created to store the names of players might be named “player.” The String data of “Mary” would be stored in the first player variable, player(0). “Bob” would be stored in the variable player(1) and “Connie” in player(2). Your bowling scores could be stored as integers in variables named score(0), score(1), score(2), and so on.

0

1

2

3

4

Mary

Bob

Connie

Mike

Linda

This data storage technique is ideal for some common computer processes such as alphabetically sorting names or adding many scores to find your bowling average. Being able to move conveniently from one stored value to another by using the sequentially numbered index value is easily programmed with techniques you will learn about in future lessons.

Databases

In a visit to your local library you likely encounter an electronic database when you search for books by your favorite author, books about horses, or books on the Civil War published in 1965. A library database packages the specific details of every book with additional data called metadata (described below). This combination allows you to search for books in any number of ways and to analyze the information in ways that would be impossible with other data storage methods. A database is a collection of related information and can store the details about such things as items in a warehouse, the individuals in a personnel record, individuals in a telephone book, and transactions on your credit card. The Web offers more databases than you can imagine. There are databases of movies, plants, animals, the human genome, pesticides, chemicals, languages, countries, sports, and on and on!

Database - A collection of information on related items which stored in a form that can be organized and searched.

Structure of databases

While we often see the contents of databases in the form of a table (grid of rows and columns), the table is NOT the database – there may be many tables that make up a single database. A database is a collection of related information made up of entities (or rows)—single examples of the data stored which are sometimes called records. Each entity or record, contains specific labeling details about the record called fields or attributes (columns). If a telephone book is a database, the information about any given telephone number is a record or entity, and the label given to the data such as name, address, and telephone number are the fields or attributes that make up the metadata. The specific data details such as Jose Rodriquez, 401 Main Street, and 213-4567 are the values.

Metadata - A description of the data in a database that enables powerful searches and the ability to answer complex questions about the data.

In order for us to see the information stored within a database, it is usually presented in the form of a table. Let’s use the example of the U.S. Department of Agriculture Plants database (http://plants.usda.gov/index.html) to explore the details of databases.

Here are 3 records or entities of the plant database:

  • The details of these 3 plants plus thousands more comprise the plant database.

  • The complete set of information on each individual plant is a record or entity.

  • The category of each specific detail such as family, growth habit, and a picture is a field or attribute.

  • The specific data such as Meadow Horsetail, Equisetaceae, and a specific picture are values.

Obviously, databases are popular for storing huge amounts of data. But what makes them so powerful? The power of databases results from the actual structure or design of the database for easily and quickly accessing, searching and reporting data. Metadata is data, or information, about the data stored in a database. Meta means “about” in Greek, so Metadata is literally “Data about data”.

For a moment, consider the data 86403. Without some explanation this value is totally useless. But the moment I tell you that 86403 is a zip code, the value has significance and meaning. “Zip code”, in this situation, is metadata. It is information about the data value 86403 that gives meaning to it as the zip code of Lake Havasu City, Arizona. This metadata allows you to search a database for answers to specific questions.

In the example of the plant database, we might create a question or query that seeks to answer the question, “What perennial plant is native to the U.S. and contains the word “horse?” The result of a query referencing the metadata would likely be a table listing all of the plants in the database that fit the description of the word “native” in the field of U.S. Nativity, “perennial” in the field of Duration, and “horse” in the field Common Name. Querying a database to find the answer to a question is a very skilled task valued by organizations and businesses.

Databases are usually created using software applications such as Microsoft Access or Microsoft SQL Server. These database applications streamline the creation of databases, the definition of metadata with fields or attributes, and the population of records or entities with values. Solving problems with queries is also made easier through database software.

Get Real

  1. Complete the array below by filling in the names of your childhood friends. What identifier would you give to this array?

    0

    1

    2

    3

    4

  2. Imagine you are creating a database to record the members of your family tree. What fields of data (or metadata) would you include?

  3. A paper telephone book is an old-fashioned database. Think about questions you could not answer (or at least not easily or quickly) with a paper telephone book that you could with an electronic telephone book.

  4. Using the table below, what records would be returned by the following query? “Select all rows where Name begins with ‘B’, BirthYear is greater than 1990, and FavoriteColor = ‘Yellow’”

    Name

    BirthYear

    FavoriteColor

    Betty

    1901

    red

    George

    1983

    yellow

    Bruce

    1991

    yellow

    Clark

    1998

    blue

    Barbara

    1989

    yellow

Here are some possible answers:

  1. childhood_buddies

    0

    1

    2

    3

    4

    Linn

    Carlos

    Fran

    Maria

    Connie

  2. These are some likely fields or meta data for a family tree data base:

    • First name

    • Last name

    • Mother

    • Father

    • Siblings

    • Spouse

    • Birth date

    • Birth place

    • Occupation

    • Date of death

  3. With an electronic telephone book you could easily locate all individuals with the same first name as you, all of the Smith families living on Oak Street, all of the businesses on Main Street that have the word “hardware” in their name, and all of the Juarez families that are not in the 925 area code.

  4. The only individual who fits the query where Name begins with ‘B’, BirthYear is greater than 1990, and FavoriteColor = ‘Yellow’ is

    Name

    BirthYear

    FavoriteColor

    Bruce

    1991

    yellow

There is a huge quantity and diversity of data that is handled by technology. Data can be stored in either analog or digital formats. Analog data is represented, transmitted, and stored as a wave or continuous stream of information. Digital information is represented, transmitted, and stored in discrete pieces as numerical values.

Computers use a binary number system to store data. The basic electronic storage unit is a bit with 2 states—on and off. These states of on and off are represented by the values of ‘0’ and ‘1.’ Eight connected memory locations or bits are called a byte. A byte can represent 256 binary values. Megabyte, kilobyte, and gigabyte are common measures of storage used in technology.

Using data in computer programs involves identifying the data type, creating variables, naming identifiers to reference the variables, and storing the data in variables.

Data types are based upon the nature of the information to be stored. Common types include:

  • integer—whole numbers

  • double—decimal numbers

  • Boolean—true or false

  • character—individual keyboard symbols

  • String—words or labels

Each data type has its own set of operators such as + or ÷ that produce unique results.

Variables are named memory locations used to store data within computer programs. Variable are created to hold a specific type of data; they cannot hold data of another type. Variables are given names, called identifiers, so that the data they hold can be referred to and used within the program.

There are many complex data containers which can be used to store data. An array is a more complex data container and is a list of sequentially numbered variables with the same name. The numbering begins with 0. This data structure allows for easy access and manipulation of collections of similar type data.

A database is another more complex data structure. A database is a collection of related information which can be easily organized and searched using queries. The data in a database contains metadata. Metadata is a description of the information that enables powerful searches and problem solving. The basic elements of a database are the records of individual items, the fields or attributes that describe the information about each record, and the specific data values for each record.

Things, Things, and More Things

It will come as no surprise to you that the world is far more complex than it was just a short time ago. For just a moment, step back in time with me. The year is 1943 and World War II is raging. A secret military project is underway to create a computer to calculate the trajectory of artillery shells. This computer, named ENIAC (Electronic Numerical Integrator and Calculator), performs in 20 minutes the math that would take humans 3 days to solve!

The ENIAC was over 100 feet long, circling a room 30 feet by 50 feet. It was 10 feet high and about 3 feet deep and weighed about 30 tons. It contained over 18,000 vacuum tubes and programs had to be physically wired into the computer.

The ENIAC used numeric data such as the wind direction and speed, plus the velocity of the shell, to calculate the shell’s flight to the target. While that was quite a feat in 1943, such calculations are common today and occur almost instantaneously in modern computer games. Needless to say, today’s complex world requires considerably more sophistication and power from computers.

We have come to rely upon technology and computers for much in our daily lives - directly in our careers or education, and indirectly through our systems of communication and transportation, our choices in entertainment and recreation, and in essential services such as food production and health care. The tasks performed by computers today involve more than just mathematical calculations. They track airplanes in flight, predict weather conditions, store huge quantities of data in the form of video, graphics and text, coordinate the delivery of products from around the world to markets, and much, much more. In fact, I challenge you to think of one business process or service that is not in some way managed by a computer. The changing needs of a global society and the complexity of keeping it all under control and manageable have changed the way in which programmers think about problems that can be solved with a computer.

In Lesson 1 of this series – Problem Solving in Life and Technology – you categorized problems, selected solution strategies to fit specific problems, and fine-tuned your personal problem solving skills. In Lesson 2 we are going to examine more closely the process of creating a computer solution for a problem. You will experience a new thinking style, which mimics the thinking of computer scientists as they tackle complicated problems.

So let’s begin exercising our brain in this new way.

From the work of computer scientists solving complex problems in the 1980’s, a new way of thinking about solving problems with computers evolved. This new thinking style allows programmers to create organized programs to solve difficult problems, involving interactions between, and dependencies upon, various entities. This thinking style has become known as Object-Oriented Design (OOD). Rather than primarily focusing on the tasks required to solve a problem and the order in which to perform these tasks, OOD focuses on modeling a real-world system and the associated objects in that world to arrive at a solution. With this shift in thinking, we analyze problems by deciding what entities, things, or objects are involved in the situation and what each object must do in order to solve the problem at hand.

Object-Oriented Design -A style of thinking which focuses on modeling a real-world system and the associated objects.

Procedural thinking is a step-by-step process with a definite starting point and definite ending point. It’s like knitting a sweater; start with a ball of yarn, perform specific steps, and end up with a sweater!

Procedural thinking looks like this:

Object-Oriented Design focuses upon relationships between the “things” involved in solving a problem. The order in which the “things” interact, the number of times they interact, and the specifics of the details of the interactions can vary with the situation. Obviously this approach is most fitting to complex problems for which the outcomes can vary depending upon the needs of the user.

Let me give you an example of a complex problem, but one you have likely encountered, which can be thought about in an OOD style.

The Department of Motor Vehicles (DMV) maintains records about you and your vehicles. Perhaps you have several different vehicles such as a car, a truck, or a boat and trailer.

Writing a computer program to handle all of this for your vehicle, as well as for thousands of other vehicles, is very complex. In addition to keeping track of your vehicles, there are interactions between the DMV and the legal system, as well as with insurance companies. You likely are issued your operator’s license by the DMV. In some states the records of voter registration and organ donors are processed and passed along by the DMV. When analyzed like this, what at first seemed like simple bookkeeping becomes a complex problem involving many interactions with, and dependencies upon, other entities.

Object-Oriented thinking looks more like this:

Complex problems with interactions and dependencies are most easily solved with OOD because this is the way humans think. We analyze and plan and resolve issues in our lives by concentrating on “things”, or objects. If you are planning a trip, you think about cars, maps, restaurants, hotels, and attractions. If you are planning a new business you think about products, employees, advertisements, bank accounts, and customers. This is just the way we process the tasks of daily life, large and small. It is also a comfortable way to develop computer solutions for complex problems.

Practicing OOD

As the name suggests, this style of designing computer programs focuses on objects. Since we intellectually build concepts, or mental images, about “things” in our world, this behavior is quite natural. Right now, close your eyes and “think” about your car. Without any effort at all, you envision its color, make, interior, and transmission. You probably quite easily anticipate its capabilities in terms of moving forward, backwards, and braking.

Now, envision – design in your mind – your dream car of the future. What name would you give it? What color is it? What kind of roof does it have? How fast does it go? Can it fly? How does it navigate? Does it interact with other cars? Does it recognize you? Guess what! You just created an abstract object by thinking in an OOD style!

You are solving a transportation need by designing a solution with an object that has properties such as a color and a name, and that has capabilities such as going fast, flying, and recognizing its owner. In addition, you thought about the car’s interactions with other cars on the road and its dependency upon some navigational system. This is the kind of thinking that computer programmers use to create solutions to problems, also.

Think again about the DMV scenario described earlier in this lesson. Let’s design a solution for the problem of processing thousands of vehicle registrations in the same way a programmer might design it with this Object-Oriented Design focus.

Recall that the Circle-Back problem solving strategy learned in Lesson 1 has three steps which repeat until the problem is solved. After the initial step of Representing the Problem by defining the goals, a few questions must be answered in order to devise a possible solution in the Searching for Solutions step.

  1. Programmers using the OOD process first ask, “What objects should be created to solve this problem?”

    In this simplified DMV example it is fairly clear that a vehicle registration object will be able to do most of the tasks required. In a more complex and realistic problem, perhaps other objects would also be needed for issuing operator permits and for communication between the vehicle, the vehicle owner, and other entities. But for now, let’s consider a simplified DMV scenario with very basic vehicle registration processes.

  2. The second question asked is, “What properties should my objects have?”

    A property is a defining characteristic. Objects have many properties. A vehicle registered with the DMV has properties essential for this problem such as the vehicle identification number, the state in which it’s registered, the year, make, and model, the owner’s name and address, and fees paid. The combination of all of these properties defines a specific and unique vehicle registration – your vehicle’s registration. It is important to select only the properties a vehicle must have to complete the problem associated with registering in your state. Extra details that are not critical to the solution are not needed.

    Property - A defining characteristic of an object that is critical to solving the problem.

  3. Finally the programmer asks, “What abilities must a vehicle have to do the work expected of it in this scenario?”

    In computer-talk these abilities are called behaviors or methods. Obviously, to do the work expected of it at the DMV, a vehicle must be able to calculate annual fees, send renewal notices to the owners, issue a license plate number, report traffic violations to the insurance company, print a registration receipt for your glove box, and maybe even communicate with the authorities if it is reported stolen.

    Method - The ability or behavior an object must possess to solve a problem.

A Registered Vehicle

Properties

1F7KB54Y1WU7734 (VIN)

Idaho (state)

2007 Ford Bronco (year, make, and model)

Kim Young (owner)

2548 Main Street (address)

$278.00 (fees)

ACME (insurer)

Methods

Update information

Calculate annual fees

Send renewal notice

Issue a license

Report to insurance company

Print a registration receipt

Communicate with law enforcement

One of the principles of Object-Oriented Design, is the idea that each object should be independent, self-sufficient and wrapped up into a neat package. Think about your personal auto. When you turn the key, the car can start on its own – it doesn’t need to interface with other objects such as an auto mechanic for this to happen (or it shouldn’t!) You also don’t need to look under the hood to see all the engine’s inner workings to make the car do things. The same ideas apply to computer programs. Encapsulation insures that the properties of objects are only modified by methods of the object. The job of maintaining OOD programs is simplified because any changes that are required are isolated due to encapsulation. Any changes to the properties or methods of an object are confined to the object. As you learn more about programming you will recognize why this is so important for efficient and bug-free programs.

Encapsulation - The concept of allowing access to the properties and methods of an object through interactions with the class itself.

Let’s review the process for creating an object-oriented design:

  1. What objects should be created to solve this problem?

  2. What characteristics or properties should my objects have?

  3. What abilities or methods must my objects have to do the work expected of them?

This 3-step questioning process gets at the essential properties and the required methods of an object necessary to solve a problem. The resulting description of an object is called an abstraction. We abstracted – or identified – the essential elements of a vehicle by defining the necessary properties and methods required to solve the problem of handling vehicle registrations at the DMV.

Abstraction - The process of identifying the essential problem details and their relationships from the problem.

Get Real

Let’s have some fun with the process of Object-Oriented Design. Imagine that you are the director of the local animal shelter. Each year you sponsor a pet show for the pets owned by local children, and you are responsible for keeping track of all the winners of the various competitions. There are hundreds of pets and each can compete in up to four competitive events. Pets can earn monetary prizes for each event and the total amount awarded to any one pet is used to determine the “Pet Extraordinaire” designation for high-scoring pets. The owners are recognized with certificates and checks for their winnings.

Analyze this problem by focusing on objects that can represent the various elements of the pet show and perform the work needed to solve this problem.

  1. What object(s) should be created to solve this problem?

  2. What properties should my object(s) have?

  3. What abilities must the object(s) have to do the work expected of it?

Your Object-Oriented Design might be different than mine; that’s one of the great things about designing software – there are numerous solutions to achieve the goals. You’re limited only by your own creativity and your willingness to learn new skills.

  1. A “pet” object should be defined because this is the basic entity that can compete in events, win money and receive awards. If you are very analytical, you might have decided that there could also be other objects such as an owner, a competition, a certificate and a check. We’ll keep things simple and just use 1 object.

  2. Pets have many obvious properties. The trick is to select only those which have some bearing upon the problem to be solved. While a pet has a color and a favorite toy, these properties are not necessary for solving the problem at hand so they should not be included. The obvious details required include the pet’s name, the pet’s owner’s name, the competitive events the pet is participating in (maximum of 4), the prize amount won (if any) for each competition, and the total winnings. You will notice that the name of the owner is needed for printing the check and the certificate. In addition, you should recognize the need for a unique identifier such as an entry number ID for each pet because there could be dozens of pets with the name “Fluffy” who’s owner is “Jim”

  3. The pet object needs to be able to set the amount of its prize for each competition as it occurs during the day and to calculate the total winnings. Additionally, the pet object must determine if the “Pet Extraordinaire” designation applies to itself, and it must print a certificate and a check. These abilities would be defined within methods written in the code of the class.

A Pet

Properties

Fluffy (pet name)

Jim (owner)

Best trick (event 1)

1st place $10 (prize)

Grooming (event 2)

3rd place $5 (prize)

$15 (calculate winnings)

Methods

Set amount of prizes for each category

Calculate total winnings

Determine “Pet Extraordinaire” designation

Print certificate

Print check

In a computer program created in the Object-Oriented Design (OOD) style, programmers translate these abstractions into the code of a specific computer language. The code which describes all of the object’s properties and methods is called a class. We can think of a Class as the blueprint, and an Object as an instance (or specific example) of that Class such as the house down the street.

Class - A computer code segment that describes an object’s properties and methods.

To solve the DMV problem we must create a “vehicle” class which defines all of the properties of a “vehicle” object, and lists the steps to be executed in each of its methods, necessary for the tasks of registration. The class in this DMV example would be named “Vehicle.” The name of a class is capitalized.

Classes are typically segments of larger programs. Don’t worry that you do not yet understand how these segments are combined into working programs. The pieces will come together as you learn more and have the opportunity to study a particular computer programming language.

Here is an example of the Vehicle class described in pseudo-code (human-readable words):

Class Vehicle

Property Vehicle_Identification_Number

Property Owner_Name

Method Calculate_Fee (X amount)

Method Issue_License (X number)

The process of creating code that follows OOD is referred to as Object-Oriented Programming (OOP). I’m only telling you this now because sometimes OOD and OOP are used interchangeably; they essentially mean the same thing – solving problems by focusing on objects with properties and methods which model the situation.

Object Factories

One way to think about a class is to visualize it as an “object factory.” Obviously, to be useful, a DMV program must create and access more than one vehicle registration. In a computer program that models the DMV, the Vehicle class serves as a factory to produce as many specific vehicles as needed. Your car registration is defined differently from a motorcycle or a boat registration. Each of these registrations, with all of its unique details, is stored separately in the computer’s memory. Because of this, each vehicle can be located in the computer's memory and manipulated without affecting any other vehicle.

To visualize this, think about an automobile factory. Each auto is made according to different specifications, depending upon the orders placed. As each automobile is produced, it’s assigned to a unique storage location in the factory’s parking lot. This is similar to the way a class that creates vehicle registration objects operates. You can think of the automobile factory as a NewAuto Class, and each new automobile is an object of type NewAuto. Going back to the DMV example, each vehicle is made uniquely to the specifications of a registration order and stored independently of the other vehicle registrations. Each vehicle registration has its individual properties and capabilities that determine its uniqueness, just as each new automobile in the factory lot has properties that make it unique from all others.

Analyzing Problems

So how many classes do I really need to solve a problem? This is a serious design question. Trying to figure out the object or objects involved in a real-world problem that can be modeled in a computer program is a challenge! Remember it takes practice and patience to learn a new thinking style. While there are no hard-and-fast rules, the answer can be determined by following these hints and guidelines that make OOD easier:

  • Visualize a problem by animating in your mind the actions that must happen as the problem is solved. Turn the process into an animated cartoon. Let inanimate objects or abstract things “come to life” with properties you can see and actions you can witness. The Disney animation Fantasia provides a good example of inanimate object coming to life.

  • Count how many different “things” in your cartoon are needed to solve the problem. These actors in the animation might be the objects that will eventually become represented by classes.

  • View objects with a narrow lens. Focus closely on the essential details of a potential object and ignore extraneous data.

  • Give objects only the most essential properties and methods to address the problem.

  • Methods that can be described as “supporting the work of this object” but not directly tied to the object should be defined in other object types.

Remember, an abstract object is just that – abstract. It is designed to model events in the real world, not duplicate them. Selecting the critical objects in a problem and determining the necessary properties and methods, is a skill that develops with practice. Deciding upon the classes for a computer program is a problem with no defined outcome or defined solution. There are multiple solutions to these design questions. The Circle-Back problem solving strategy works well. There are plenty of opportunities to start back at the beginning. Think of Object-Oriented Designing as solving a mystery with clues and relationships of varying levels of importance. Jump in, give it a try, and have fun.

Get Real

Practice a little OOD by thinking about the problem of managing a grocery store inventory. The manager of the store needs to keep track of the location of products on the shelves, order replacement products when the supply gets low, remove items when the “sell-by” date passes, discontinue unpopular items, and pay suppliers.

Animate this problem in your mind by creating a cartoon of “things” that act.

  1. What is the primary object you see?

  2. What properties do they have that are essential for managing an inventory?

  3. What do they do?

  4. Who or what do they communicate with?

  5. What messages do they receive or send?

  6. Do these objects need help from other objects?

Because this is a highly creative activity and some people have better imaginations than others, your answers will likely be very different from mine. That’s great because there are no perfect answers and creative problem solving is valued in computer programming.

  1. A variety of grocery items: oranges, cornflakes, salmon, tomato soup, yogurt, etc.

  2. They possess a UPC code that includes a name, size, producer, and price. There is also a shelf locator, delivery date, lot number with sell-by date, an ideal quantity number, and a number-on-hand value.

  3. These items keep track of the number on hand, order more when the supply is low, send notices when the sell-by date is expired, change their prices, and pay suppliers.

  4. The cash register for printing receipts, the stock workers, the producer

  5. They send messages to reorder, remove from shelf, or discontinue. They receive messages from stock workers to change their price, location, or ideal quantity to keep on hand.

  6. Yes - the cash register, an ordering object, a banking object, a record keeping and printing object.

There are many more concepts and complexities of this powerful OOD style which you will learn when you begin programming. But for now let’s consider two more ideas which are real power boosters for programmers.

As you might have already guessed, the creation of classes as separate, independent, encapsulated portions of code makes them reusable. If you create a class representing an inventory item in a grocery store program, the same code could likely be reused in a program for a hardware store or a warehouse company for keeping track of products and inventory.

Code reuse enables programmers to work efficiently to build huge, complex programs by assembling different bits of already existing classes into new creations. You can think of classes as parts in a Lego set. A toy wheel can by used in building cars, trucks, mopeds, and more.

Code Reuse - Building computer programs with components such as classes which can be applied to similar problems in other programs.

The fact that code can be reused in many different situations has led to the creation of huge collections of classes called libraries. Programmers can search through these libraries to find just the “object” they need. You have likely, but unknowingly, encountered code reuse. For example, nearly every computer game, from your favorite Solitaire to Project Gotham Racing, employs random numbers. Programmers who need random numbers for their program don’t have to write the code to generate these random numbers themselves. They just need to add the random number class to their program, send the correct request message to it, and the class takes care of the rest by producing a random number to be used in the game.

The second power booster for OOD is inheritance of classes. To visualize this, envision the diagrams used to represent your branching family tree. Near the top are Great-Great-Great Grandmother and Grandfather Lee. Each downward branch represents the next generation of Lees, each of which has inherited many characteristics of the previous generation, but has many unique traits of its own. This same concept is used in computer science to build up and refine the objects created from classes.

Inheritance - A hierarchy of classes in which the properties and methods of the top level or parent class extend into each lower level or child class.

The easiest example to think about at this stage of your learning is the Pet class we created earlier in this lesson. You probably recognized it as being rather simplistic for a pet show, in part because any pet show is going to have more specific animals than just “pets.” There will be dogs, cats, birds, and probably even a lizard, or two. For purposes of keeping track of the entrants and their winnings, all of these pets have some traits in common. They each have an owner, a name, and winnings. You can imagine a more sophisticated scenario where there are competitions unique to each type of pet. Birds might compete for the most beautiful feathers and dogs could compete for the best trick.

This refinement can be created through class inheritance. Without getting bogged down in the programming details at this point, imagine this: You create a Pet class that has all of the properties and methods that are the same for every pet in the show. These would include properties such as its name and owner. Next, you create a class just for dogs. You tell the computer that a dog is just a more sophisticated pet (you already know that if you own a dog!) and that everything that is programmed in the Pet class applies to this Dog class. Essentially a Dog “is a” Pet. In the Dog class you define additional, unique “dog” properties such as weight and trick competition earnings. It might even have some methods that no other pet has. The same process of defining this “second generation” of classes would apply to the Cat class and the Lizard class. You could expand this to an additional level of inheritance so that another class – the Golden Retriever class – would inherit from the Dog class and the Siamese class would inherit from the Cat class. Inheritance is not limited to just one class inheriting from another class. Numerous classes can inherit so you can add many types of dogs and cats.

This how you might visualize the relationships between various classes in a pet show:

You can imagine this same technique used with the DMV registration problem and the Vehicle class. If the Vehicle class is the “parent” class at the top of the hierarchy, there could be “children” such as a Car class, a Truck class, a Motorcycle class, or a Boat class. You might even recognize that this could be carried even further if we make a Semi-trailer class the “child” of the Truck class. Logically it follows that a Semi-trailer is just a more specialized form of a Truck. With this inheritance technique programmers build powerful, sophisticated, and flexible programs.

This is how you might visualize the relationships between various vehicles registered at the DMV. There are certainly many more types of accounts that you can add to the structure.

Here are a couple examples of inheritance described in pseudo-code (human-readable words):

Class Siamese Class Truck

Inherits Cat Inherits Vehicle

Property eyeColor Property maxWeight

Get Real

  1. Think about your experiences online. What objects or tasks have you observed that are repeated in a variety of experiences that might be examples of code reuse?

  2. Imagine you are designing a program to handle the personnel records and payroll for a hospital. Because there are many distinct classifications of employees with unique descriptions and pay schedules you decide to use inheritance as you develop the classes for the program. What will you name the parent class? What are some of the child classes you might want to create? Draw a tree to represent the relationships.

Here are some possible solutions:

  1. Your answers might include such online objects such as “shopping carts” and “registration forms” that are found on shopping and membership sites. You might have mentioned tasks such as shopping checkouts, downloading, and search procedures.

  2. There are many structures you could design to represent the inheritance relationships among classes representing hospital employees. The actual design would be influenced by the specific goals of the program. One possibility is to make a generic “parent” Employee class with “child” classes of Medical, Operations, and Management employees. The next level of “child” classes might be Doctor, Nurse, Food Service, Custodian, Administration, and Clerical employees. The important consideration is that each “child” class inherits properties and methods of its parent class and represents a greater level of refinement through its unique properties and methods.

Events and messages are two concepts vital to actually using objects in a computer program. An event as defined in computer science is not too different from your own personal definition of the term “event.” An event in the context of computer science, and in daily life, means “something happened to catch my attention.” An example of an event in daily life would be a lightning strike or the ring of a doorbell. Each of these events would catch your attention and perhaps cause some response from you. In computer science, the click of a mouse or tap of a key is an event. Likewise, the computer will take notice and might respond to the event if it has been instructed to do so by the program that is currently running. Just as you would not likely respond to the neighbor’s ringing doorbell, the computer doesn’t necessarily respond to every mouse click or key tap that occurs. A message is an instruction sent to an object at the occurrence of an event that requests the object to perform one of its methods.

Event - An action such as a mouse click or a key press which is recognized by a program and may prompt some action by the program.

To better understand this concept of events and why it’s important to OOD, let’s look over the shoulder of a DMV clerk as he or she interacts with a customer. The interaction might go like this:

Clerk: “Hello. What can I do for you today?”

Customer: “I would like to renew my vehicle registration.”

Clerk: “What is your license number, please?”

Customer: “385-CJK”

Clerk: Enters the numbers 385-CJK into a field on the computer screen and clicks on a “Find Registration” button.

Behind the scenes the button click action by the clerk is interpreted by the computer as an event – Ta-Da! Something happened! Because of the code in the vehicle registration program, the computer responds by sending a message to the computer system to find in its memory the specific and unique vehicle object associated with this number. Next it sends a message to that specific vehicle to display some of its properties on the screen where the teller sees Kim’s name, address, and description of the vehicle and the calculated the registration fee.

Clerk: “This year’s fee is $180.00. Has any information changed in regard to this vehicle, Kim?”

Customer: “Yes, my address has changed. I now live at 23 S. New Haven Street.”

Clerk: Enters “23 S. New Haven Street” into a field and clicks on the “Update Owner Information” button.

Another button click event has occurred and a message is sent to the vehicle object to change the recorded address of the owner. And perhaps yet another message is sent to this vehicle object to send its updated owner information, as well as the renewed registration to the printer.

Clerk: “Your registration has been renewed and your address changed. Here is your new registration copy for the glove box.”

Customer: “Thank you”

Clerk: “You’re welcome, Kim. Please come again”

Clicks on the “End Transaction” button initiating another event which sends a message to the system to close access to this particular vehicle.

How does this occur inside the code? After a programmer writes the code for the Vehicle class (“vehicle” object factory) to create these vehicle registration objects, he or she creates another segment of code called the graphical user interface (GUI) which interacts with the class, and objects created from the class, through messages. The graphical user interface is the part of the program visible to the user – in this case, the DMV clerk. When a vehicle owner registers a new vehicle, the clerk uses the GUI part of the program as a tool to call upon the class by sending a message to create a specific vehicle object with a unique set of vehicle properties for this specific customer. In computer terms, this step to create new, unique objects and store them in memory is called instantiation. The Vehicle class creates an “instance” of the class. This instance is the object. In other words, the Vehicle class creates a new vehicle object based upon the specific “blueprint” for a vehicle as defined in this “vehicle factory” class and stores it in the computer memory.

Instantiation - The creation of a new object from specifications described in a class.

This is what the code to create a new object from the Vehicle class looks like in pseudo-code (human-readable words):

Create MyCar as a new Vehicle(list of property values)

Conceptually, the clerk uses the graphical user interface to trigger events which send messages to the class. These messages can be commands either to classes to create new objects, or to previously created objects to execute methods. In the DMV example, the clerk uses the application by entering information and clicking on buttons which create events that cause messages to be sent to the Vehicle class to create new vehicle registrations or to record transactions for a specific registration.

Occasionally a message sent to an object must carry with it some additional details. A “Update Information” message sent to a specific Vehicle object must carry with it new information about the persons name or address. This additional information sent with a message is called a parameter.

Parameter - A value sent to a method with a message that is needed to perform the work of the method.

This is what the code to send additional information in the form of a parameter looks like in pseudo-code when the message to update information is sent to a specific vehicle:

MyCar.UpdateInformation(23 S. New Haven Street)

Get Real

Let’s explore events, messages, and parameters in a common computer application.

  1. Open Microsoft Word or other word processor. Write a short paragraph describing your understanding of OOD at this time.

  2. Now experiment with some of the common commands you use as you edit in a word processor. Complete the chart below.

Task

Event

Message

Parameter

Find




Insert hyperlink




Underlining text




Because there are several ways to perform the indicated tasks your answers will likely vary from the answers below. The important concept is to analyze what event you are triggering, the message being sent to the computer by that event, and the additional data or parameters the computer will need to complete the intended task.

Task

Event

Message

Parameter

Find

Mouse click

Enter Key pressed

Open find dialog box

Search through text

None

Characters to find

Insert hyperlink

Mouse click

Return

Open link dialog box

Add link to text

None

URL

Underlining text

Mouse click & drag

Mouse click on U

Select chosen text

Underline text

None

Selected characters

Object-Oriented Design (OOD) is a style of analyzing a complex problem by focusing on the “objects” involved in the solution. Three questions are asked in analyzing a problem:

  1. What objects should be created to solve this problem?

  2. What properties should the objects have?

  3. What abilities must the object have to do the work expected of it?

The process of abstraction involves identifying the essential traits of an object that are necessary for the solution. Properties are the defining characteristics of an object and methods are the behaviors or abilities of an object needed to solve the problem.

Objects are defined and encapsulated in code segments called classes. Classes contribute to efficient programming because they can be reused in many different programs. Creating a new object from a class is called instantiation.

Inheritance enables programs to reuse code and to extend general classes into more specialized classes. Child classes inherit properties and methods from parent classes and have additional, unique properties and/or methods of their own.

Events are actions that occur during the use of a computer program. Events are noticed by the computer and can result in a message being sent to a class or to a particular object to carry out an action. Sometimes when messages are sent to objects additional information is needed to perform the task. This additional information is called the parameters.

Join me in lesson 3 to learn how computers represent, store, and use data such as numbers, words, and more, in computer programs.

Problem Solving in Life and Technology

Problem Solving in Life and Technology

Problem solving skills are essential to success in every aspect of life. You depend upon these skills for success in your personal life and finances, in your family and civic responsibilities, and in your professional career. Everyone has skills in problem solving yet you may have wondered how it is that some people are so good at it in some parts of their lives, but so miserable at it in other parts. We all know individuals who have no “common sense” yet are “book smart”, and we know others who have incredible skills for managing their personal finances but fail miserably in their relationships. We find ourselves wondering how they (and at times, ourselves) can be so inconsistent in what appears to be simple problem solving skills. The truth of the matter is that problem solving is not simple. Problem solving skills take practice and purposeful application of rules and processes to fit specific types of problems. Most people learn these skills through interactions with family and friends, in school, or during career training. Some of it is so ingrained in our personality that we are unaware of our own thought processes. For example, when you get dressed in the morning, you probably don’t have to think through the articles of clothing you will need (pants, a shirt, 2 socks, etc.), and you probably don’t consciously determine ahead of time what order to put them on in.

There are many different kinds of problems to be solved in life and in the field of computer science, and consequently, there are different strategies to solve them. People engaged in technology and computer science share this dependency upon extraordinary problem solving skills for creating all of the conveniences, gadgets, and modern wonders we have come to depend upon. Let’s start our discussion of problem solving with a description of types of problems and explore how each of these types can be reflected in technology and computer science. Then, we’ll look at the strategies to solve these types of problems, the unique strategies of solving problems in technology, and finally, consider ways to improve one’s problem solving skills. As we go along you will have the opportunity to think about problem solving from a personal perspective.

Problems with clear-cut answers and solutions

Problems with definite answers that are solved with prescriptive strategies are the type that many of us spent years practicing in school. These are typically the problems at the end of the chapter in a math, physics, or computer science textbook. We learned that in order to get the right answers all we need to do is follow the rules described in the chapter. If only life were so simple! Individuals who are very adept at this type of problem solving are sometimes called “book smart” and are very skilled at remembering the rules. Sometimes this type of problem is referred to as being highly structured – no guess work required.

Indeed, some of life is clear-cut; balancing your checkbook, following a recipe, putting together a model, installing new software, and writing a formula to calculate the average rainfall for the year. Unfortunately, most of the big challenges in life, and in computer science, fall into other categories of problem solving.

Problems with a fairly defined outcome but with many solution strategies

Things start to get messy when we’re confronted with problems that have a fairly defined outcome but for which the solutions can be as varied as the individuals you meet in your daily commute. This type of problem confronts us on a daily basis. In comparison to clear-cut problems and solutions, these problems are only moderately structured.

In your personal life you need to feed yourself and perhaps a family. The defined outcome is that menus be nutritious, safe, and within your budget but the solutions to the problem are as varied as the cultures and tastes of the world!

Examples of this type of problem in technology include a spreadsheet to plan a budget or a job schedule to coordinate employee’s shifts. The solution is constrained by various factors such as the number of employees, the duration of each shift, etc., but the form and design of the solution can be quite diverse. For example, creating the local area network for a small business requires a fairly straightforward application of hardware, but analysis and predictions of how employees will use the network, the volume of traffic, the future plans for expansion, and the changing business needs, will all impact the final solution possibilities.

This type of problem requires not only the “book smarts” to identify the data required and the constraints of the problem, but also a certain level of creativity to imagine all the possible solutions. The technology that makes up everything from our home security systems to our automobiles, from appliances to personal entertainment devices, have created a demand for individuals skilled in solving this type of problem.

Problems with no defined solution or defined solution strategy

Now things are really getting complicated! Problems with various acceptable solutions, no known solution, or perhaps no solution at all, and a myriad of strategies to find an answer (most yet undiscovered), tend to frustrate us the most. They lack almost all structure so we are left to fend for ourselves in order to create the structure through our own values and priorities. We deal with problems in this category daily, but they often require much more time and effort to solve. We are confronted with questions such as: Where should I live? What career should I train for? What is the cure for cancer? How do we achieve world peace? What is my purpose on this earth?

We also face this type of problem with technology in our lives. What computer system will best fit my needs? How do I select a communication service? How should I, personally, deal with privacy and security? What is my role as a cyber-citizen? Sometimes we can call in an expert; sometimes we just have to solve the problems ourselves.

And of course, in the world of computer science, computer scientists, programmers, and others, work to solve this type of problem as the very core of their profession: How can a network to manage the pharmacy needs of customers across the country or around the world be created? How can the huge amounts of data gathered by national security experts be manipulated and analyzed to protect the lives and property of citizens? What simulation can be programmed to predict, even divert, hurricanes? What can be done to minimize the effects of climate change? Is there other life in the universe? What programming strategy will discover the essence of life reflected in our chromosomes?

The good news is that this type of problem generates fun and creativity in life, and in computer science! The bad news is that this type of problem solving requires effort, knowledge, and a deliberate thought process for most of us. More good news is that problem solving is a skill that can be learned and enhanced.

Get Real

Analyze your ability to solve problems by thinking through the following questions.

  1. Select one area of your life to reflect upon - your hobby, job, family, relationships, or civic role. Which category of problem solving are you most comfortable with in this life role?

    1. Problems with clear cut answers and solutions.

    2. Problems with fairly defined outcomes but many solutions.

    3. Open-ended problems where I can experiment and be creative.

  2. How did you learn the skills to solve this particular type of problem in this part of your life?

    1. My family modeled and reinforced these skills.

    2. My teachers taught these skills.

    3. I learned them through trial and error.

    4. I modeled after others who were successful in this role.

  3. Which problem solving type offers the most difficulties in this life role?

    1. Problems with clear cut answers and solutions.

    2. Problems with fairly defined outcomes but many solutions.

    3. Open-ended problems where I can experiment and be creative.

  4. For each of the following problem solving categories, identify a life role for which this is your best problem solving skill set. Think about your life roles as a parent, a friend, a volunteer, a student, a citizen, or a wage earner.

    1. Problems with clear cut answers and solutions.

    2. Problems with fairly defined outcomes but many solutions.

    3. Open-ended problems where I can experiment and be creative.

  5. Assess your current problem solving skills in regard to technology. In which of these technology areas have you encountered problems for which you have had the problem solving skills to solve?

    1. Configuring technology components such as entertainment systems

    2. Trouble shooting or repairing hardware

    3. Using software such as spreadsheets or audio editing software

    4. Creating your own presence on the Web with a Web page or blog

    5. Expressing creativity with graphic, music or video software

    6. Analyzing problems and writing computer programs to solve them

    7. Other specialty areas

  6. Describe a frustrating technology related problem which you recently encountered. Remember your comments; we will return to this question later.

Your answers will likely be different but here are some examples to get you thinking.

  1. Kim might select her family role to think about these questions and decide she is good at solving problems which have fairly defined answers but multiple solutions strategies.

  2. She learned these skills as a child from her family who often discussed family and world events in terms of the possibilities that existed for solutions.

  3. The problems that are totally open-ended present her with the most difficulties. She likes to find the best solution and it’s difficult to recognize it with these types of problems.

  4. She decides that she is best with problems that have clear-cut answers in her role as an engineer technician. She is also a good problem solver in her cooking hobby because she likes to experiment with recipes clipped from magazines. Kim is best at solving totally open-ended problems in her role as park commissioner on the city council.

  5. Because of her engineering background, she is an excellent problem solver with configuring technology components and trouble shooting hardware. She has never tried to write a computer program so she suspects it might be frustrating to start with.

  6. Recently Kim created a blog to share her ideas and experience from her city council work. She just can’t make it look professional or feel inviting.

Your new understanding of the basic categories of problems faced in modern life is the first step to becoming a better problem solver. Once you recognize the type of problem you are faced with, you can select an approach that will yield the most satisfactory results. Certain solution strategies generally work best with specific types of problems.

Request-Response-Result Strategy

The Request-Response-Result problem solving strategy is likely the one you are quite comfortable with because you practiced it for years in school on those 10-question worksheets and the review problems at the end of the chapter in the chemistry textbook. It’s the strategy that correlates best to the clear-cut category of problems; a request is made, you respond with steps of a rule, and the one and only correct result is achieved. It works perfectly when applied to clear-cut problems.

This strategy rarely works well when applied to other types of problems. Typically, people who go through life using only this approach to problem solving are said to see life in terms of black or white. Sadly for them, they are unaware of other strategies that work more successfully in solving many problems faced in today’s world.

In the world of technology, individuals don’t encounter too many of these problems for which they must apply the Request-Response-Result strategy because technology has been created to do it very effectively for us. You own a calculator to do math, complete with built-in square root, average, minimum and maximum functions. If you are an engineer, your computer likely has many functions built-in to solve problems of this type that are unique to your work. The same can be said for almost any job. A store attendant uses a computer to automatically calculate a discount, the tax, and the change. Emergency responders use computers that monitor patients and determine medicine dosages. Pilots use devices to determine arrival times based upon navigational data. Your microwave oven is even programmed to pop the corn with the touch of one button and the word processor I use follows rules of grammar to correct my writing!

The Request-Response-Result is the type of problems that computers are very good at solving. A computer can quickly accept a request, apply a response based upon any number of rules, and display the result. Making computer solve these problems is the work of computer programmers who create programs for computers and a wide variety of devices with embedded, or hidden, computer components in appliances, automobiles, and gadgets of all sorts.

Embedded - A hidden component of a larger system such as the computer components in your car.

These programmers design the algorithm for the computer to follow to match the data, the specific conditions, and criteria for a satisfactory result.

Algorithm - A precise and systematic method for solving a problem.

Certainly there are times while working with technology at which we use this problem-solving strategy ourselves. Successfully plugging in the components of your computer is simple if you follow the rule to match the color of the cord with the color of the socket. Installing software is a breeze if you follow the specific rules of the online prompts. Even the construction of a fairly complex PowerPoint presentation has been made easier with wizards that guide you in following the rules.

The IDEAL Problem solving strategy

With a name like IDEAL you would think that this is the best problem solving strategy available. This strategy was developed during the 1960s and 70s and is based on the idea that if you learn the strategy you can apply it to any problem situation on any topic. It is useful in many situations, and it fits well with the type of problem that is has several possible solutions. It lacks the opportunity to redo the effort because there is no built-in step for starting over.

There are 5 steps that represent the acronym IDEAL.

  1. Identify the problem

  2. Define the problem by sorting through the relevant information

  3. Explore the possible options through brainstorming

  4. Act on the strategy selected

  5. Look back and evaluate the results of your actions

This strategy can be applied to many technology problem areas, as well as the problems and challenges of daily life. When you’re called upon to give a presentation to your work group you likely use this approach. In order to select the best format you ask yourself, “What is the goal of this presentation?”, “What constraints do I have in terms of equipment, time, skills?”, and “What is possible – PowerPoint, chalk talk, slide show, or Live Meeting?” You select a format for your presentation based upon your analysis, and after the event, you critique the outcome and add it to your list of experiences to draw upon the next time you make a presentation. This style of problem solving has likely served you very well.

The IDEAL approach can be used in selecting computer components and software, configuring a local network, and writing computer programs to solve simple problems.

The Circle-Back Model

Recent research into problem solving has found that there is considerably more to effectively solving complex problems than just knowing the steps of some particular technique. Many problems must be approached from different angles through a process of trial and error, so the opportunity to evaluate the outcome and try again is critical. The Circle-Back strategy is particularly effective in addressing technology-related problems, especially the complex problems that programmers work on. Creating software to model weather patterns, or analyze economic strategies, or control robots is not nearly as clear cut as the previous problem solving strategies would imply. The Circle-Back strategy is used when “failure is not an option”; when the problem might be worked on indefinitely and it is likely that it could take a great many cycles to arrive at a solution.

The Circle-Back method involves 3 basic steps that repeatedly cycle until a solution is achieved. Each major step has many sub-components that are customized to the situation and must be accomplished. The beginning point is to Represent the Problem clearly and fully. This step involves calling up all relevant information that impacts the problem, establishing the goal, and defining a starting point. In the world of technology and software development, this phase can take a long time and require the expertise of many individuals.

The Search for Solutions step includes refining the goal based upon the research and work done in the first step and developing a plan of action to reach the goal.

The step to Implement the Solution is the action phase and it contains the critical activities of executing the plan created in the previous step and evaluating the results of the action. Here is where an important juncture occurs; if the results do not meet the goal, the process is started again back at the first step of Representing the Problem and the Circle-Back process continues until success is achieved.

This approach to problem solving is especially valuable to computer scientists. Many of the problems they work to solve are huge and complex without predefined solution sets. The problems must be broken down into sub-problems. Each of the smaller problems is processed through the 3 basic steps and when all the sub-parts are working, the whole plan can be constructed, implemented, and evaluated.

So how does this work in technology? Imagine the task of creating a video game for the Xbox. Stating the goal is almost more than one can think about. The game must have a great story line, realistic graphics, exciting animation, fast response time, and on and on. How would you even begin? It might be reassuring to know that big production computer games require a team of hundreds of individuals. There are artists, writers, programmers, audio specialist, musicians, marketers, testers and many more. Each specialty team is responsible for its own goals and problem solving cycles. The Circle-Back approach is especially effective in complex, open-ended problems that require as much creativity as they do analytical problem solving skills.

Get Real

Analyze these technology situations. Select the solution strategy you would use to solve the problem.

  1. The network is infected with a virus and needs to be cleared.

    1. Request-Response-Result

    2. IDEAL

    3. Circle-Back

  2. Your ISP (Internet Service Provider) notifies you that your mailbox has exceeded its limit.

    1. Request-Response-Result

    2. IDEAL

    3. Circle-Back

  3. Your engineering team is assigned to reprogram the assembly line robots at the local automotive plant.

    1. Request-Response-Result

    2. IDEAL

    3. Circle-Back

  4. Your supervisor asks you to analyze recent sales data in a graphic format for the department meeting.

    1. Request-Response-Result

    2. IDEAL

    3. Circle-Back

  5. Your company receives the contract to customizing the medial records software for the nearby hospital.

    1. Request-Response-Result

    2. IDEAL

    3. Circle-back

Answers:

  1. B; Ridding a system of a virus fits the IDEAL strategy because it has only one acceptable solution but many possibilities in terms of the tools and processes to use, as well as steps to insure future security.

  2. A; Clearing an email account is a clear-cut problem with the required response of emptying one’s mailbox of unneeded files. It fits the Request-Response-Result strategy because there is only one outcome and one solution.

  3. C; Designing robotic systems is very complex with many possible solutions that fit the Circle-Back strategy. Engineers will break the problem into small sub-problems establishing sub-goals, creating solutions, testing, and evaluating, and likely revising many times before constructing the entire system.

  4. B; Designing the graphics to represent given data fits the IDEAL strategy because the outcome is fairly defined with several solutions to choose from for this single situation.

  5. C; Customizing any system requires multiple cycles through the Circle-Back process through thorough analysis of the situation, careful determination of the goals and sub-goals, implementation of a detailed plan, and evaluation of its effectiveness.

Because of recent research, we now recognize that understanding and applying a strategy to a problem isn’t enough to effectively solve the problem. Researchers have found that there are many other factors that build good problem solving skills. In addition to selecting an appropriate strategy to fit the problem, you must have a deep base of knowledge in the subject area of the problem. Additionally, individuals need practice with a strategy within the context of real-world problems. This new thinking on the importance of having a solid base of knowledge in a particular subject has changed the way educators and trainers teach problem solving strategies.

This must seem like a vicious circle; how can you become a good problem solver without knowledge and experience, both which require problem solving skills to achieve? My advice is to take it slow and easy, learn as you go, call for help when you need it, and continually try to piece together what you already know about the topic with what you are experiencing in a current problem.

Self-Help Strategies

  1. Start with a realistic assessment of what you know and the experiences that can be applied.

  2. Analyze the situation – break it into smaller challenges

  3. Draw upon your experiences with similar scenarios

  4. Figure out what you need to know and where to find it

  5. Come up with a plan

  6. Implement it

  7. Test it

  8. Repeat as necessary

  9. Evaluate the process and add to your experiences account

Try it out

Imagine that you are having difficulties with the wireless network at home. It won’t connect each family member’s computer to the printer in the home office. In a panicked attempt to solve the problem, you unplugged everything, find the printer software, reinstalled it on every computer, hook each computer directly to the printer in hopes of helping the computers “find it”, and eventually give up and call upon the fifteen year-old living next door.

If you had the opportunity to apply strategies learned in this lesson, what might you have done differently?

You would likely recognize that this is a problem that has only one acceptable outcome but perhaps there are several actions that can be tried to correct the problem. If you could redo the situation with the problem solving strategies you just learned, you might have called in the fifteen year old first (just kidding!).

Likely you would have used the Circle-Back method with more time spent on the first step of assessing the problem and recalling other experiences you have had with the home network. You might have begun the debugging process by breaking it into smaller pieces – checking if each computer had printer drivers, checking the wireless signal strength, and the printer itself. You would have recalled what you know about networks in general. Perhaps you would have checked the computer manual to discover where network settings are controlled, you might have searched for pertinent information in the printer manual, and maybe even checked online help forums. You probably would have telephoned a friend to gather more insights from her experiences. After learning all you could, and thinking about past experiences with your wireless network, you could formulate a plan of possible actions, execute each action, evaluate the results of each action, and try other strategies until the problem was solved or until you decided to call in an expert.

Debugging - A method of discovering the source of errors causing problems in a system or process.

Certainly following a problem solving strategy doesn’t guarantee successful results every time. That is why the Circle-Back strategy is effective; it’s not an all-or-nothing scenario, and it offers opportunities for organized skill development both in the context of the specific problem at hand, and in problem solving in general.

Get Real

Look back to the technology problem you described for question 6 in the first “Get Real” section of this lesson– Describe a frustrating technology related problem which you recently encountered. Solve it again in your imagination by using the strategies from this lesson to identify how you might have arrived at a better solution with less frustration.

In hindsight, what learning occurred in that experience that you can apply to a future situation?

Your answers will likely be different but here is what Kim might have said:

Recently Kim created a blog to share her ideas and experiences from her city council work. She just can’t make it look professional or feel inviting.

Her revised strategy:

  1. Kim knows nothing about blogs but can draw upon her experiences writing council reports for the mayor.

  2. The task can be broken into smaller problems: understanding how blogs work, creating an attractive online persona, and developing a journal writing style.

  3. In college she was a reporter for the school newspaper which offered a similar experience.

  4. She decides she needs to learn about blogs, so she will visit several and ask a blogging friend for advice.

  5. Her plan includes researching blog sites for helpful hints, finding a site that offers an appealing interface, and sharing her entries with family and friends before posting.

    Interface - The medium through which users interact with the computer. It might include button and menus.

  6. She plans to create a time schedule with several sub-goals to make the project manageable.

  7. After implementing her plan she will test it by seeking input from citizens, evaluating the impact of her ideas, and then continue to grow and mature in the world of blogs by modifying her work as indicated from the feedback and self evaluations.

In hindsight, Kim knows that this frustrating experience taught her that time spent gaining knowledge and looking at good examples is time well spent and that writing is a skill which can be transferred to new technologies.

All of us have a whole collection of rules we recite to help us with our grammar or to calculate the tip amount. These general “rules of thumb” are called heuristics. They provide a general plan for solving problems. The strategies for solving problems described earlier in this lesson fall into the category of heuristics; they offer general guidance for our actions. Computer programmers use problem solving strategies – or heuristics – to arrive at the general, overall, plain language solutions to solve problems using computers. However, computers cannot interpret our normal language; they do not make assumptions, draw conclusions, or interpret our meaning. Because computers cannot read our minds (yet!), the instructions they follow must be extremely detailed and presented in a logical order that leaves nothing to guess work. This begins the action phase – writing software – for solving problems using computers.

Heuristic - A general guideline or rule-of-thumb for solving problems.

Algorithms – The Recipe in Computer Science

Writing software, even simple programs, requires a detailed series of steps for the computer to follow. Computer programmers, sometimes called “software developers”, begin by creating a sequential list of tasks which the computer must perform in order to arrive at a solution. This task list must be translated into a specific language which the computer can understand. This list of steps is called an algorithm. Don’t let the word scare you. Algorithm is just a technical term for “recipe.” Creating an algorithm requires critical thinking about the problem plus careful analysis of the situation, and goes hand-in-hand with problem solving strategies.

Algorithm - A precise and systematic method for solving a problem.

To think about the detailed requirements of a computer program try this: Write out the instructions for making your favorite sandwich. Now, pretend you are a robot that has no history of food preparation, and no experience with making a sandwich. Envision what happens when you execute the step to “Top with brown mustard and slice.” Will the robot know you mean to open the jar of mustard, scoop 1 teaspoon from the jar, spread it evenly over the pastrami, top with another slice of bread (ideally taken from the wrapper!), and use a knife to cut from corner to corner? It’s likely that the assumptions another human would make about creating a sandwich would be skipped by the robot and you would end up with the jar of mustard sitting on top of the meat and a big mess when an attempt to “slice” occurs.

Execute - To carry out a specific instruction step such as a command in a computer program.

Writing a computer program involves a detailed algorithm containing the exact steps to execute in order to arrive at the desired outcome. Let’s look at the algorithm for a task a computer could be programmed to complete – calculating the total cost of the pizza you ordered.

Inputs (Ingredients):

  • Need to know the size of the pizza ordered

  • Need to know the price list of the restaurant

  • Need to know the number of extra toppings ordered

Algorithm (Recipe):

  • Multiply the number of extras by .75

  • Add the cost of the extras to the base price

  • Multiply the new subtotal by .06 for sales tax

  • Add the tax to the subtotal

  • Add a delivery charge of 3.00

  • Print all charges and the total in itemized list

After this planning step, the plain language instructions of the algorithm are translated into a programming language. There are many languages that programmers use to communicate with computers. Perhaps you have heard of Visual Basic, C#, or Java. In later lessons we will explore algorithms to describe various tasks computers are often expected to accomplish and how languages are used to describe specific tasks to a computer. Learning a computer language is not too unlike learning another speaking language such as French or Spanish. You decide what you want to say and then select the words to convey that meaning. But, more about that later…

Get Real

Write the directions for making a pastrami sandwich as an algorithm. Be as specific as possible.

Your answer might be a bit different but this is how I make a pastrami sandwich.

Inputs (Ingredients):

  • Bread

  • Pastrami

  • Mustard

Algorithm (Recipe):

  • Locate the loaf of bread on the counter

  • Open the package of bread at one end

  • Remove 2 slices

  • From the refrigerator, get the package of pastrami and the jar of mustard

  • Open the package of pastrami

  • Place 2 slices on the face of one piece of bread

  • Open the jar of mustard

  • Using a knife, scoop out an amount about the size of a marble

  • Use the knife to spread it evenly on the top surface of the pastrami

  • Place the second slice of bread on top of the pastrami and mustard taking care to line up the edges

  • Use the knife to cut the sandwich in half diagonally from the top left corner to the bottom right

  • Place the sandwich on a plate, carry to a comfortable location, and enjoy!

Summary

Life presents us with problems every day, and thank goodness, problem solving is a learned skill. To become more effective, it is helpful to analyze the type of problem being confronted and select a strategy that fits the specific problem type. Problems can be categorized as:

  • problems with clear-cut answers and solutions

  • problems with a fairly defined outcome and many possible solutions

  • problems with no defined outcome or defined solution strategy

Solution strategies can take the form of:

  • Request-Response-Result

  • IDEAL

  • Circle-Back

Any solution strategy is most effective if it fits the needs of the problem presented. In addition to being able to analyze the type of problems being confronted and fitting an appropriate strategy to it, gathering knowledge of the topic is a vital element for success.

Technology helps us solve trivial, or clear-cut problems, as well as more complex problems that, until recently, were totally unsolvable. Computer scientists use heuristics to develop algorithms as a critical step in the problem solving process because computers can only follow very specific directions. A heuristic is a general guideline or “rule-of-thumb” for solving a problem. An algorithm is a detailed instruction list for accomplishing a task which can be translated into a specific computer language.

Join me in our next lesson when we further explore how computers can solve problems by modeling the real world and we delve into some of the inside details of computer science and programming.