bits and bytes - lesson 2

20
Bits & Bytes: Lesson 2 Things, Things, and More Things The world through the eyes of a computer 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 1 The ENIAC – US Army Photo

Upload: miguelteixeirama

Post on 30-Dec-2015

12 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Bits and Bytes - Lesson 2

Bits & Bytes: Lesson 2

Things, Things, and More Things

The world through the eyes of a computer

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.

1

The ENIAC – US Army Photo

Page 2: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

Understanding Object-Oriented DesignFrom 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.

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:

2

Object-Oriented Design

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

Step 1Step 1 Step 2Step 2 Step 3Step 3

Page 3: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

3

Your Vehicle

The Insurance Company

The Legal System

Organ Donor Registry

License Plate Manufacturer

Page 4: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

4

Property

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

Page 5: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

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.

5

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

Encapsulation

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

Page 6: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

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

6

Abstraction

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

Page 7: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

7

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

Page 8: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

Defining Objects with ClassesIn 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.

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

8

Class

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

Page 9: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

9

Page 10: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

10

Page 11: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

Capturing the power of classesThere 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.

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

11

Code Reuse

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

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.

Page 12: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

own. This same concept is used in computer science to build up and refine the objects created from classes.

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.

12

Pet Class

Lizard Class

Dog Class

Cat Class

Golden Retriever Class

Siamese Class Calico Class

Page 13: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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

13

Vehicle Class

Car ClassMotorcycle

ClassTruck Class

Classic ClassSemi-trailer

ClassFarm Truck

Class

Page 14: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

14

Employee

Class

Medical ClassOperations

Class

Managers

Class

Doctor Class Nurse ClassFood Service

Class

Custodial

ClassAdmin Class Clerical Class

Page 15: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

Events and MessagesEvents 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.

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

15

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.

Page 16: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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.

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.

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)

16

Instantiation

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

Parameter

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

Page 17: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

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

17

Page 18: Bits and Bytes - Lesson 2

Bits and Bytes: Lesson 2

SummaryObject-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.

18