Tải bản đầy đủ (.pdf) (347 trang)

The object oriented thought process

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.35 MB, 347 trang )


The Object-Oriented
Thought Process
Third Edition


Developer’s Library
ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS

Developer’s Library books are designed to provide practicing programmers with
unique, high-quality references and tutorials on the programming languages and
technologies they use in their daily work.
All books in the Developer’s Library are written by expert technology practitioners
who are especially skilled at organizing and presenting information in a way that’s
useful for other programmers.
Key titles include some of the best, most widely acclaimed books within their
topic areas:
PHP & MySQL Web Development

Python Essential Reference

Luke Welling & Laura Thomson
ISBN 978-0-672-32916-6

David Beazley
ISBN-13: 978-0-672-32862-6

MySQL

Programming in Objective-C


Paul DuBois
ISBN-13: 978-0-672-32938-8

Stephen G. Kochan
ISBN-13: 978-0-321-56615-7

Linux Kernel Development

PostgreSQL

Robert Love
ISBN-13: 978-0-672-32946-3

Korry Douglas
ISBN-13: 978-0-672-33015-5

Developer’s Library books are available at most retail and online bookstores, as well
as by subscription from Safari Books Online at safari.informit.com

Developer’s
Library
informit.com/devlibrary


The Object-Oriented
Thought Process
Third Edition
Matt Weisfeld

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City


The Object-Oriented Thought Process, Third Edition
Copyright © 2009 by Pearson Education
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher. No patent liability is assumed with respect to
the use of the information contained herein. Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.
ISBN-10: 0-672-33016-4
ISBN-13: 978-0-672-33016-2
Library of Congress Cataloging-in-Publication Data
Weisfeld, Matt A.
The object-oriented thought process / Matt Weisfeld. -- 3rd ed.
p. cm.
Includes index.
ISBN 978-0-672-33016-2 (pbk.)
1. Object-oriented programming (Computer science) I. Title.
QA76.64.W436 2009
005.1'17--dc22
2008027242
Printed in the United States of America
First Printing: August 2008

Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any

trademark or service mark.

Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible,
but no warranty or fitness is implied. The information provided is on an “as is” basis. The
author and the publisher shall have neither liability nor responsibility to any person or entity
with respect to any loss or damages arising from the information contained in this book or
from the use of the programs accompanying it.

Bulk Sales
Pearson offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales. For more information, please contact
U.S. Corporate and Government Sales
1-800-382-3419

For sales outside of the U.S., please contact
International Sales


Acquisitions Editor
Mark Taber
Development
Editor
Songlin Qiu
Managing Editor
Patrick Kanouse
Project Editor
Seth Kerney
Copy Editor
Chrissy White

Indexer
Tim Wright
Proofreader
Matt Purcell
Technical Editor
Jon Upchurch
Publishing
Coordinator
Vanessa Evans
Book Designer
Gary Adair
Composition
Mark Shirar


Contents

Contents at a Glance
Introduction

1

1 Introduction to Object-Oriented Concepts
2 How to Think in Terms of Objects

37

3 Advanced Object-Oriented Concepts
4 The Anatomy of a Class


75

5 Class Design Guidelines

87

6 Designing with Objects

5

53

103

7 Mastering Inheritance and Composition

129

8 Frameworks and Reuse: Designing with Interfaces
and Abstract Classes 151
9 Building Objects

179

10 Creating Object Models with UML
11 Objects and Portable Data: XML

193
207


12 Persistent Objects: Serialization and Relational
Databases 225
13 Objects and the Internet

247

14 Objects and Client/Server Applications
15 Design Patterns

Index

309

287

271

v


Table of Contents
Introduction

1

1 Introduction to Object-Oriented Concepts
Procedural Versus OO Programming

5


6

Moving from Procedural to Object-Oriented Development
Procedural Programming
OO Programming

9

10

What Exactly Is an Object?
Object Data

10

10

Object Behaviors

11

What Exactly Is a Class?

14

Classes Are Object Templates
Attributes

9


15

17

Methods

17

Messages

17

Using UML to Model a Class Diagram
Encapsulation and Data Hiding
Interfaces

18

19

19

Implementations

20

A Real-World Example of the Interface/Implementation
Paradigm 20
A Model of the Interface/Implementation Paradigm
21

Inheritance

22

Superclasses and Subclasses
Abstraction

Is-a Relationships
Polymorphism
Composition

25

25
28

Abstraction

29

Has-a Relationships
Conclusion

23

23

29

29


Example Code Used in This Chapter

30

2 How to Think in Terms of Objects

37

Knowing the Difference Between the Interface and the
Implementation 38
The Interface

40


The Implementation

40

An Interface/Implementation Example

41

Using Abstract Thinking When Designing Interfaces
Giving the User the Minimal Interface Possible
Determining the Users
Object Behavior

48

48

Identifying the Public Interfaces

49

Identifying the Implementation
50

References

51

50

3 Advanced Object-Oriented Concepts
Constructors

47

48

Environmental Constraints

Conclusion

45

53


53

The Default Constructor

54

When Is a Constructor Called?
What’s Inside a Constructor?
The Default Constructor

54
54

54

Using Multiple Constructors

55

The Design of Constructors

59

Error Handling

60

Ignoring the Problem

60


Checking for Problems and Aborting the Application

60

Checking for Problems and Attempting to Recover

61

Throwing an Exception
The Concept of Scope
Local Attributes

63

64

Object Attributes

65

Class Attributes

67

Operator Overloading
Multiple Inheritance
Object Operations
Conclusion


71

References

71

61

68
69

70

Example Code Used in This Chapter

4 The Anatomy of a Class
The Name of the Class
Comments

77

75
75

72


Attributes

77


Constructors
Accessors

79
80

Public Interface Methods

83

Private Implementation Methods
Conclusion

84

References

84

83

Example Code Used in This Chapter

5 Class Design Guidelines

84

87


Modeling Real World Systems

87

Identifying the Public Interfaces

88

The Minimum Public Interface
Hiding the Implementation

88

89

Designing Robust Constructors (and Perhaps Destructors)
89
Designing Error Handling into a Class

90

Documenting a Class and Using Comments

91

Building Objects with the Intent to Cooperate
Designing with Reuse in Mind

Documenting a Class and Using Comments
Designing with Extensibility in Mind

Making Names Descriptive

93

Providing a Way to Copy and Compare Objects
Keeping the Scope as Small as Possible

94

A Class Should Be Responsible for Itself

95

Designing with Maintainability in Mind

Using Object Persistence

97
99

Serializing and Marshaling Objects
Conclusion

100

References

101

96


97

Testing the Interface

91

92

92

Abstracting Out Nonportable Code

Using Iteration

91

91

Example Code Used in This Chapter

100

101

93


6 Designing with Objects
Design Guidelines


103

103

Performing the Proper Analysis

107

Developing a Statement of Work
Gathering the Requirements

107

107

Developing a Prototype of the User Interface
Identifying the Classes

108

108

Determining the Responsibilities of Each Class

108

Determining How the Classes Collaborate with Each
Other 109
Creating a Class Model to Describe the System

Case Study: A Blackjack Example
Using CRC Cards

109

111

Identifying the Blackjack Classes

112

Identifying the Classes’ Responsibilities

115

UML Use-Cases: Identifying the Collaborations
First Pass at CRC Cards

124

UML Class Diagrams: The Object Model
Prototyping the User Interface
Conclusion

127

References

128


Inheritance

129

129

130

Generalization and Specialization
Design Decisions
Composition

126

127

7 Mastering Inheritance and Composition
Reusing Objects

133

134

135

Representing Composition with UML

136

Why Encapsulation Is Fundamental to OO


138

How Inheritance Weakens Encapsulation
A Detailed Example of Polymorphism
Object Responsibility
Conclusion

145

References

146

109

141

141

Example Code Used in This Chapter

139

146

120


x


Contents

8 Frameworks and Reuse: Designing with Interfaces
and Abstract Classes 151
Code: To Reuse or Not to Reuse?
What Is a Framework?
What Is a Contract?

153

Abstract Classes

154

Interfaces

151

152

157

Tying It All Together

159

The Compiler Proof
Making a Contract


161
162

System Plug-in-Points
An E-Business Example

165
165

An E-Business Problem

165

The Non-Reuse Approach

166

An E-Business Solution

168

The UML Object Model

168

Conclusion

173

References


173

Example Code Used in This Chapter

9 Building Objects

173

179

Composition Relationships
Building in Phases

179

181

Types of Composition
Aggregations

183

Associations

184

183

Using Associations and Aggregations Together

Avoiding Dependencies
Cardinality

186

186

Multiple Object Associations
Optional Associations

Tying It All Together: An Example
Conclusion

192

References

192

189

190
191

10 Creating Object Models with UML
What Is UML?

193

193


The Structure of a Class Diagram

194

185


Contents

Attributes and Methods
Attributes

196

Methods

197

Access Designations
Inheritance
Interfaces

196

197

198
200


Composition

201

Aggregations

201

Associations

201

Cardinality

204

Conclusion

205

References

205

11 Objects and Portable Data: XML
Portable Data

207

207


The Extensible Markup Language (XML)
XML Versus HTML

209

209

XML and Object-Oriented Languages

210

Sharing Data Between Two Companies

211

Validating the Document with the Document Type
Definition (DTD) 212
Integrating the DTD into the XML Document
Using Cascading Style Sheets
Conclusion

223

References

223

213


220

12 Persistent Objects: Serialization and Relational
Databases 225
Persistent Objects Basics

225

Saving the Object to a Flat File
Serializing a File

227

227

Implementation and Interface Revisited
What About the Methods?

231

Using XML in the Serialization Process
Writing to a Relational Database
238

Making the Connection
The SQL Statements

238
239


231

234

Accessing a Relational Database
Loading the Driver

229

236

xi


xii

Contents

Conclusion

242

References

242

Example Code Used in This Chapter

13 Objects and the Internet


247

Evolution of Distributed Computing
Object-Based Scripting Languages
A JavaScript Validation Example
Objects in a Web Page

247
248

250

253

JavaScript Objects

254

Web Page Controls

255

Sound Players

257

Movie Players

257


Flash

242

258

Distributed Objects and the Enterprise

258

The Common Object Request Broker Architecture
(CORBA) 259
Web Services Definition
Web Services Code
Invoice.cs

263

267

267

Invoice.vb

268

Conclusion

270


References

270

14 Objects and Client/Server Applications
Client/Server Approaches
Proprietary Approach

272

Serialized Object Code
Client Code

271

271
272

273

Server Code

275

Running the Proprietary Client/Server Example
Nonproprietary Approach
Object Definition Code
Client Code

278


280

Server Code

281

Running the Nonproprietary Client/Server Example
Conclusion

276

278

283

283


References

284

Example Code Used in This Chapter

15 Design Patterns

287

Why Design Patterns?


288

Smalltalk’s Model/View/Controller
Types of Design Patterns

291

Structural Patterns

295

Behavioral Patterns

298

299

Conclusion

300

References

300

Example Code Used in This Chapter

Index


309

289

290

Creational Patterns

Antipatterns

284

301


About the Author
Matt Weisfeld is an associate professor in business & technology at Cuyahoga
Community College (Tri-C) in Cleveland, Ohio. A member of the Information
Technology faculty, he focuses on programming, web development, and entrepreneurship. Prior to joining Tri-C,Weisfeld spent 20 years in the information technology industry gaining experience in software development, project management, small business
management, corporate training, and part-time teaching. He holds an MS in computer
science and an MBA in project management. Besides the first two editions of The ObjectOriented Thought Process, he has published two other computer books and articles in magazines and journals such as developer.com, Dr. Dobb’s Journal, The C/C++ Users Journal,
Software Development Magazine, Java Report, and the international journal Project
Management.


Dedication
To Sharon, Stacy, Stephanie, and Duffy

Acknowledgments
As with the first two editions, this book required the combined efforts of many people. I

would like to take the time to acknowledge as many of these people as possible, for
without them, this book would never have happened.
First and foremost, I would like to thank my wife Sharon for all of her help. Not only
did she provide support and encouragement throughout this lengthy process, she is also
the first line editor for all of my writing.
I would also like to thank my mom and the rest of my family for their continued
support.
I have really enjoyed working with the people at Pearson on all three editions of this
book.Working with editors Mark Taber, Seth Kerney,Vanessa Evans, and Songlin Qiu has
been a pleasure.
A special thanks goes to Jon Upchurch for his help with much of the code as well as
the technical editing of the manuscript.
Finally, thanks to my daughters, Stacy and Stephanie, and my cat Duffy for keeping
me on my toes.


We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator.We value
your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
You can email or write me directly to let me know what you did or didn’t like about
this book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book, and
that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or email address. I will carefully review your comments and share them
with the author and editors who worked on the book.
Email:
Mail:



Mark Taber
Associate Publisher
Pearson Education
800 East 96th Street
Indianapolis, IN 46240 USA

Reader Services
Visit our website and register this book at informit.com for
convenient access to any updates, downloads, or errata that might be available for
this book.


Introduction

This Book’s Scope
As the title indicates, this book is about the object-oriented (OO) thought process. Obviously, choosing the theme and title of the book are important decisions; however, these
decisions were not all that simple. Numerous books deal with various levels of object orientation. Several popular books deal with topics including OO analysis, OO design, OO
programming, design patterns, OO data (XML), the Unified Modeling Language (UML),
OO Internet development, various OO programming languages, and many other topics
related to OO development.
However, while pouring over all of these books, many people forget that all of these
topics are built on a single foundation: how you think in OO ways. It is unfortunate, but
software professionals often dive into these books without taking the appropriate time
and effort to really understand the concepts behind the content.
I contend that learning OO concepts is not accomplished by learning a specific development method or a set of tools. Doing things in an OO manner is, simply put, a way of
thinking.This book is all about the OO thought process.
Separating the methods and tools from the OO thought process is not easy. Many people are introduced to OO concepts via one of these methods or tools. For example, years
ago, most C programmers were first introduced to object orientation by migrating directly to C++—before they were even remotely exposed to OO concepts. Other software professionals were first introduced to object orientation by presentations that

included object models using UML—again, before they were even exposed directly to
OO concepts. It is not unusual to find that programming books and courses defer OO
concepts until later in the learning process.
It is important to understand the significant difference between learning OO concepts
and using the methods and tools that support the paradigm.This came into focus for me
before I worked on the first edition of this book when I read articles such as Craig Larman’s “What the UML Is—and Isn’t,” In this article he states,
Unfortunately, in the context of software engineering and the UML diagramming language,
acquiring the skills to read and write UML notation seems to sometimes be equated with
skill in object-oriented analysis and design. Of course, this is not so, and the latter is much
more important than the former. Therefore, I recommend seeking education and educational
materials in which intellectual skill in object-oriented analysis and design is paramount
rather than UML notation or the use of a case tool.


2

Introduction

Although learning a modeling language is an important step, it is much more important to learn OO skills first. Learning UML before OO concepts is similar to learning
how to read an electrical diagram without first knowing anything about electricity.
The same problem occurs with programming languages. As stated earlier, many C
programmers moved into the realm of object orientation by migrating to C++ before
being directly exposed to OO concepts.This would always come out in an interview.
Many times developers who claim to be C++ programmers are simply C programmers
using C++ compilers. Even now, with languages such as C# .NET,VB .NET, and Java
well established, a few key questions in a job interview can quickly uncover a lack of
OO understanding.
Early versions of Visual Basic are not OO. C is not OO, and C++ was developed to be
backward compatible with C. Because of this, it is quite possible to use a C++ compiler
(writing only C syntax) while forsaking all of C++’s OO features. Even worse, a programmer can use just enough OO features to make a program incomprehensible to OO

and non-OO programmers alike.
Thus, it is of vital importance that while you’re on the road to OO development, you
first learn the fundamental OO concepts. Resist the temptation to jump directly into a
programming language (such as VB .NET, C++, C# .NET or Java) or a modeling language (such as UML), and take the time to learn the object-oriented thought process.
In my first class in Smalltalk in the late 1980s, the instructor told the class that the new
OO paradigm was a totally new way of thinking (despite the fact that it has been around since
the 60s). He went on to say that although all of us were most likely very good programmers, about 10%–20% of us would never really grasp the OO way of doing things. If this
statement is indeed true, it is most likely because some people never really take the time
to make the paradigm shift and learn the underlying OO concepts.

What’s New in the Third Edition
As stated often in this introduction, my vision for the first edition was primarily a conceptual book.Although I still adhere to this goal for the second and third editions, I have
included several application topics that fit well with object-oriented concepts. For the
third edition I expand on many of the topics of the second edition and well as include
totally new chapters.These revised and updated concepts
n
n
n
n
n
n
n

XML is used for object communication.
Object persistence and serialization.
XML integrated into the languages object definition.
Adding properties to attributes.
XML-based Internet applications.
Client/Server technologies.
Expanded code examples in Java, C# .NET and VB .NET.



This Book’s Scope

The chapters that cover these topics are still conceptual in nature; however, many of the
chapters include Java code that shows how these concepts are implemented. In this third
edition, a code appendix is included that presents the chapter’s examples in C# .NET and
Visual Basic .NET.

The Intended Audience
This book is a general introduction to fundamental OO concepts with code examples to
reinforce the concepts. One of the most difficult juggling acts was to keep the material
conceptual while still providing a solid, technical code base.The goal of this book is to allow a reader to understand the concepts and technology without having a compiler at
hand. However, if you do have a compiler available, then there is code to be investigated.
The intended audience includes business managers, designers, developers, programmers, project managers, and anyone who wants to gain a general understanding of what
object orientation is all about. Reading this book should provide a strong foundation for
moving to other books covering more advanced OO topics.
Of these more advanced books, one of my favorites remains Object-Oriented Design in
Java by Stephen Gilbert and Bill McCarty. I really like the approach of the book, and have
used it as a textbook in classes I have taught on OO concepts. I cite Object-Oriented Design in Java often throughout this book, and I recommend that you graduate to it after
you complete this one.
Other books that I have found very helpful include Effective C++ by Scott Meyers,
Classical and Object-Oriented Software Engineering by Stephen R. Schach, Thinking in C++
by Bruce Eckel, UML Distilled by Martin Flower, and Java Design by Peter Coad and
Mark Mayfield.
The conceptual nature of this book provides a unique perspective in regards to other
computer technology books.While books that focus on specific technologies, such as
programming languages, struggle with the pace of change, this book has the luxury of
presenting established concepts that, while certainly being fine-tuned, do not experience
radical changes.With this in mind, many of the books that were referenced several years

ago, are still referenced because the concepts are still fundamentally the same.

This Book’s Scope
It should be obvious by now that I am a firm believer in becoming comfortable with the
object-oriented thought process before jumping into a programming language or modeling language.This book is filled with examples of code and UML diagrams; however, you
do not need to know a specific programming language or UML to read it.After all I have
said about learning the concepts first, why is there so much Java, C# .NET, and VB .NET
code and so many UML diagrams? First, they are all great for illustrating OO concepts.
Second, both are vital to the OO process and should be addressed at an introductory
level.The key is not to focus on Java, C# .NET, and VB .NET or UML, but to use them
as aids in the understanding of the underlying concepts.

3


4

Introduction

The Java, C# .NET and VB .NET examples in the book illustrate concepts such as
loops and functions. However, understanding the code itself is not a prerequisite for understanding the concepts; it might be helpful to have a book at hand that covers specific
languages syntax if you want to get more detailed.
I cannot state too strongly that this book does not teach Java, C# .NET, and VB .NET
or UML, all of which can command volumes unto themselves. It is my hope that this
book will whet your appetite for other OO topics, such as OO analysis, object-oriented
design, and OO programming.

This Book’s Conventions
The following conventions are used in this book:
n


n

n

Code lines, commands, statements, and any other code-related terms appear in a
monospace typeface.
Placeholders that stand for what you should actually type appear in italic monospace.Text that you should type appears in bold monospace.
Throughout the book, there are special sidebar elements, such as

Note
A Note presents interesting information related to the discussion—a little more insight or a
pointer to some new technique.

Tip
A Tip offers advice or shows you an easier way of doing something.

Caution
A Caution alerts you to a possible problem and gives you advice on how to avoid it.

Source Code Used in This Book
You can download all the source code and examples discussed within this book from the
publisher’s website.


1
Introduction to
Object-Oriented Concepts
A
lthough many people find this bit of information surprising, object-oriented (OO)

software development has been around since the early 1960s. Objects are now used
throughout the software development industry. It is no secret that the software industry
can be slow-moving at times. It is also true that, when systems are working fine, there has
to be a compelling reason to replace them.This has somewhat slowed the propagation of
OO systems.There are many non-OO legacy systems (that is, older systems that are already
in place) that are doing the job—so why risk potential disaster by changing them? In
most cases you should not change them, at least not simply for the sake of change.There
is nothing inherently wrong with systems written in non–OO code. However, brand-new
development definitely warrants the consideration of using OO technologies.
Although there has been a steady and significant growth in OO development in the
past 15 years, the continued reliance on the Internet has helped catapult it even further
into the mainstream.The emergence of day-to-day business transactions on the Internet
has opened a brand-new arena, where much of the software development is new and
mostly unencumbered by legacy concerns. Even when there are legacy concerns, there is
a trend to wrap the legacy systems in object wrappers.
Object Wrappers
Object wrappers are object-oriented code that includes other code inside. For example, you
can take a structured module and wrap it inside an object to make it look like an object. You
can also use object wrappers to wrap functionality such as security features, non-portable
hardware features, and so on.

Today, one of the most interesting areas of software development is the marriage of legacy
and Internet based systems. In many cases, a web-based front-end ultimately connects to
data that resides on a Mainframe. Developers who can combine the skills of mainframe
and web development are in demand.


6

Chapter 1 Introduction to Object-Oriented Concepts


Objects have certainly made their way into our personal and professional information
systems (IS) lives—and they cannot be ignored.You probably experience objects in your
daily like without even knowing it.These experiences can take place in your car, talking
on your cell phone, using your digital TV, and many other situations.
With the success of Java, Microsoft’s .NET technologies and many others, objects are
becoming a major part of the technology equation.With the explosion of the Internet,
and countless local networks, the electronic highway has in essence become an objectbased highway (in the case of wireless, object-based signals).As businesses gravitate toward
the Web, they are gravitating toward objects because the technologies used for electronic
commerce are mostly OO in nature.
This chapter is an overview of the fundamental OO concepts.The concepts covered
here touch on most, if not all, of the topics covered in subsequent chapters, which explore
these issues in much greater detail.

Procedural Versus OO Programming
Before we delve deeper into the advantages of OO development, let’s consider a more
fundamental question:What exactly is an object? This is both a complex and a simple
question. It is complex because learning any method of software development is not trivial. It is simple because people already think in terms of objects.
For example, when you look at a person, you see the person as an object.And an object is defined by two terms: attributes and behaviors.A person has attributes, such as eye
color, age, height, and so on.A person also has behaviors, such as walking, talking, breathing, and so on. In its basic definition, an object is an entity that contains both data and behavior.The word both is the key difference between OO programming and other
programming methodologies. In procedural programming, for example, code is placed
into totally distinct functions or procedures. Ideally, as shown in Figure 1.1, these procedures then become “black boxes,” where inputs go in and outputs come out. Data is
placed into separate structures and is manipulated by these functions or procedures.

Inputs

Outputs

Figure 1.1


Black boxes.

Difference Between OO and Procedural
In OO design, the attributes and behaviors are contained within a single object, whereas in
procedural, or structured design, the attributes and behaviors are normally separated.


Procedural Versus OO Programming

As OO design grew in popularity, one of the realities that slowed its acceptance was the
fact that there were a lot of non-OO systems in place that worked perfectly fine.Thus, it
did not make any business sense to simply change the systems for the sake of change.Anyone who is familiar with any computer system knows that any change can spell disaster—
even if the change is perceived to be slight.
This situation came into play with the lack of acceptance of OO databases.At one
point in the acceptance of OO development it seemed somewhat likely that OO databases would replace relational databases. However, this never happened. Businesses had a
lot of money invested in relational databases, and there was one overriding factor—they
worked.When all of the costs and risks of converting systems from relational to OO databases became apparent, there was no compelling reason to switch.
In fact, the business forces have now found a happy middle ground. Much of the software development practices today have flavors of several development methodologies such
as OO and structured.
As illustrated in Figure 1.2, in structured programming the data is often separated from
the procedures, and sometimes the data is global, so it is easy to modify data that is outside
the scope of your code.This means that access to data is uncontrolled and unpredictable
(that is, multiple functions may have access to the global data). Second, because you have
no control over who has access to the data, testing and debugging are much more difficult. Objects address these problems by combining data and behavior into a nice, complete
package.

Function 1

Function 2


Global Data

Function 3

Figure 1.2

Function 4

Using global data.

7


8

Chapter 1 Introduction to Object-Oriented Concepts

Proper Design
We can state that when properly designed, there is no such thing as global data in an OO
model. This fact provides a high amount of data integrity in OO systems.

Rather than replacing other software development paradigms, objects are an evolutionary
response. Structured programs have complex data structures, such as arrays, and so on.
C++ has structures, which have many of the characteristics of objects (classes).
However, objects are much more than data structures and primitive data types, such as
integers and strings.Although objects do contain entities such as integers and strings,
which are used to represent attributes, they also contain methods, which represent behaviors. In an object, methods are used to perform operations on the data as well as other actions. Perhaps more importantly, you can control access to members of an object (both
attributes and methods).This means that some members, both attributes and methods, can
be hidden from other objects. For instance, an object called Math might contain two integers, called myInt1 and myInt2. Most likely, the Math object also contains the necessary
methods to set and retrieve the values of myInt1 and myInt2. It might also contain a

method called sum() to add the two integers together.
Data Hiding
In OO terminology, data is referred to as attributes, and behaviors are referred to as methods. Restricting access to certain attributes and/or methods is called data hiding.

By combining the attributes and methods in the same entity, which in OO parlance is
called encapsulation, we can control access to the data in the Math object. By defining these
integers as off-limits, another logically unconnected function cannot manipulate the integers myInt1 and myInt2—only the Math object can do that.
Sound Class Design Guidelines
Keep in mind that it is possible to create poorly designed OO classes that do not restrict access to class attributes. The bottom line is that you can design bad code just as efficiently
with OO design as with any other programming methodology. Simply take care to adhere to
sound class design guidelines (see Chapter 5 for class design guidelines).

What happens when another object—for example, myObject—wants to gain access to the
sum of myInt1 and myInt2? It asks the Math object: myObject sends a message to the Math
object. Figure 1.3 shows how the two objects communicate with each other via their
methods.The message is really a call to the Math object’s sum method.The sum method
then returns the value to myObject.The beauty of this is that myObject does not need to
know how the sum is calculated (although I’m sure it can guess).With this design
methodology in place, you can change how the Math object calculates the sum without
making a change to myObject (as long as the means to retrieve the sum do not change).
All you want is the sum—you don’t care how it is calculated.
Using a simple calculator example illustrates this concept.When determining a sum
with a calculator, all you use is the calculator’s interface—the keypad and LED display.The
calculator has a sum method that is invoked when you press the correct key sequence.You


×