22
Chapter 1 Software Development and Visual Basic .NET 3

Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

  • Upload
    doanthu

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Chapter 1Software Developmentand Visual Basic .NET

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

3

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:01 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 2: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Visual Basic .NET is a radical departure from the previous versions of Visual Basic,the world’s most popular programming language. If you have had experiencewith Object-Oriented (OO) languages like Java or Delphi you will probably take

to Visual Basic .NET fairly quickly. After you have spent a few months using VisualBasic .NET, you’ll find it hard to return to an earlier version (unless you really must).

You have probably also read or heard that support for the common language runtime(CLR) and the .NET Framework transforms Visual Basic .NET into a “pure” or “true”object-oriented language. To decide how true this claim is, let’s first understand what a“pure” and “true” OO language is.

If you are new to object-oriented software development, this chapter will introduceyou to the OO concepts that all Visual Basic programmers need to know. This chapterintroduces these software developments and OO concepts early on, to help you derivethe most benefit from this book and from Visual Basic .NET.

We begin by reviewing the evolution of software development over the past fewdecades. Then we shall see how Visual Basic .NET—hereon referred to as Visual Basic—has risen to meet the challenges of a demanding industry, answering the world’s thirstfor software.

Visual Basic and the Difficulty ofDeveloping SoftwareWhether silicone- or carbon-based, what makes computers tick is simply the groupingsof the numbers 1 and 0, combined in sequences to form instructions. This is known assoftware—how it is created and used is what drives technology.

The essence of software is the ability to marshal and control bits of data in order tocommunicate; to control devices; to display, project, and render images; to model, designand manufacture widgets; to move objects; to perform highly complex computationsand calculations, and so on.

Software is an extremely complex science. At the same time it is an art form—thesoftware developer must be creative in designing and writing software that simulatesand addresses real world scenarios. Developers are required to do much more than justwrite code for complex mathematical algorithms or to simply transfer information frompoint A to point B.

Software development is time-consuming: The combination of both time andcomplexity makes it a very costly process. Unless a software engineer knows practicallyeverything there is to know about the core language syntax and grammar and hasexperience using it, a development process can rapidly expand beyond the range ofaffordability. “Core language” doesn’t mean peripheral or collateral technologies, orlibraries like the database libraries (ADO.NET) or the Internet communications libraries,or the Web development technologies (ASP.NET), but the foundation used to create allthese collateral technologies. This does not mean that these collateral technologies arenot important—they are very important—it means that you cannot hope to use or even

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

4 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:01 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 3: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

create the collateral technologies or components unless you first understand thefoundations, processes, and facilities used to build them.

Reducing Complexity and Time-to-Market with ReuseThere have been many horror stories of how a miscalculated value caused a machineto explode, or how a bank lost millions due to a single errant statement in an algorithm,or how a product had to be recalled because of an incorrect quality control constant.

An experienced programmer knows to use well-written and proven softwarecomponents to avoid having to rewrite and retest the product. We in the software industryknow that software is an iterative process. It is also a refining process. Without the abilityto reuse what has been refined or what currently works well for the task at hand, wewill not advance as quickly as we need to in the coming decades. If we had not beenable to reuse what so many have done before us we would not be where we are today.

Take C.A.R. Hoare’s famous sorting algorithm, quicksort. He invented this sortin 1960; it is used today in every modern language (we will cover this algorithm inChapter 12, “Arrays and Other Data Structures,” along with bubble sort, and in Chapter 14in the discussion of delegates). Many software geniuses have chosen to share their efforts.Bruce Schneier’s blowfish encryption algorithm springs to mind, as does the emergenceof formally cataloged patterns for software design. (There are also a number of algorithmsthat are patented and that we can’t use. The sirens of the data compression wars are stillringing in many companies.)

Software development has certainly changed over the past few decades. The demandfor reusable code, and the ever-increasing demands on software writers to turn out bettercode, have resulted in improved software design and implementation techniques thatfacilitate today’s software-engineering principles and requirements. Had not Visual Basicbeen adapted for the need, had it not risen to the challenge, it would have been replacedby something else.

Software Development andSoftware EngineeringSoftware engineering is not easy to define; indeed, many argue that it is not a form ofengineering at all and that its designers are not really engineers. But software developersare engineers and include in their ranks many professionals with formal training andexperience. According to Webster’s dictionary, “[software] engineering is the applicationof mathematical and scientific principles to practical ends, as the design, construction,and operation of efficient structures, equipment, and systems.”

Declared an engineering discipline by NATO in 1968, software design also “providesthe equipment, systems, and tools to facilitate all forms of engineering practice” (thisauthor’s words). Modern software development has also borrowed greatly from otherrelated disciplines such as civil, electrical, mechanical, and structural engineering—

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ETC h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 5

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:02 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 4: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

6 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

especially in the fields of analysis, design, and construction. Even the concept of patterns,discussed later in this chapter, is borrowed from civil engineering.

While many excellent software engineers are graduates of computer science schools,programmers with an engineering background have the benefit of forward training indesign and construction.

The software industry emerged in the mid-20th century with the advent of the moderncomputer and has progressed through three distinct “ages” since then:

■ The Procedure-Oriented Age Procedure-oriented programming was largelyconcerned with computational results rather than data—the focus being onprocedures, or just code, as islands of functionality. Software systems werenot organized in any meaningful structure and were merely collections of filescontaining huge functions and procedures that were processed as required fordiscrete calculations. Data was external to the function—a black box—and easilyaccessible because it was global. Because the systems were fixated on a result,a value, they could be adequately managed by the very dedicated individuals thatwrote them. Examples of such languages include Assembly Language, C,generic BASIC, generic Pascal, Ada, COBOL and so forth. Most languages todayhave evolved to accommodate the modern programming practices, yet manyprogrammers still work in a flat, linear procedure-oriented style. Current Webdevelopment has not helped this situation, either. The following example, whileextreme, is simple BASIC in all its procedural glory. (Think of thousands of linesfocused on one result, computing the speed of a spacecraft relative to the forcesimposed on it in space.) This type of programming is now as foreign as Englishin a Dead Sea Scroll:

60 FOR TOPSP%=10 TO 100:

70 VOERC=TOPSP%/100

80 GOSUB 180:REM calculate top speed

90 THETA5$=STRS$(FIX((THETA5+.005)*100))

■ The Structure-Oriented Age As software systems grew, programmersneeded to manage and maintain them more efficiently. The structure-orientedage introduced a paradigm in which the functions were organized in structures—a module containing procedures and data. In other words, the unit or level ofabstraction became the module rather than the individual procedure. Structuralprogramming lends itself to encapsulation, data-centric programming, collectionsof like routines, and object-like programming.

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:02 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 5: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

■ The Object-Oriented Age By the end of the 1960s it became apparent thatthe ever-growing complexity of software systems would necessitate a newmodel, one that was more humanly manageable and comprehensible. Nowalmost half a century after the first object-oriented software language, Simula,was created, the OO age has finally taken hold in response to this complexity.OO lets us model and design software systems around familiar concepts (objects)behind which complexity is hidden through abstraction, much like the abstractionfound in nature. The focus of programming is mostly on attributes and datarather than computations or calculations. Encapsulation and other featureshave been refined, and continue to be refined, to better serve the OO model.

Simula-1, the first OO language, arrived in 1966 and introduced the first attempt tofocus on behavior and data in objects rather than procedures. If you are new to OO Iwould jump to Chapter 9, which kicks off discussing classes and Chapter 10 which delvesinto the subject of abstraction and interfaces.

The remainder of this chapter will explore how and why object-oriented technologyhas gained critical acceptance in the software-development community today and howthis model of programming can now be utilized by any modern software language.

The Classic Programming ModelsComputer programming as we know it today began in the late 1950s and burgeonedin the 1960s. In those days, writing code was not considered an engineering profession.Computers could do very little, and people could usually calculate mathematical problemsmore quickly. There were many stories from that time concerning public institutions thatspent millions on computers, only to learn that their staff could outperform the machines.

At first the effort involved in programming a computer was not worthwhile. Thefirst useful programs were nothing more than reams of sequential instructions. Afterprocessing the steps, the computation would be complete and the computer would beready to start again.

This process worked for simple programs, but as computers became more powerfuland sophisticated, the complexity and effort required to program them became barriersto their usefulness. According to one industry maxim, “Program complexity growsuntil it exceeds the capability of the programmer to maintain it.” Then chaos takes over.

Identifying structure in computer programs became a popular crusade for manyscientists and teachers in the early years of the profession. By the end of the 1960s, itculminated in a movement called structured programming, a software engineering disciplinethat is still widely taught in first-year computer science and software engineering courses.Many colleges require it as a prerequisite to learning object-oriented programming (OOP).As you will see, Visual Basic .NET and the .NET Framework present a highly structuredprogramming framework.

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 7

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:03 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 6: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

8 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

Structured ProgrammingThis is essentially the technique of organizing programs into a collection of smallstand-alone modules. The modules can be grouped into a hierarchy or a network,and each unit has a single entry and a single exit point. Processing the lines of codein the module occurs from the top down, and the control structure usually forbidsunconditional branching.

Specific techniques let us divide algorithms into small functional units so that oneor more programmers can work on each unit, refine it, test it, debug it, and share it withthe rest of the team. Fellow programmers then debug and check each other’s code. Ina process similar to modern manufacturing, all the units are then combined to producethe larger application or system. This is a highly efficient method that works both forteams and individuals.

Modules are not special “objects” or language-specific containers, and as longas a language can compile and link multiple source-code files it can be structuredalong modular lines. It is important to note an important distinction here: Structuredprogramming divides the engineering practice into two categories—design andconstruction (or implementation).

Software maintenance includes not only debugging and fixing faulty software, but alsoadding required features, improving performance, and more.

On the one hand, software-design engineers use structural techniques to analyzethe problems, determine a solution path, and create a system to meet several objectives,which include satisfying the customer and maintaining the software.

On the other hand, software-construction engineers use their code-writing skills toimplement the code. They provide the necessary implementation at the functional levelof the module with regard to the specific methods or algorithms. In many shops, assigningengineers to specific design and implementation roles can provide huge dividends.

Many programmers hate modeling and design at the higher levels of abstractionand are more productive devising code, in which the radius of focus is only a fewmillimeters. In fact, this is the age that coined the slogan “code is king.” To quotePaul C. Clements:

"While 'top-down programming' and 'structural programming' were all the rage in1974, both referred to practices in which getting to code was clearly the end game.(Contrast this to the current object- or component-oriented world in which weconcentrate on services provided, not statement executed.)"

from Paul C. Clements' Introduction to David Parnas' famous paper"On a 'Buzzword': Hierarchial Structure"

Gifted engineers are versatile enough to produce at both the macro- and microlevels.A number of important benefits emerged from the structure-oriented programmingparadigm, as the next few sections will illustrate.

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:03 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 7: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

Bug-Reduced CodeThe boundaries of buggy code are within the confines of a module, which is usually theresponsibility of one programmer. It is much easier to detect a bug in a module throughisolation than in a file containing a single mega-procedure. Once the bugs are dispatchedfrom the modules, the pest-free code can then be reused in other parts of the application.

A number of studies suggest a small procedure, a method, is not necessarily more bug-freethan a gargantuan method of 500 lines.

Divide and ConquerThe strongest Roman emperors realized that the solution to conquering their enemieswas to divide the armies of resisters and then conquer the smaller units. Modern analyticalproblem- solving techniques teach the same approach, as do many successful algorithmmasters. The best way to solve a problem is to restate it in as many ways as you possiblycan; this helps identify the “real” problem, which you then break down into smallercomponents. I teach this technique in designing algorithms and will discuss it inlater chapters.

For now, let’s imagine you are hired to build an accounting system that will debit anaccount in one process and credit an account in another. Would it not be best to creatediscrete Debtor and Creditor modules with clearly defined interfaces to accomplish thesetasks? The Debtor module would first deduct an amount from an account and then conveythe number deducted to the Creditor module. These modules can be in the same codefile or in different files, as long as they remain separate entities. This ensures that if abug arises in the creditor part of the code, the debtor part will not collapse as well.

ReuseContrary to what many OO purists claim, reuse became the battle cry of softwareprofessionals long before the rise of object-orientation. The idea even predates theindustrial revolution, which heralded the effort to make better products throughfaster and cheaper means.

Here’s an excellent example of reuse. During World War II, the United Statesgovernment ordered car manufacturers to help build bombers such as the Avenger,a small aircraft that was capable of dropping a torpedo, bomb, or mine on the enemy.The companies were ordered to build the components exactly according to specificationsso that parts made by one manufacturer could be used or replaced with the parts ofanother. The result was that by the end of the war many Avengers were flying withtransplanted components made from several manufacturers.

Software reuse allows us to build better programs faster and with fewer programmers.Over the years, many libraries have been built and sold to thousands of companies using

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 9

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:03 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 8: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

identical code in many different products. The code in these components has been testedcountless times and reused in the many different circumstances.

TeamingStructured programming allows us to build a software product in teams. As with theAvenger, various programmers, grouped into designers and implementers, can workindependently on different parts of a product. Structured programming also lets usdelegate according to skill sets, which include writing the stored procedures; drivingthe code on the web site; sorting the data structures; and controlling specifications,class diagrams, use cases, and documentation.

Structural Nada?Despite the progress made since the advent of structure-oriented programming, manydesigners still do not program in a “structured way.” They program without regard forthe interrelationships of modules, organization for reuse, overall structure, or protectionof data. Software project managers often talk in terms of the “number of function points”in an application or system, so as to express the extent or size of the project. But talkingabout so-called function points is meaningless if there is no way to express the architectureof that system, its components, their interrelationships, and its various structures.

As I said earlier, many courses in OOP first teach structured programming, becausea good OO program is also a well-structured one. Many first-year programming coursesthat begin with C++ or Java require you to learn structured programming in theselanguages before you learn to “objectify” your code.

Object-Based ProgrammingAs structured programming methods became more refined, it became apparent tothe engineers that modules of code could be related to as objects. Many languagesgradually become more object-based, especially as compilers emerged that couldenforce encapsulation and cater to the compiling, linking, and binding of numerousmodules into complete applications.

A good example of object-based programming plots the transformation of C into C++.Today C++ is what you would call a hybrid language because it allows you to codestandard C modules, to add objects and do object-based programming, or to invokethe object-oriented features of the language such as inheritance and polymorphism.

Visual Basic is an excellent example of the evolution of a language. It was bornin May 1991, the child of a shapeless language parent, BASIC. Then it grew into itsstructured programming and module-based programming stages (all the way to VB 6).Now it has matured into a true object-oriented language, Visual Basic .NET. Today thelanguage has pure, compiler-enforced support for inheritance, polymorphism, and allthe great features that pure OO languages support.

10 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:04 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 9: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Object-Oriented Software DevelopmentComputer specifications are advancing at a record pace while prices for these systemsare falling rapidly. As computer hardware gets cheaper, software is getting more andmore expensive. In order to create machines that will address bigger and more complexproblems, we need software that is more complex and thus more expensive. Thereis also new hardware such as mobile devices, super fast processors, cheap memory,and tiny hard disks that require sophisticated new software. The problem is furthercompounded by our desire for ever-faster and more powerful computers.

In the early 1990s, servers cost far more than the software running them. Today,you can buy many powerful servers for the same price as the operating system andapplication suite that will be used by a team of people.

While structured programming helps flatten the complexity curve of programming,it is still difficult to manage large software development projects with structure-orientedpractice alone.

Ten years ago, a text-based word processor consisted of fewer than 30,000 lines ofcode and probably required fewer than five people to build and maintain it. It was easyto write the modules to its easily defined structure. Fifteen years ago, word-processingsoftware merely displayed characters, saved text files, and at best provided spell checking.

Today, an average word processor comprises millions of lines of code, highly complexdata structures, and algorithms—not to mention all the complexities of the underlyingoperating system. Today’s system caters to writing, linguistics, semantics, grammar,design, layout, typography, printing, production, imaging, word recognition, and somuch more.

As soon as a structured-programming project becomes large and complex, yourability to manage and maintain the application begins to break down. Couple thiswith the demand for artificial intelligence, highly advanced and complex algorithms,specialized graphics and effects, sophisticated business systems, and so on, and youend up with software too complex to comprehend.

The main problem in building such software is that our human abilities to design,organize, manage, and maintain it have not evolved much. In fact, we are less able totake control of our software today than we were 10 or 20 years ago. It would be safe tosay that any sizable application is beyond the ability of any one person to comprehend.

Thus, the founders of OOP realized that if software modules were managed accordingto the objects they represented instead of the collective sums of their functions, howeverwell organized, then the development process would undergo a major paradigm shift.

While both structure-oriented and object-based programming focus on design practice,object-oriented development pushes this process to the level of attributes, services,properties, and concepts. OO allows us to design, understand, and maintain highlycomplex software by hiding the complexity of the code behind familiar objects.

Large structured-programming projects are very difficult to manage. Even witha small team of designers, it becomes very hard for each member to understand what

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 11

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:04 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 10: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

the others have written and why. Furthermore, the extreme amount of detail can easilyobscure the larger picture.

Despite the fact that OOP is not a new idea (it was introduced at about the same timethat structured programming began to take hold), many experienced programmers stillstruggle with the concepts underlying it, principally due to the fixation on code. To fullyunderstand OO requires a mental shift away from code construction/implementation,toward design/metaphorical thought. In many ways you have to lose some of themathematician/rocket-scientist mentality. To fully appreciate and understand OOP,you need to become an artist, a choreographer, and a biologist.

Not long ago I had two “experienced engineers” write to me: one responding to astatement in my Java newsletter and another trying to understand Visual Basic .NET.The former said, “OOP sounds revolutionary, but really modularity has been part of astructured programming for decades.” The latter said, “Well, if all that Visual Basic .NETadds to VB is inheritance, then I have been programming in an OO language for yearsalready, so I don’t see what the big ideal is.”

In the next few sections we will talk about the concepts of OOP, but just enoughfor you to take the OO test and judge Visual Basic. I believe you need an unshakableunderstanding of OOP to get the best out of .NET development and Visual Basicprogramming. Thus, several chapters in the book are directly about OOP conceptsin Visual Basic and every chapter touches on OO concepts in one form or another.

Real-World ReflectionsIn recent years, object-oriented development has gained enormous popularity because ithelps us decompose extensive software systems from a high viewpoint. It takes abstractionto the highest levels above the code because it allows the software designers to modeland design their system as collections of objects that can be associated with real-worldsituations or as objects in the real world.

Take a look at your hand. What do you see? Do you first see a hand or its anatomy?Even an orthopedic surgeon, who is trained to see the anatomy, still does not focus onthe molecules that make up the anatomical parts of the hand. If we were unable to mentallyencapsulate all anatomical or molecular ingredients at these lower-levels, we would notlast ten seconds in the world.

OO provides the same benefits. It lets us collect the anatomical and molecular low-levelroutines of our software in objects that are then grouped together to make the system.Thus, we could say that an application is a collection of 250 objects, or we could chokeon the statement that “our system is 100,000 lines of code, 4,000 functions, 200 variables,and so forth.”

How do the objects integrate and interoperate to form the application and performits collective duties? In the real world, objects in a biological system accomplish thisthrough a complex network of messages. Sender objects send messages to Receiver objects,which act on the requirements contained therein. If the receiver does not process theinput correctly, or the sender falters in its delivery, or the messaging system itself isfaulty, the entire “organism” might be affected. For example, when we get hungry

12 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:05 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 11: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 13

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

and pick up a sandwich, our mouth receives the message to open and to process the food.If the neurological pathways begin to break down, as in the case of multiple sclerosissufferers, the objects that make up the organism are unable to act and the organism dies.

We use object-oriented design techniques and tools to help us develop object-orientedsystems. The engineering of OO software is similar to other engineering disciplines;an OO system is built in the same way a structural engineer constructs a bridge or anarchitect designs a house.

An architect starts by sketching and then transfers the design to a computer so thatit can be properly scaled and organized into its respective system of objects (hence myattestation that software engineering facilitates all forms of engineering). The housemay be modeled so that it can be viewed in its physical form, albeit much scaled down.When the house is ready to be built, the various objects of the house are constructed.We software developers prefer to use the term implemented, but the idea is the same.

Our modeling and design tools have become very advanced in recent years. WithUnified Modeling Language (UML) as the principal [modeling] language, tools likeRational Rose and Visio 2002 (to mention two premier products) enable us to designand model the most complex systems effortlessly. If our customers can imagine it, wecan build it; the only limitation is their budget.

The concept of pattern languages is beginning to take root and will be part ofmainstream software engineering, like UML, within a few years.

What Makes a Pure Object-Oriented LanguageWhile OO allows us to apply abstract concepts to the design of our systems, the closerwe get to the implementation, or code, the less we begin to care about OO. In fact, oncethe source code is compiled, the “OO-ness” is completely gone, because the processorsdo not care about objects and their attributes. They care about what operations need tobe performed, what instructions need to be processed, and how much memory it takesto do the computations or process the data. At the method—or routine—level, we areprogramming the objects; the logic and practice at this level are the same for object-orientedlanguages as they are for structured-oriented languages.

However, if OO were nothing more than a design technique, it would not be as usefulas we would like. We can design according to real-world problems, scenarios, and objects,and we can also implement the functionality along real-world lines, as far as possible.So there are a number of additional traits or features of OO languages that allow us toextend the object model to the lower levels, which allows the objects to interoperate onthe outside and the methods to interoperate on the inside.

A “pure” or “true” object-oriented language thus comprises the following traits:

1. Modularity is achieved in modules called classes, the unit of encapsulation.

2. Related classes are grouped in hierarchies. The classes are related bydescent—inheritance.

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:05 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 12: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

3. The classes can be instantiated at runtime as objects, and their functionality anddata dynamically accessed. (Class functionality can also be statically accessedwithout instantiation.)

4. Objects access one another’s data and implementation using messages passedbetween them.

5. Objects are able to dynamically respond in different ways and serve upvariations in functionality in response to the same message—polymorphism.Through the employment of interfaces, polymorphism is achieved becausedifferent implementations can exist behind the same interface used in morethan one place.

If you expected to find encapsulation on the list, you might be surprised. Let’s considersome of the points made earlier. Encapsulation is often cited as one of the three mostimportant tenets of an OO language (inheritance and polymorphism are the other two).But while it is vital to OO, encapsulation is really a trait of all modern programmingmethodology, adopted without question by OOP from both object-based programmingand structured programming practice. Encapsulation was certainly supported in theearlier versions of Visual Basic. Therefore, inheritance and polymorphism are the two criticalenabling features of all true OO languages. Visual Basic now supports both.

Having said that, just because a language supports both inheritance and polymorphismdoes not mean that it is 100 percent object-oriented. Let’s review the five essential traitsand then investigate implementation according to real-world analogies.

Just ClassesIn an OO environment, all code is written in a class structure. The attributes ofthe structure, compiler directives, class declaration, references and directives in theimplementation code, direct compilation and the transformation of the class into a memberunit of an application, or as part of a dynamically linked library that can be accessed byother applications.

The .NET Framework classes comprise the built-in types, base classes, objects,interfaces, attributes, enumerators, events, and so forth, which cater to the fundamentalobject-oriented software principles of modularity, abstraction, encapsulation, andclassification.

Classes for Modularity, Cohesion, and CouplingThe principle of modularity in software systems (which, as we discussed already, predatesOOP) requires that classes be organized into highly cohesive, but loosely coupled units.Figure 1-1 illustrates the concept. The cohesion in the classes relates to the collectionof methods and data that are organized to serve the common purpose of the class.

In order to define common purpose, let’s consider the cells in the human body.Different cells have specialized jobs to do, and their contents are highly cohesive

14 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:05 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 13: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

properties that serve a common purpose. Brain cells, for example, do not have thesame properties and methods—ways of doing something for an organism—that bloodcells do. They’re only composed of elements that enable brain functions, such as memoryretention. Similarly, our white blood cells contain only the highly cohesive assortmentof components that fulfill their role of protecting against bacterial infection. The propertiesof divergent types of cells may look the same, but they do different things for varyingreasons. Each cell’s contents are isolated from other cells—nature does not store thefunctions of brain cells in blood cells.

Likewise, you would not put the elements required for file operations in a class cateringto encryption. When you need to use methods for file operations, however, the File classshould be accessible to all other classes. This is where loose coupling comes into the picture.

The loose coupling of classes relates to their interdependency. In other words, classescan interact with each other—an activity that is achieved through the messaging network(method calls) we discussed earlier. (Incidentally, this loose coupling is also very similarto the interdependencies of living cells. Figure 1-2 shows how forms are used to presentthe user interface and how they need only provide implementation for user input andinformation. Access to data and functionality is derived from a framework of classesand objects in which the form is merely a central object for presentation and input (a verydifferent focus from the form-centric model in older versions of Visual Basic).

Conversely, classes can also be tightly coupled when they need to be. Inheritance,composition, aggregation, interfaces, and other coupling techniques provide provenmethods of interaction among classes that depend on each other.

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 15

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

Figure 1-1. Cohesive, loosely coupled units send messages to each other

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:06 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 14: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Classes for AbstractionWe encounter abstraction every day of our lives. Complex systems are presented to uswith their intricacies separated from the essential components required to understandthem. Software engineers and information technology experts work with this reality allthe time. Whites Papers, for example, aim to present a technology through abstractionand are nothing more than distillations of extremely complex subjects. Chapter 2, albeitlengthy, is an abstract of the common language runtime. Its coverage of the subject shouldbe sufficient for programmers who don’t have plans to build a new compiler or a new.NET language. (See Introduction about White Papers.)

Abstraction in OOP is a central principle dictating that programmers do not needto grasp the complexities of various implementations in order to use them. For example,there is little reason to know how a method executes the heapsort algorithm if you onlyneed to sort and not to implement a better heapsort.

16 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

Figure 1-2. Applications are collections of loosely coupled classes

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:07 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 15: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Classes for EncapsulationEncapsulation and abstraction go hand in hand. Classes abstract the complexities oftheir functionality but make that capacity available through simple interfaces. This isthe essence of encapsulation.

Interfaces are a central tenet in OOP and a very important feature of the .NETFramework. Interfaces and implementation are separated from each other. The latteris provided as standard class members.

But the framework also allows you to provide abstract classes as the foundationfor class hierarchies. These base classes are able to provide abstract methods withoutimplementation and allow you to inherit such interfaces for implementation in descendantclasses. The framework also supports formal interface classes. Later we’ll examine howthey facilitate polymorphism. Interfaces are discussed at length in Chapter 10, “Interfaces”

Classes for Hiding InformationEncapsulation hides information, implementation, and data from parties that don’t needto access them. You only need to know how to pass data to the class’s sorting methods,what the impact of the sort may be on system resources, and how the sorted data isreturned to you. It’s similar to taking your shirts to the cleaners. It doesn’t matter whatmachinery they use as long as the shirts are cleaned well.

Why is it so important to hide certain data and procedures? (You’ll see notesand references to hiding in many places in this book.) In understanding the benefitsand differences of loose coupling, tight coupling, and cohesion in classes, you’ll quicklycomprehend why publicly accessible data detracts from these traits.

As soon as loosely coupled classes begin to access each other’s data directly viapublicly accessible fields they begin to depend on each other. For example, if class Bcontains methods that depend on data residing in class A, it would be better to mergethe two classes, or have class B inherit from class A because you might not be able toeasily change the interface to the data without damaging the dependent class’s interest.The classes have thus become tightly coupled through bad design . . . and the couplingmay be the opposite of what we want to happen.

Shared information and data makes software maintenance much more costly andtime-consuming, as illustrated in Figure 1-3. Several classes that can directly accessthe public variable of a single class will do so. And if they do, they will all have to beupdated every time the shared data field is changed or the interface to the class is alteredor discontinued. You may only have one publicly exposed field, but if a thousand classesdepend on the field, changing it affects all one thousand classes.

In highly complex systems involving many programmers, it becomes difficult tochart which class is dependent on the data in another class without formal couplingtechniques such as inheritance and aggregation. Sharing information per se is generallynot wise, even if you have no formal specification or requirement in place for accessingthe public data.

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 17

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:08 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 16: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

It is also much easier to trace sources of bugs and defects when elements and methodsare encapsulated because you know that no other class, except a nested class, is dependenton them. So when changes are made, they only affect that class’s members, which alsomakes this group less prone to causing problems in the application.

There are suitable techniques for sharing information when this is a requirement.In the chapters to come, we will explore explicit design techniques and patterns thataccomplish this. For the most part, access to data occurs through strictly controlledinterfaces and protocols. If you remember that the contents of your class are secretand only available on a need-to-know basis, you’ll have far fewer problems withyour code down the line.

Code that is open to public variables is also vulnerable to security breaches. Whenmultiple threads access public variables, the code becomes less reentrant and more aptto suffer corruption and data loss.

Classes for ClassificationWe know that if a module of structured code can be organized as objects, then those objectscan be grouped into classes that share functionality and mirror real-life scenarios. Further,these can be aggregated into libraries, allowing classes that have similar traits to shareand reuse data and implementation.

The test for classification is a simple one. If a conglomerate of classes belongs to ahierarchy, or the components are logically derived from each other, then they belongtogether. The same is true for animals: It’s easy to differentiate between canine andfeline, for example. It’s not difficult to determine if classes already belong to a certaingroup. You simply ask “What is it?” The answer will take the form “it is an x” or “itis a kind of” and you have the collection of classes to which it belongs. If you cannotidentify what your class is and the design calls for more classes of the same “thing”then you have the makings for a new class collection.

Sometimes its harder to determine what your class is a member of. For example,a cheetah has all the signs of being a kind of cat, but it does not have retractable claws.So you would have to decide whether the cheetah “is a kind of cat” or “is a kind of dog.”

18 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

Figure 1-3. Classes that depend on other classes for global data are harderto manage

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:08 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 17: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Class that Beget Classes: InheritanceNow that you can aggregate your classes in hierarchies and collections, it becomesmuch easier to reuse the classes or couple them in various ways. A feature of OOP isinheritance—modeled on nature, it lets classes share common functionality and data ina formal framework. In nature, descendants receive many attributes from their parents.We never derive 100 percent from them because then we would lose our uniqueness.

A file manipulation class at the base level, for example, requires the fundamental abilityof providing the essential file manipulation functionality: create, open, delete, move, andsave files. It makes sense that once a class with these basic functions is established, newclasses performing some type of input/output (I/O) might inherit this functionality.

This is what code reuse means: It involves using the exact same code provided inthe base class everywhere you need a basic-file I/O routine, not reusing legacy codewritten 40 years ago by cutting and pasting it into a new class. In other words, evenif a mega-application has 150 different classes that need access to file manipulationroutines, there is only one file-manipulating class that the entire application hasaccess to.

In properly designed applications, reuse can achieve as much as a 70 percent reductionin the introduction of new code.

Classes for Objects: InstantiationClasses are represented at runtime by their objects. You can think of a class as the blueprintfor the object. At design time, the class is nothing more than a unit of implementation—the equivalent of the module in structured programming. At runtime, the classes becomeobjects through a process called instantiation, instance creation, or instance activation.

Once an object is created and represented in memory, it can enjoy relationships withother objects through the messages distributed around the application. Objects occupyheap space or stack space, so they need to be managed as part of the software/computer“eco-system.” If they take up space and are no longer needed, then they need to bedisposed of so that other objects can be created and allowed to do their work.

Classes for Association, Aggregation, and CompositionObjects are related to each other and interact with each other in ways that make senseand mirror nature. For starters, if objects become too big they can be broken down intosmaller objects, which can then share associative relationships. For example, with anEmployee class that provides an authentication facility by verifying presented credentialsagainst a database, it may make sense to break it down into two classes—one to specializein authentication and one to handle Employee data. This will yield a smaller Employeeobject that processes data and communicates with the user interface on one hand andthe smaller Authenticate object on the other. The two objects will be associated by theneed for an employee to authenticate. The associative relationship will be from Employeerequesting authentication from Authenticate, which receives the data and presents it

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 19

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:09 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 18: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

20 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

for verification against a database, and not the other way around. The buzzword forthis relationship is “delegation.”

When an object is required to take on more than one role, we say that the objecthas an association relationship to another object. For example, Employee objects needto associate with Company objects for various reasons, such as signing non-disclosureagreements. But it is also possible for the Employee to interact with the Company objectas a shareholder, director, or executive officer. Composition is similar to aggregation,but it exists for the exclusive relationship that one object has with another. An exampleof composition is a linked list which is constructed from two types of classes: a classthat represents the list object as a unit and a composite node class that is instantiatedas nodes belonging only to the list object in which it resides.

We will delve into various relationships further in Chapters 9 and 13.

Classes for EventsOOP is the key enabling technology for event-driven programming. If one objectchanges the state of its data or a variable and another object needs to know about theevent, a message can be passed that allows independent objects to act on input fromthe first one. Thus, entities can make control-flow decisions or take action according tochanges in the system as a whole. The .NET Framework event-model is discussed mainlyin Chapter 14, but also in the chapters in part IV.

Classes for Message PassingIn pure object-oriented systems, objects interoperate by passing messages as describedearlier. Objects issue messages to invoke functionality, send or receive data, and so on.In the .NET languages, this is known as the method call. In order to reference methods,properties, and other components of classes, the method calls need to conform to a format.This format is known as the message signature.

How do you send a message to an object? First your code needs to reference the nameof the object and its method. Consider the following method:

MyPhone.Dial(PhoneNumber)

This is a message communicating to a phone object named MyPhone and telling it(the method call message) to phone the number passed in the message to the parametercalled PhoneNumber. “MyPhone” is the name of the receiver and the object that sendsthe “dial” message is called the sender.

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:09 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 19: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 21

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

Classes for PolymorphismPolymorphism means “many forms” in Greek. It is one of the foundational tenets ofobject-orientation and is usually one of the hardest traits to grasp in OO development.It allows the implementation behind an interface to change without affecting the clientor the value of the service expected by the client. It is also the process that allows entitiesto act in different ways depending on the message they receive.

If you are new to programming, polymorphism might be an easier concept to masterthan if you were trained in classic Visual Basic and had never been exposed to the idea.Polymorphism is nonexistent in the procedural-structural or object-based programmingworlds where functions and procedures do not hide inside objects that interact withtheir environment through a system of messages.

The public-switched telephone network (PSTN) is a good example of polymorphismat work. Ever since the invention of the telephone, the user experience has hardly changed.Except for a few adjustments in the way you request a telephone number, the processof dialing and speaking has remained unchanged for more than a century—you pickup the phone, dial the number (dials are actually obsolete), and speak.

It all started with two tin cans and a piece of string (which was the model). But onceelectrical current was introduced and voice was carried over the circuit, or the loop, ourlives changed forever. Behind the interface, however, there have been many updatesto the processes involved in making the connections, converting the signals, switching,and so on.

No matter what implementation technology is behind the interface, or telephone—tone detection, voice recognition, pulse detection, digital or analog transmission, wireor fiber optics, landlines, the Internet—the user remains unaffected and obtains theservice expected.

Classes for InterfacesThe .NET Framework provides for the incorporation and employment of interfaces,which are key to integrating method polymorphism in an OO framework. The conceptof pure interfaces that provide no implementation may be difficult to comprehend. Butif you understand the meaning of polymorphism, the reason we have interface classesbecomes clear.

Polymorphism implies that you can have many different implementations (code) of amethod behind a single interface. Methods are defined in interfaces by providing only thesignature, which consists of the method’s identifier (its name) and formal parameter list.The interface and the definition become part of a contract between the implementor andthe interface provider for the purpose of enabling polymorphism at the method level.

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:09 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 20: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

Thus, wherever the interface is implemented it provides the additional forms inwhich a method definition can be implemented. In the end, you have a single interfaceand a method definition, but many forms of implementation. Once the implementingclasses are coupled with other components in the .NET Framework, or with private orthird party collections, the entire framework is extended and advanced.

FrameworksFrameworks are collections of reusable classes that present software designs and code thatcan be recycled for various application domains. A framework can be a small collectionof classes or it can be a massive collection of libraries and technologies composed ofthousands of reusable classes, and millions of lines of code, organized in namespacesand packaged in assemblies, as in the .NET Framework.

The .NET Framework caters to the complexity problem associated with extensive classlibraries, components, and various interoperable layers. In short, it is a massive and deepfoundation on which to build software economically. It would have been extremelydifficult, time-consuming, and expensive for us to have to write the code that existsin the framework, to deal with the various operating systems, the networks, the hardware,and so on, in addition to writing the software our clients require.

You could argue that the .NET Framework tries to solve a problem that feeds onits solution. The bigger and more complex the operating system and the bolder theapplication- and problem-domains, the more we depend on the framework.

.NET’s object-oriented design facilitates the reuse and extends the code base throughOO development features, such as inheritance and polymorphism. Frameworks arediscussed further in Chapter 2, which introduces the common language runtime.

PatternsPatterns drive frameworks and encourage not only code reuse but design reuse. Codereuse relates to the sharing of classes and code. For example, a method, which may beinherited, can be deployed unchanged in many different places. At a higher level, the.NET Framework becomes a natural facility for the incorporation of patterns.

The use of patterns is a fascinating trend that has emerged from the many featuresof OO software creation. Patterns prescribe, through design and architecture, how reusingvarious solutions and techniques can solve any software problem. This represents ahigher level of abstraction.

To understand design patterns in software development, you should understandthe model behind the concept. The idea of pattern use is not new. It is borrowed fromthe works of architectural genius Christopher Alexander who described how for thousandsof years people’s design and construction techniques remained unchanged. In three books

22 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:10 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 21: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

and numerous papers on building patterns, Alexander illuminated timeless buildingpractices that can be distilled into 253 patterns.

See The Timeless Way of Building by Christopher Alexander (1979), A PatternLanguage— Towns, Buildings, Construction by Christopher Alexander et al., (1977),and The Oregon Experiment by Christopher Alexander et al. (1975).

According to Alexander, “Each pattern describes a problem which occurs over andover again in our environment, and then describes the core of the solution to that problem,in such a way that you can use this solution a million times over, without ever doingit the same way twice.”

Over the years OO developers have found parallel concepts for software-designpatterns. In 1995, Erich Gamma and three of his colleagues published one of the firstsoftware-pattern catalogs called “Design Patterns”, which was based on the findingsof Alexander. See Design Patterns: Elements of Reusable Object-Oriented Software by ErichGamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995).

Gamma’s work contained a collection of 23 of the most commonly used general-purpose software-design patterns that are application- and problem-domain independent.The book classifies the patterns as follows:

■ Creational Patterns Deal with the creation of objects

■ Structural Patterns Deal with the static composition and structure of classesand objects

■ Behavioral Patterns Deal with the dynamic interaction among classesand objects

Pattern use has been widely adopted by large developer communities. It is asmuch a part of the Java developer’s arsenal as are code-reuse concepts like inheritanceand composition. Developers of .NET find themselves poised to exploit not only aframework but also a vast collection of proven patterns from which to begin softwareconstruction.

You will find pattern references being repeated many times in this book: Theseinclude ones for static classes, object creation, inheritance, aggregation, association,delegation, and more. The text will encourage you to develop and refine your ownpatterns and contribute them to the efforts of the developer community.

There is now alternative thought that patterns are outmoded in the new world of Webservices, XML, and the Simple Object Access Protocol (SOAP). But just because clientand server processes can be split over wide areas and across disparate platforms andnetworks does not make the implementation on each side any less object-oriented. Onthe contrary, I believe formal pattern use among .NET developers is set to explode. SeeChapters 4 and 9.

C h a p t e r 1 : S o f t w a r e D e v e l o p m e n t a n d V i s u a l B a s i c . N E T 23

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

INTR

OD

UC

TION

TOV

B.N

ET

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:10 AM

Color profile: Generic CMYK printer profileComposite Default screen

Page 22: Chapter 1 - McGraw-Hill Educationbooks.mcgraw-hill.com/downloads/products/0072133813/0072133813_… · discussed later in this chapter, is borrowed from civil engineering. ... Structural

ObservationsAlbert Einstein was quoted as saying: “Everything should be made as simple as possible,but no simpler.” In many respects, Visual Basic .NET and the .NET Framework shouldbe viewed in the essence of that remark. It is going to take a lot of effort to fully understandall the features and implications of using the new “version,” but in the end, softwareengineering will become much easier.

It should be very easy for you now to understand what Visual Basic .NET is andthat it supports all the tenets and principles of a pure OO software-development language,such as inheritance and polymorphism.

However, Visual Basic also supports many other desirable features of a pure OOlanguage, and these include structured-exception handling (the application of objectsto trap and handle errors), free threading for concurrency, and so on. The extensiveframework does not only support Visual Basic like all .NET languages, but a common-language managed-code runtime environment that takes care of the economics andhousekeeping.

Hopefully it is now clear that this book is a reference manual for both the constructionand implementation abilities of Visual Basic as well as its design, structuring, modeling,and maintenance abilities. Many chapters are devoted to using the OO features andthe design-level aspects of software engineering; others focus lower down in the class“ranks” of the framework where we deal with services, functionality, and code.

It should also be clear to you as an experienced Visual Basic programmerthat Visual Basic .NET introduces a significant paradigm shift in the development ofapplications. It replaces the concept of developing with forms, which is an outdatedmodel that harks back to an over-hyped era of “visual” programming. As discussedearlier in this chapter, our focus is on classes, objects, and new concepts, not on howto “drop” controls on forms. This is the reason that the main discussion on Windowsforms and user interfaces is reserved for the latter part of the book.

However, before we can tackle either the design or the construction subjects, wefirst have to get familiar with the framework and the runtime that support the language.This and more are the subjects of Chapter 2.

24 V i s u a l B a s i c . N E T : T h e C o m p l e t e R e f e r e n c e

Complete Reference / Visual Basic .NET: TCR / Shapiro / 9381-3 / Chapter 1

P:\010Comp\CompRef8\381-3\ch01.vpTuesday, March 19, 2002 10:16:11 AM

Color profile: Generic CMYK printer profileComposite Default screen