Chapter 3
Structured Techniques
and Object-Oriented
Programming
Programming Logic for Business
Copyright 2001 Laura Saret
Laura Saret EdD
Chapter Outline
 What Are Straight-Line Flowcharts and What’s
Wrong with Them?
 Why Did We Progress from Modular to
Structured Programming?
 What Are the Rules for Writing a Structured Program?
 Example: Using Structures
 If Structured Programming Was So Great, Why Do Programmers
Now Use Object-Oriented Programming?
 How Does Object-Oriented Programming Look at a Problem?
 What Are Objects and Classes?
 How Do Objects Interact With Each Other?
 Example: Creating a Class
 Why Do We Need to Focus Our Energy on Structured
Programming Concepts?
 Example: Using Process and Error Subroutines
Outline (continued)
What Is Pseudocode?
What Are Hierarchy (Structure) Charts?
Example: Using Local and Global Variables
What Are Housekeeping and Termination Functions?
Example: Initialization and Termination Functions; Local
and Global Variables; Total at End of Report
 Example: Counter-Controlled Loops





Chapter Objectives
After completing this chapter you should be able to.…
 Describe the historical progression from straight-line to
modular to structured to object-oriented programming
 Understand the advantages and disadvantages of structured
programming
 Identify and use programming structures
 Explain how object-oriented programming differs from
structured programming
 Use object-oriented terminology
 Explain how objects interact with each other
 Understand what is involved in creating a class
 Understand when and how to use local and global storage
locations
 Use structured programming concepts to draw flowcharts and
hierarchy charts as well as construct pseudocode for programs
that require error processing, local and global storage
locations, totals at the end of a report, and loops including
counter-controlled loops
Straight-Line (Sequential)
Flowcharts
 Logic progresses from Start to Stop with few, if
any subroutines
 Go to (unconditional branch) instructions are
frequently used
 The more complicated the logic, the more difficult
it is to follow
Modular Programming
 Encourages subroutines
 Behind most software development over the last
century
 Large programs are divided by functional parts into
subroutines or modules
 Go to instructions only permitted within subroutines
 Two objectives when creating routines
 Strong cohesion
 Instructions are closely related
 Routine does one function such as printing
 Loose coupling
 No or a weak connection between routines
 One routine does not depend on other routines
From Modular to Structured
Programming
 Why structured programming?
 Advantages of structured programming
 Standard method for solving a problem
 “Go-to-less”
 Easier to test and debug than straight-line or modular
programs
 Structured walkthroughs
 A single program can be written by more than one
programmer
 Programs can share routines
 Help minimize thrashing
A Structure is 1 or More
Instructions (Flowchart Symbols)
Combined According to Rules
What Are the Rules for Writing a
Structured Program?
3 basic structures
 Sequence
 Decision (selection)
 Repetition (looping or
iteration)
Sequence Structure
 Can contain any symbol
except for the decision
symbol
 Steps are executed in
sequence with no instruction
changing the order
Write a
line
Move
Score to
High-Score
Do
Low-Score
Do
Average
Decision Structures
If…Then
If…Then…Else
Case
If…Then
Is
Add 1 to
Code =
Code1-Count
Yes
1?
No
If…Then…Else
No
Do Male
Is
Gender =
"F"? Yes
Do Female
Do BenefitAnalysis
Case
Value = ?
=0
>0
<0
Move
spaces to
Sign
Move
"Negative" to
Sign
Move
"Positive" to
Sign
Repetition (Looping or Iteration)
Structures
Top-test loop
Bottom-test loop
How Many Times is Each of the Following
Loops Executed?
Do Process
Done = ?
"Yes"
"No"
Do Process
Done = ?
"Yes"
"No"
Top test
Bottom test
Is This a Top-Test or a Bottom-Test Loop?
It is neither a
top-test nor
bottom-test
loop.
The loop is
invalid!!!!!!
In structured programming
the decision to leave the loop
must be the first instruction
or the last instruction in the
loop
Hints for Identifying Structures
 No decision symbols?
 Sequence structure
 Begins with a decision symbol?
 Top-test loop
 Decision
 If…Then
 If…Then…Else
 Case
 Ends with a decision symbol?
 Bottom-test loop
What Are the Rules for Writing a
Structured Program?
Only one entrance into
and one exit out of a
structure
Entrance into structure
Exit 1 from
structure
Exit 2 from
structure
Entrance 1
into structure
Exit from structure
Entrance 2
into structure
What Are the Rules for Writing a
Structured Program?
No “go to” statements
B
B
What are the rules for writing a
structured program?
Decision and
repetition structures
can be nested
Example of nested structures: You
can represent case structures using
nested If…Then…Elses
Value = ?
< >0
Value = ?
<0
Move
"Negative" to
Sign
>0
Move
"Positive" to
Sign
=0
Move
spaces to
Sign
What Are the Rules for Writing a
Structured Program?
Only 1 stop
instruction. It must
be in the Mainline
routine.
Example from Section 3.4 (page 87):
Using structures
 This flowchart
is an example
from chapter 2
 Is it
structured?
Start
Open
Files
Read a
Record
EOF?
Yes
No
Write a
Line
Close
Files
Stop
This is a
structured
solution
Start
Open
Files
Sequence
Structures
Read a
Record
EOF?
Yes
Close
Files
No
Write a
line
Read a
Record
Top-test loop
Structure
Stop
SOLUTION 1
Check for EOF
is after the
read--Notice
that a priming
read is
required
Start
Open
Files
Read a
Record
EOF?
No
Write a
Line
Read a
Record
Yes
Close
Files
Stop
SOLUTION 2
Check for
EOF is
before the
Read--No
priming
read is
required
Start
Open
Files
EOF?
No
Read a
Record
Write a
Line
Yes
Close
Files
Stop
Start
Open
Files
Sequence
Structures
EOF?
Close
Files
Yes
No
Read a
Record
Top-test loop
Structure
Write a
line
Stop
SOLUTION 3
Some languages require that the EOF be part of
and immediately follow the READ instruction.
Let’s look at the book (page 90)
What
is
DONE?
 Done is an indicator
 Allows the programmer to keep track of (indicate)
whether all records have been processed
 Indicators are used to track conditions in a
program
 There are 2 differences between using Done
and checking for EOF
1. You can check Done whenever you want
2. You can only check EOF when the programming
language allows it
Structured programming
produced significant
improvements in
software quality and
development time…
So…Why are Programmers Now Using
Object-Oriented Programming?
 Increasing dependence on
information processing is
creating a crisis
 Volume of information is increasing
faster than the ability to create
software
 Programmers cannot generate
software to keep pace with the
potential of new hardware
Some Programming Issues are Not
Adequately Addressed by Structured
Programming
 It is rarely possible to anticipate the design of a
completed system before it’s actually implemented
 Systems are works in progress
 Development of GUIs is very complicated in
traditional procedure-oriented programming
languages
 Sharing data across routines is difficult and errorprone
 Focus of structured programming is on the modularity and
procedures
 Data interactions are ignored
 Allowing modules to share all their data and interact freely
creates subroutines that are very dependent on each other-therefore, we don’t have independent routines
So, What’s the Answer to the
Data Sharing Problem?
 Modularize the data along with the procedures by
giving each subroutine its own local data that it
alone can read and write
INFORMATION
HIDING
Information Hiding Allows the Programmer to
Work with Modules or Procedures Developed
by Others at an Abstract Level
 Abstraction
 Internal details are hidden from the user
 Data and procedures are not exposed to
procedures not needing to know them
Another Advantage of Object-Oriented
Programming is Reusability
 Building a house
 Electrical system
 Plumbing system
 Heating/air conditioning
system
 Objects in Windows
 Buttons
 Menus
How Structured Programming Looks at a
Problem
 Procedures
 Data acted upon by the procedures are
maintained separately from the procedures
Program
Data
Procedure
Procedure
How Object-Oriented Programming
Looks at a Problem?
 Objects
 Data
 Methods
 Methods surround
the data and
protect data from
other objects
Data
Objects
 Objects are things (nouns)
 Objects have attributes (properties)
 Adjectives that describe an object
 Objects have methods (behaviors)
 Verbs that specify what the object can do
 Events are used to trigger behaviors
Let’s Look at a Person Object
 What are its attributes (properties)?
 What are its methods (behaviors)?
 What triggers each of the methods?
Class
 Abstract term used to uniquely
describe the scheme of an object
 Properties
 Methods
 Events
 Instantiation
 Creating an instance of an object
from a class
 A class is an abstraction
 Person class is not an actual person
 Every object is an instance of its
class
Inheritance, subclass, superclass
MUSICAL INSTRUMENTS
 Objects that belong
to the subordinate or
subclass have the
attributes and
methods of the
subordinate class
Percussion
Woodwind
String
and the attributes
Instruments
Instruments
Instruments
and methods of
classes above it in
the hierarchy
 Subclasses inherit
methods and
attributes
 Subclasses can
define their own
methods and
attributes
Aggregate Object
Classes Can be Subclasses of
Other Classes
 A banana is a fruit
 An apple is a fruit
 A strawberry is a fruit
 A grape is fruit
Objects Interact with Each
Other by Sending Messages
Client (sender of message)
Server (receiver of message)
Waiter Bring Hamburger, Fries, Iced tea
Object receiving message method
parameters
The Details of How the Server Object
Carries Out its Operation Are Hidden
Waiter Bring Hamburger, Fries, Iced tea
Object receiving message method
parameters
Polymorphism Allows Objects of
Different Classes to Respond
Differently to the Same Message
Clown
Put On
Make Up
Model
Put On
Make Up
Encapsulation
 Packaging related data and procedures
together
 Data is accessed only by the object’s methods
 This is done by sending messages
 Advantages of encapsulation
 Data in the object being accessed are
protected from damage by other objects
 Client objects don’t need to know how a
method works--only that it does
Creating a Class
Class Name
Rectangle
Attributes
Length
Width
Methods
Area
Perimeter
Template
Rectangle
Class
Area and Perimeter Methods
 Rectangle-Area length,width = length * width
 Rectangle-Perimeter length,width =
2 * length + 2 * width
 What happens when we send the following message
to the rectangle object?
 Rectangle-Area 3,5
Why Do We Still Write
Structured Programs?
 Way of breaking a program into
routines
 Object-oriented programming works
at a higher level of abstraction than
structured programming does
 After objects have been identified,
methods are designed using structured
techniques
 We are concentrating on methods or
procedures
Example in Section 3.11 (page 98):
Process and Error Subroutines
Start
Error
Open
Files
Write
"No Input
Records"
Read a
Record
EOF?
Yes
No
Do
Process
No
EOF?
Yes
Close
Files
Stop
Student-Name
Credits
Do
Error
Return
Process
Credits:
Tuition =
10
>
1050
<=
Tuition =
Credits * 100
Write
a Line
 What is the Error
routine used for?
Read a
 This program has
Record
2 read
instructions
Return
 What is the first
read instruction
used for?
 What is the
second read
instruction used
for?
Student-Name
Tuition
Student-Name
Credits
Let’s Look at a Pseudocode Solution
MAINLINE
START
OPEN files
READ a record (STUDENT-NAME,
CREDITS)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO PROCESS routine
ENDLOOP
ENDIF
CLOSE files
STOP
ERROR
WRITE “No Input Records”
ENDERROR
PROCESS
IF CREDITS > 10 THEN
Tuition = 1050
ELSE Tuition = Credits * 100
ENDIF
WRITE a line (STUDENT-NAME,
TUITION)
READ a record (STUDENT-NAME,
CREDITS)
ENDPROCESS
What is Pseudocode?
 An alternative to flowcharting
 Represents logic in an English-like manner
 Rules
 Avoid the use of words peculiar to a particular programming
language
 Indent lines to make the pseudocode easy to read and
understand
 Show key words (Move, Write, Read) in a different color, font, or
capitalized
 Punctuation is optional
 End every If with EndIf
 Begin every loop with a Loop instruction; End every loop with
EndLoop
 Main routine is to be shown first
 Terminate all routines (other than Mainline) with an End
instruction
Show key words in a different color, font,
or capitalized
MAINLINE
START
OPEN files
READ a record (STUDENT-NAME,
CREDITS)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO Process
ENDLOOP
ENDIF
CLOSE files
STOP
Indent
MAINLINE
START
OPEN files
READ a record (STUDENT-NAME,
CREDITS)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO Process
ENDLOOP
ENDIF
CLOSE files
STOP
End every If with EndIf
MAINLINE
START
OPEN files
READ a record (STUDENT-NAME,
CREDITS)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO Process
ENDLOOP
ENDIF
CLOSE files
STOP
Begin every loop with a Loop instruction;
End every loop with EndLoop
MAINLINE
START
OPEN files
READ a record (STUDENT-NAME,
CREDITS)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO Process
ENDLOOP
ENDIF
CLOSE files
STOP
Terminate all routines (other than
Mainline) with an End instruction
ERROR
WRITE “No Input Records”
ENDERROR
Hierarchy Charts
 Also called
 Structure charts
 Top-down charts
Mainline
Error
Process
Shade the Upper-Right Corners of
Common Routines
Mainline
Initialize
Error
Process
Headings
Headings
Terminate
Scope of a Variable
 What parts of a program can use
the values stored in a particular
location
 Global
 Exposed to entire program
 Local
 Defined in a class, method, or
procedure and can only be used
by that class, method, or
procedure
 Can be passed as parameters in
messages
Let’s Look at the Example in
Section 3.14 (page 101)
We Will Look Only at Routines that
Pass or Receive Local Variables
All Storage Locations
are Local and Passed
as Needed
MAINLINE
START
OPEN files
READ a record (CUST-NUM,
CUST-NAME, AMOUNT)
IF EOF THEN
DO ERROR routine
ELSE LOOP UNTIL EOF
DO PROCESS routine
(DATA SENT: CUST-NUM,
CUST-NAME, AMOUNT.
DATA RETURNED: NONE)
ENDLOOP
ENDIF
CLOSE files
STOP
Start
Open
Files
CustNum
CustName
Amount
Read a
Record
EOF
?
Yes
Do
Error
No
Data Sent:
Do
Process
CustNum
CustName
Amount
Data Returned:
None
EOF
?
No
Yes
Close
Files
Stop
PROCESS (DATA RECEIVED:
CUST-NUM, CUST-NAME,
AMOUNT. DATA TO RETURN:
NONE)
DO CALCULATE routine (DATA SENT:
AMOUNT. DATA RETURNED:
DISC-RATE, DISC-AMOUNT,
NET-AMOUNT)
WRITE a line (CUST-NUM,
CUST-NAME, AMOUNT,
DISC-RATE, DISC-AMOUNT,
NET-AMOUNT)
READ a record (CUST-NUM,
CUST-NAME, AMOUNT)
ENDPROCESS
Process
Do
Calculate
Data Received:
CustNum
CustName
Amount
Data to Return:
None
Data Sent:
Amount
Data Returned:
DiscRate
DiscAmount
NetAmount
Write a
line
CustNum
CustName
Amount
DiscRate
DiscAmount
NetAmount
Read a
Record
CustNum
CustName
Amount
Return
CALCULATE (DATA RECEIVED:
AMOUNT. DATA TO RETURN:
DISC-RATE, DISC-AMOUNT,
NET-AMOUNT)
DiscRate =
IF AMOUNT < 100 THEN
.10
DISC-RATE = 0.10
ELSE DISC-RATE = 0.20
ENDIF
CALCULATE DISC-AMOUNT
(DISC-AMOUNT = AMOUNT *
DISC-RATE)
CALCULATE NET-AMOUNT
(NET-AMOUNT = AMOUNT –
DISC-AMT)
ENDCALCULATE
Data Received:
Amount
Data to Return:
DiscRate
DiscAmount
NetAmount
Calculate
Is
Amount
Yes < 100?
No
DiscAmt =
Amount *
DiscRate
NetAmt = Amount
- DiscAmt
Return
DiscRate =
.20
Housekeeping and Termination
Functions
 Housekeeping (initialization) functions
 Done at the beginning of a program or routine
to get ready for processing
 Termination (end-of-program)
functions
 Done at the end of a program or routine
to finish-up processing
Housekeeping (Initialization)
Functions
 Assigning initial values to storage locations
 Counter = 0
 Opening files
 Instantiating objects
 Reading the first record of each input file
 Where?
 In the mainline routine
 As a separate routine
 As part of each routine that requires housekeeping
Termination (End-of-Program)
Functions
 Finishing the processing of the last input record
 Printing final totals
 Closing files
 Where?
 Mainline
 Separate routine
 Part of each routine that requires something to be
“finished up” before returning to the calling routine
Let’s examine the example in
section 3.16 (page 106)
 The program determines the number of boxes
required for an order and displays screen output
 Initialization functions
 Termination functions
 Local and global variables
 Total at end of report
How is the Number of Boxes
Calculated?
The number of boxes
for each product is
calculated and a
total is determined
4 painting
kits
5 computer
games
50 bubbles
10 stuffed
animals
15 action
figures
How Many Boxes Are Needed for
150 Bubbles?
 Each box holds 50 bubbles
 150 bubbles / 50 bubbles per box = 3 boxes
How Many Boxes Are Needed for
175 Bubbles?
 Each box holds 50 bubbles
 175 bubbles / 50 bubbles per box = 3 boxes
 What do we do with the remaining 25 bubbles?
 When there is a remainder, we need to use
another box—in this case we will need 4 boxes
How Does the Program Do the
Calculation? (see page 110)
 First the program does integer division
 Num-Items \ Items-Per Box
 When integer division is done, the
remainder is ignored
 150 \ 50 = 3
 175 \ 50 = 3
 Then the program does regular division
 Num-Items / Items-Per Box
 150 /50 = 3
 175 / 50 = 3.5
 If the result of the two divisions is not
equal, then we know there was a
remainder when the division was done,
and one is added to the number of
boxes needed
Examine the Data Dictionary
(pages 106-107)
 TOTAL is a global variable
 It is used to store the total number of boxes
 All other variables are local variables
 They will need to be passed and returned
Examine the Flowchart
(Pseudocode) (pages 108-110)
 The Mainline routine
 Sets Total = 0
 Opens files
 Clears the screen
 Reads a record containing the number of Bubbles,
Animals, Figures, Games, and Kits
 Calls Calculate to determine the number of boxes (Total)
 Passes Bubbles, Animals, Figures, Games, Kits
 Calls Terminate to
 Display Total
 Close files
Calculate…
 Calls Number-Boxes 5 times





Bubbles
Animals
Figures
Games
Kits
 Number-Boxes determines the number of boxes
and adds the number to Total
 What is passed to Number-Boxes each time it is
called?
 What is returned from Number-Boxes?
 What is done with the value that is returned?
Counter-controlled loops
 Used when you want to do a task
a certain number of times
 Before doing the loop, determine
 Start value
 End value
 Increment value
 Initialize Counter to Start
 If Counter is greater than End
 Exit the loop
 Otherwise, continue with the next
step
 Execute statements in the loop
 Add Increment to Counter
Counter = Start
Is
Counter >
End?
Yes
No
Execute
instructions in
loop
Add Increment
to Counter
Let’s examine the example in
section 3.17 (page 106)
 What is the Start value used for Interest?
 What is the End value used for Interest?
 What is the Increment value?
 What does the loop do?
Descargar

Chapter 1