It became apparent to me how different .NET in general and Visual Basic .NET in particular was going to befrom the current version of the language VB 6 and the current Windows software d
Trang 2Table of Contents
Visual Basic NET The Complete Reference 1
Foreword 3
Acknowledgments 6
Introduction 8
Chapter 1 10
Chapter 2 10
Chapter 3 10
Chapter 4 11
Chapter 5 11
Chapter 6 12
Chapter 7 12
Chapter 8 12
Chapter 9 12
Chapter 10 13
Chapter 11 13
Chapter 12 13
Chapter 13 13
Chapter 14 14
Chapter 15 14
Chapter 16 14
Chapter 17 15
Conventions 15
Part I: Introduction to Visual Basic NET 16
Chapter List 16
Chapter 1: Software Development and Visual Basic NET 17
Overview 17
Visual Basic and the Difficulty of Developing Software 17
Reducing Complexity and Time−to−Market with Reuse 18
Software Development and Software Engineering 18
The Classic Programming Models 19
Structured Programming 20
Bug−Reduced Code 21
Divide and Conquer 21
Reuse 21
Teaming 22
Structural Nada? 22
Object−Based Programming 22
Object−Oriented Software Development 22
Real−World Reflections 24
What Makes a Pure Object−Oriented Language 25
Just Classes 25
Classes for Modularity, Cohesion, and Coupling 26
Classes for Abstraction 27
Classes for Encapsulation 27
Classes for Hiding Information 27
Classes for Classification 28
Trang 3Table of Contents Chapter 1: Software Development and Visual Basic NET
Class that Beget Classes: Inheritance 29
Classes for Objects: Instantiation 29
Classes for Association, Aggregation, and Composition 29
Classes for Events 30
Classes for Message Passing 30
Classes for Polymorphism 30
Classes for Interfaces 31
Frameworks 31
Patterns 32
Observations 33
Chapter 2: Visual Basic NET and the NET Framework 34
Overview 34
Getting to Know the Framework's Runtime 35
The Common Type System 35
The Common Language Specification 36
The Common Language Runtime 38
Microsoft Intermediate Language 40
Metadata 41
Executable Code 42
Managed Execution 42
Side−by−Side Execution 44
Application Domains 44
Automatic Memory Management 45
Just−in−Time Deployment 46
Understanding Assemblies 47
Locating Assemblies, Anytime 48
What's in an Assembly 49
The Roles of the Assembly 53
Attributes, Reflection, and Assemblies 55
Strong Names 55
The NET Security Model 56
Observations 58
Part II: Visual Basic NET Fundamentals 60
Chapter List 60
Chapter 3: The Visual Basic NET Development Environment 61
Overview 61
Working with the Visual Studio IDE 61
Navigating the IDE 62
Starting from the Start Page 69
Creating a Visual Basic NET Solution 72
Loading the Vb7cr Solution 73
Creating a New Project 73
Solution Directory Structure 76
File Extensions 76
Working with the Base−Class Library 77
A Minimal Visual Basic NET Application 80
Trang 4Table of Contents Chapter 3: The Visual Basic NET Development Environment
Observations 82
Chapter 4: The Elements of Visual Basic NET 83
Overview 83
Visual Basic NET: The Foundation 83
Lexical Elements 83
Preprocessing Directives 84
General Concepts 84
Option, Imports, and Namespaces Directives 84
Types 85
Type Members 85
Statements and Statement Blocks 86
Expressions 86
Operators 87
Visual Basic NET Mini Style Guide 88
Naming and Notation 88
Hungarian Notation 89
Word Choice 90
Getting Started 90
Character and Lines 91
Statements and Blocks 95
Nothing for Nothing or Something for Nothing 96
Classes, Types, and Objects: What's the Difference? 97
Classes: The View from Above 98
The Class Declaration Space 99
The Directive Space 102
The Implementation Space 109
Elemental Value Types 110
Working with Numbers 112
Integer Types 112
Visual Basic 6 to Visual Basic NET 113
Point Types 113
Characters 114
Booleans 114
Literal Notation 115
Type Conversion 118
Working with Variables and Constants 120
Variable and Constant Declaration Shorthand 124
Default Initialization 125
Keeping Data Private 126
Scope 128
Variable and Constant Lifetimes 129
Observations 131
Chapter 5: Visual Basic NET Operators 133
Overview 133
What an Operator Does 133
Numbering Systems Reviewed 134
Positional Notation 135
Trang 5Table of Contents Chapter 5: Visual Basic NET Operators
Converting from One System to Another 136
Operator Precedence 138
Changing Precedence Order with Parenthesis 139
Unary Operators 140
Arithmetic Operators 141
Assignment Operators 141
Comparison Operators 143
Concatenation Operator 144
Logical Operators 144
Logical And, Or, and Xor 145
Short−Circuit Logical Operators 146
Bitwise Operators 147
Flag Sets 148
Shifting Bits 150
Specialized Operators 154
Is 155
Like 155
Operator Overloading 156
Exceptions Referenced in this Chapter 158
Observations 158
Chapter 6: Software Design, Conditional Structures, and Control Flow 159
Overview 159
Control Structures 160
Control Flow 160
Fully Sketched Code 162
Step−Form Notation 162
Pseudocode 162
Nassi−Schneiderman Charts 162
Flowcharts 163
Design Pitfalls 164
Conditional Statements 165
If 165
Else 168
Else If 168
Tips for Else and Else If 169
Select Case 171
GoTo 173
OnError 174
Loops 174
DoLoop 174
For Next 175
For Each Next 176
While 177
One or the Other Conditional Functions 177
Choose 177
IIF 178
Switch 178
Pausing, Resuming, and Exiting Iteration 179
Trang 6Table of Contents Chapter 6: Software Design, Conditional Structures, and Control Flow
Exit Idiosyncrasies 180
Observations 181
Chapter 7: Methods 182
Overview 182
What Is a Method 182
Types of Methods 184
Synchronous vs Asynchronous Method Calls 184
Method Data 185
Method Data: Global vs Local 187
Local Declarations 188
Passing Arguments to Parameters 190
Calling Methods 194
Function or Sub Methods 196
Method Access Characteristics 198
Public Methods 199
Protected Methods 200
Friend 200
Protected Friend 200
Private Methods 201
Controlling Polymorphism Characteristics of Methods 201
Mining the Framework's Methods 205
The Methods of System.Math 206
Programming with the Math Class 208
Math−Related Exceptions 210
Properties 211
Properties vs Fields 213
Properties vs Methods 214
Introduction to Exception Handling 214
The Exception Handler 216
Try Catch Blocks 217
Design and Construction of Methods 218
Class and Method Cohesion 220
Method Coupling 222
The Length of a Method 222
Recursive Design of Methods 223
The Base Case 224
The Stopping Condition 225
The Impact of Recursion 226
Understanding Method Performance 227
Observations 231
Part III: Classes and Objects 232
Chapter List 232
Chapter 8: Types, Structures, and Enumerations 233
Overview 233
The Value−Type Model 233
How Value Types Work 235
Trang 7Table of Contents Chapter 8: Types, Structures, and Enumerations
Boxing 236
Why are Value Types Objects? 238
Structs and Enums Ahoy: Creating New Value Types 239
Structures 240
Structure Behavior 246
Enumerations 248
Working with System.Enum 250
Flags 253
Final Words on Enums 255
The Object−Reference Model 256
Null Reference 261
What the Reference Refers To 262
The Object−Reference Model and Equality, Comparison, and Assignment 262
Observations 263
Chapter 9: Classes 265
Overview 265
Getting the Semantics Correct 266
Of Classes and Types 267
Semantics and Notation 267
Modeling 267
Software Modeling 268
Viewpoints 269
Unified Modeling Language 271
UML Diagrams 272
UML Notation for Class Diagrams 273
UML Notation for Class Relationships 274
Modularity 274
Modularity Metrics: Coupling and Cohesion 275
The Classes Are the System 275
Class Characteristics 278
In the Beginning Abstract Classes 279
Factoring Out Commonality 280
The Members of Abstract Classes 281
Inheritance 282
Inheritance and Polymorphism 284
Inheritance and Coupling 284
Multiple Inheritance 285
Order and Control with Inheritance 286
Reduction of Complexity 287
Maintenance 288
Code Reuse 288
Implementing a Space Ship's Fuel Injector Software 289
Instance Fields 290
Instance Constructors 292
Properties 293
Methods 295
Publishing the ShuttleInjector Class 297
Activating the ShuttleInjector Class 298
Trang 8Table of Contents Chapter 9: Classes
The Inherited Members of Object 300
Testing for Reference Equality with Equals 300
ToString 301
Cloning 302
GetHashCode 303
GetType 303
ReferenceEquals 304
Finalize 304
Aggregation and Composition: Reuse by Containment 304
More Aggregation at Work: A Form for Testing 308
Ending Inheritance with Sealed Classes 310
Improved Performance with Shared Classes and Modules 311
Observations 312
Chapter 10: Interfaces 313
Overview 313
Abstraction and Interfaces in Object−Oriented Software Design 313
Getting Passionate (or Radical) about Interfaces 315
Interfaces and Inheritance 316
Realizing the Benefits of Interfaces 318
Implicit Interfaces 318
Explicit Interfaces 320
Abstract Class or Explicit Interface 321
An Introduction to Interface Design and Implementation 322
Accessing and Using the Implementation 324
Compound Interfaces 325
Designing and Defining Interfaces 327
Interfaces, Once Published, Must Not Change 327
Interface Invariance 327
Constructing the Interface 328
Getting Started with the Interface Definition 329
Implementing Interfaces 331
Interface Implementation Semantics 331
Implementing ICloneable 332
Implementing IComparable 333
Exceptions Covered in this Chapter 334
Observations 334
Chapter 11: Exceptions: Handling and Classes 336
Overview 336
Why Do We Need Exception Handling? 337
Structured Exception Handling 101 337
Exception−Handling Models 340
The Resumption Model 340
The Termination Model 340
Recovering from Exceptions 341
Exception Statements 343
Try 343
Catch 344
Trang 9Table of Contents Chapter 11: Exceptions: Handling and Classes
Finally 348
When Filters 349
Nesting Try Blocks 351
Throw 352
Exception−Handling Tips 357
Creating Your Own Exception Classes 358
The NET Exception Hierarchy 358
Choosing a Base Class from which to Inherit 359
Observations 362
Chapter 12: Collections, Arrays, and Other Data Structures 363
Overview 363
NET's Array and Collections Namespace 364
Specialized Collections 366
ICollection 366
IEnumerator and IEnumerable 367
IList 367
Stacks 367
How to Program Against a Stack 371
Queues 372
How to Program Against a Queue 374
Arrays 376
The Array Class 377
Declaring and Initializing Arrays 378
Declaring Multidimensional Arrays 381
Jagged Arrays 381
Programming Against Arrays 382
The UBound Statement 383
Redeclaring Arrays 384
The Erase Statement 386
The IsArray Function 386
Array Exceptions 386
Passing Arrays to Methods 388
Receiving Arrays from Methods 389
Searching and Sorting Arrays 389
The BinarySearch Method 390
The Basics of Sorting Arrays 392
Bubble Sort 393
Partition and Merge 397
Quicksort 401
Sorting Strings and Other Objects 406
Populating Arrays 407
Arrays for Objects 407
Hash Tables 413
Observations 417
Chapter 13: Advanced Design Concepts: Patterns, Roles, and Relationships 419
Overview 419
Designs on Classes 419
Trang 10Table of Contents Chapter 13: Advanced Design Concepts: Patterns, Roles, and Relationships
Singleton 420
Bridge 423
Strategy 427
State 429
Linked Lists and Trees 433
Understanding the Linked List 434
Designing a BaseưContainer Class for Lists (and Trees) 436
Implementing the Node 437
Implementing the Container 439
Implementing the Iterator 456
Observations 458
Chapter 14: Advanced Interface Patterns: Adapters, Delegates, and Events 459
Overview 459
Adapters and Wrappers 461
Interface Adaptation in ActionCOMư NET Interop 462
The Adapter Pattern in NET 465
The Adapter Pattern Event Model 470
Delegation: Please Help Me! 471
Delegates 475
Understanding Delegates 477
Declaring the Delegate 477
Early Bound Delegate Declares 478
Late Bound Delegate Declares 479
Sorting Data with Delegates 481
Multicast Delegates 484
The NET Framework Event Model: Delegates and Events 485
Getting Ready to Wireưup: The Event Model in a Nutshell 489
Delegate Events vs Adapter Events 490
Delegates vs Function Pointers 492
Observations 493
Chapter 15: Data Processing and I/O 494
Overview 494
Data Processing 494
Working with Strings 495
Members of the String Class 496
Clone 496
Compare 497
CompareTo 497
Concat 498
Copy 498
CopyTo 499
EndsWith, StartsWith 499
Equals 500
Format 500
IndexOf, LastIndexOf 501
Insert 501
Intern, IsInterned 501
Trang 11Table of Contents Chapter 15: Data Processing and I/O
Join, Split 502
PadLeft, PadRight 503
Remove 503
Replace 503
SubString 503
ToCharArray 504
ToLower, ToUpper 504
Trim, TrimEnd, TrimStart 504
Classic Visual Basic String Functions 504
String Formatting 505
NumberFormatInfo 506
DateTimeFormatInfo 508
Custom Formatters 510
Building Strings with StringBuilder 512
Capacity 513
Append 513
AppendFormat 514
Insert 514
Remove 514
Replace 515
Regular Expressions 515
The NET Framework Regex Metalanguage 517
File, Stream, and Text IO Operations 519
Files and Directories 520
The File Class 521
Path 521
File Enumerations 524
Basic File Class Operations 527
Directory 529
The FileInfo Class 530
DirectoryInfo 531
Using the Classic File System Object 532
FileSystemWatcher 534
Streams 537
FileStream 538
SeekOrigin Enumeration 542
BufferedStream 543
NetworkStream 544
CryptoStream 544
MemoryStream 544
Readers and Writers 545
Text Encoding 545
StringReader/StringWriter 546
StreamReader/StreamWriter 548
BinaryReader/BinaryWriter 550
XML I/O 550
Reading XML Files 550
Writing XML Files with XMLTextWriter 554
Serialization with XML 557
Trang 12Table of Contents Chapter 15: Data Processing and I/O
Activating Serialization at Run Time 560
Observations 561
Part IV: Writing Software with VB NET 562
Chapter List 562
Chapter 16: Interfacing with the End User 563
Overview 563
Windows Forms 565
A Form Is an Object 566
The System.Windows.Forms Namespace 566
Automatically Generated Code 568
Introduction to Threading 569
The User Interface and Thread Design 570
The NET Framework's Thread Model 571
Getting Started with Basic Threading 571
MDI Applications 573
Creating the MDI Parent 573
Creating the MDI Children 575
The Active Child 576
Arranging the Forms 577
Delegating Application Startup and Shutdown 577
Keeping a Form on Top 578
Form Transparency 578
Modality 579
Changing Borders 580
Changing the Size of Forms 581
Screen Location 581
Components and Controls 583
Adding Components and Controls to Forms 583
Layout and Grouping 584
Positioning Controls 588
Setting a Single Property for Multiple Controls 589
Complex Property Pages 589
Using The Property Grid 590
Menus and Toolbars 590
Adding Menus and Menu Items Programmatically 590
Context−Changing Menus 591
Enhancing Menus 593
The Menu Class 594
Responding to User Input 594
Binding Events Dynamically 595
Hot Spots 595
Mouse and Keyboard Events 596
Keyboard Events 597
Using a Timer to Fire Events 597
Collecting User Input 597
Buttons 597
Edit Text Boxes 598
Trang 13Table of Contents Chapter 16: Interfacing with the End User
Check Boxes 600
Radio Buttons 601
Combo Boxes 601
DomainUpDown 601
NumericUpDown 601
Date and Time Picker 601
Calendar 602
A Palette 602
List Boxes 602
CheckedListBox 602
ListView 603
Trackbars (Sliders) 603
Toolbars 603
TreeView 603
Presentation and Informational Controls 603
Labeling 604
LinkLabel 604
Status Bar 605
Icons 605
PictureBox 605
ImageList 605
Progress Bars 605
Grids 606
ToolTip 606
The ErrorProvider Control 606
Help Provider 607
Printing Support 607
Drag and Drop 607
Dragging Data 607
Dropping Data 608
Using the Clipboard 609
Observation 609
Chapter 17: Getting Ready to Release 610
Overview 610
Thinking in Debug Terms 611
The System.Diagnostics Namespace 611
Enabling Debugging 615
Run−time Configuration Files 616
Machine Configuration File 617
Application Configuration File 617
Security Configuration File 618
Working with Configuration Files 618
Working with the Debug Class 618
The Debug Write Methods 619
Assertion 619
Fail 622
Tracing and the Trace Class 623
Instrumentation 623
Trang 14Table of Contents Chapter 17: Getting Ready to Release
Understanding the Phases of Code Tracing 624
Listening to Your Code 624
Developer−Defined Listeners 627
Trace Switches 627
Debugging with Visual Studio NET 629
What Species Is Your Bug 629
Debugging Aids 630
Breakpoints 631
Getting Started 632
The Visual Basic NET Compiler 635
Using a Response File for Compilation 637
Managing a Class Library from the Command Line 638
Conditional Compilation Directives 639
Observations 640
List of Figures 641
Chapter 1: Software Development and Visual Basic NET 641
Chapter 2: Visual Basic NET and the NET Framework 641
Chapter 3: The Visual Basic NET Development Environment 641
Chapter 4: The Elements of Visual Basic NET 641
Chapter 6: Software Design, Conditional Structures, and Control Flow 641
Chapter 7: Methods 642
Chapter 8: Types, Structures, and Enumerations 642
Chapter 9: Classes 642
Chapter 10: Interfaces 642
Chapter 12: Collections, Arrays, and Other Data Structures 642
Chapter 13: Advanced Design Concepts: Patterns, Roles, and Relationships 643
Chapter 14: Advanced Interface Patterns: Adapters, Delegates, and Events 643
Chapter 16: Interfacing with the End User 644
Chapter 17: Getting Ready to Release 644
List of Tables 645
Chapter 2: Visual Basic NET and the NET Framework 645
Chapter 3: The Visual Basic NET Development Environment 645
Chapter 4: The Elements of Visual Basic NET 645
Chapter 5: Visual Basic NET Operators 645
Chapter 6: Software Design, Conditional Structures, and Control Flow 646
Chapter 7: Methods 646
Chapter 8: Types, Structures, and Enumerations 646
Chapter 9: Classes 646
Chapter 10: Interfaces 646
Chapter 11: Exceptions: Handling and Classes 646
Chapter 12: Collections, Arrays, and Other Data Structures 647
Chapter 15: Data Processing and I/O 647
Chapter 16: Interfacing with the End User 648
Chapter 17: Getting Ready to Release 648
Trang 15Table of ContentsList of Sidebars 649
Chapter 5: Visual Basic NET Operators 649 Chapter 7: Methods 649
Trang 16Visual Basic NET The Complete Reference
Jeffrey R Shapiro
About the Author
Jeffrey R Shapiro is a software architect and IT specialist who has written several books on software
development and technology, including SQL Server 2000: The Complete Reference.
McGraw−Hill/Osborne
2600 Tenth Street
Berkeley, California 94710
U.S.A
To arrange bulk purchase discounts for sales promotions, premiums, or fund−raisers, please contact
McGraw−Hill/Osborne at the above address For information on translations or book distributors outside the
U.S.A., please see the International Contact Information page immediately following the index of this book.Copyright © 2002 by The McGraw−Hill Companies All rights reserved Printed in the United States ofAmerica Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced
or distributed in any form or by any means, or stored in a database or retrieval system, without the priorwritten permission of publisher, with the exception that the program listings may be entered, stored, andexecuted in a computer system, but they may not be reproduced for publication
Trang 17George Toma Charbak,
Melinda Moore Lytle
Illustrators
Michael Mueller, Lyssa Wald
Series Design
Peter Hancik
This book was composed with Corel VENTURA Publisher
Information has been obtained by McGraw−Hill/Osborne from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw−Hill/Osborne, or others, McGraw−Hill/Osborne does not guarantee the accuracy, adequacy, or completeness of any information and
is not responsible for any errors or omissions or the results obtained from the use of such information
This book is dedicated to the late Sabas (Saby) Blanco
November 13, 1975 to October 7, 2001
Visual Basic NET The Complete Reference
Trang 18is the NET Framework and, in particular, Visual Basic NET.
Visual Basic NET and the NET Framework and I go back almost five years when I was an aggressive Javaprogrammer (of course, the framework was just a nameless, mysterious OO project at MS then) While Iworked with several flavors of Java, all my customers needed stuff for the Windows platform Visual J++ was
my tool of choice (especially after programming Delphi for a few years) Then, delegates (those so−calledobject−oriented function pointers) and other things that Microsoft was doing with Java hit a nerve center atthe house of Sun The result was the Intifada between the two software makers that stopped VJ++ in its tracks
For the next couple of years the Visual J++ Web site at Microsoft.com and "VJ" remained unchanged TheJava world moved on with newer stuff from Sun, and VJ and Windows Foundation Classes (WFC) languished
in the lawsuits I and tens of thousands of Windows VJ programmers lost a lot of faith in the software
While I developed some sophisticated stuff in VB, I also kept current with Java (not VJ) So it did not take melong to finally "get" what had "set" so many VB programmers to refusing to use anything else to develop theirsoftware (no matter how much certain technology lacking affected them)
When Visual Basic NET emerged I realized I had the best of both worlds everything I loved about VJ and
VB in one package Sure, I still have an affinity for curly braces, but no other language in the world is asproductive as Visual Basic NET, not even C# And I tell you that as a programmer who has coded in morethan just Java, Delphi, and Visual Basic and C#
Well, it is finally here, and it's the best thing since strawberry−flavored cranberries
While chewing on my burger, I also reflected on what Microsoft had said to us earlier that day about how theywould like us to write about the NET Framework The one statement that stood out was that they were keen
to see books that did not simply rehash the tons of information that were going to be put out, or compete withthe online material (which is excellent) They were looking for books that would help people understand notonly the fundamentals of the framework and its many languages, but also how to use the extremely powerfuland complex constructs and technologies they were going to unleash
It became apparent to me how different NET in general and Visual Basic NET in particular was going to befrom the current version of the language (VB 6) and the current Windows software development paradigmsand object models, such as COM and ActiveX I was both surprised and amused at how familiar Visual Basic.NET and the NET Framework now looked to Java, Visual J++ and Delphi
Trang 19I found myself in a unique position, having arrived at Visual Basic (I skipped the earlier versions and cut myteeth on VB 5 and 6) via C++, Delphi, and Java I at once felt that Visual Basic NET would appeal not only
to existing VB developers (or scare some of them half to death) but to the many Java and Delphi
programmers The latter are of special interest to me because, like me, they are not only dedicated to theWindows platform, but they have been programming in true object−oriented languages for almost a decadenow After all, I learned Delphi back in the early 1990s, Java in 1995 Much of what's new to Visual Basic,like true OO and free threading, has been part of the Delphi and Java arsenal for many years You will see that
I talk not only to VB programmers (for the most part) but also to VJ and Delphi programmers
What you now have in Visual Basic NET is the marvelous utility and simplicity of Visual Basic coupled withthe incredible power of OO and Visual J++ (ten−fold) To put it in a nutshell: You can now do with VisualBasic NET what you once only dreamed was possible, and do it faster than with any other language In many
cases, once you get up to speed with the syntax and semantics, you can just about write the software in your
sleep
I have written a number of computer books, but it was a challenge to write a really good software
development book The proverbial hat goes off to all those guys and gals who have penned something forsoftware developers
Having my own library of software development books, I know that you need to strike a balance betweentalking and showing If you talk too much and don't provide enough examples, you lose your audience If youshow too much you end up alienating everyone and might as well be writing in hieroglyphics I especiallydislike books that provide a page of narrative and then throw 15 pages of unexplained code at you I mustadmit I have never learned much about writing software from any of those tomes
It's also difficult to provide meaningful examples and enough of them I believe the examples should beplucked from live code in functioning products They should not be examples knocked up in Notepad thatwere obviously never compiled While I have taken some shortcuts here and there to provide a quick and dirtyexample, every line of code written in this book has been written and compiled in Visual Studio NET andthen tested
You will also find that there is more narrative than code in many places I have gone to great lengths toexplore all the various facets of the constructs and technologies you will encounter as a NET programmer.The reason is simple Computer books don't seem to get thinner, and this is compounded by there being somuch to talk about or explain I decided that instead of publishing 1500 pages with hundreds of examples thatcannot be compiled from wood pulp, or compiled on the train to work, that it would be better to put as muchextra code as possible into the various projects that were created with this book
A giant Visual Studio NET solution, Vb7cr, is included with this book that by publication will have beenculled from more than 50 projects, some of them implemented for commercial applications You will find alot in the projects, from the linked list classes to a full−blown ASP.NET application that implements a
sophisticated search facility, and more They have all been compiled and tested with the released version ofVisual Studio and the NET Framework You can download the software from www.osborne.com and
www.sdamag.com It's just code and downloads easily on a 56K connection, so Osborne and I deemed itunnecessary to come out with a CD
Of particular interest in the solution is a complete binary tree example, which extends the linked list projectcovered in the book Rather than publishing the 50 pages this particular project took, the code has been fullytested and is available in the first version of the solution Not only will you find the classes useful for buildingsophisticated data structures, but the project provides an excellent learning tool for object−oriented
enthusiasts It at once provides grounding in OO, inheritance, aggregation, composition, and polymorphism,
Foreword
Trang 20and discusses how to use interfaces, delegates, exception handling, and some sophisticated algorithms Thereare a number of interesting killer methods in the classes (like recursing the tree nodes and using delegates tospeed up binary search), so you get to work at a high level of abstraction on the one hand and a very low level
on the other
This book assumes you have some idea how to program But it will also work for you if you have never so
much as written a While statement before and you are willing to learn I have provided some grounding on
software development practices for newcomers, like what constitutes good method writing or class
construction Experts will no doubt gloss over these areas, although those experts new to Visual Basic NETwill do well to refresh themselves with the practices that can help them become very efficient OO
practitioners
If you don't know the Unified Modeling Language (UML), you should get a guide to bring yourself up tospeed I express many concepts using UML class diagrams Visual Studio NET for Enterprise Architectsships with a version of Visio 2002 specifically geared for architecting NET software using UML For allsizable software development projects, completing the model (as discussed in Chapter 9) is the first thing youmust do before you hack out a single method
You will find that I spend an enormous amount of time in object−oriented aspects of Visual Basic NET Ibelieve to the credit of the book some chapters are more about OO software development than Visual Basic.NET (hence the reason for the number of UML diagrams in the book) However, every general discussionabout OO software development is backed up by an example in Visual Basic NET
I cannot stress enough, especially to my learned comrades, how important it is to fully understand and use
Visual Basic NET to write correct object−oriented software If you are going to live in the OO house you
need know what's in the ceiling, what the walls are made of, and what's lurking in the basement If you take itall in and not just cook spaghetti on the stove, I promise you will be richly rewarded with an ability to writesoftware in any NET language you want (J# included)
I am incredibly impressed by how Microsoft has gone to great lengths to reduce the complexity involved inwriting good software, while at the same time providing constructs that allow you to create the most
incredible facilities While you get advanced constructs like a free−threading model, which can add to
complexity, they have taken away the need for you to manage every ounce of memory on a computer I oncehad the unfortunate job of creating a high−end mail server, which needed to manage numerous threads.Having to manage memory on every thread at the same time made that task unforgettable
This book in no way covers everything about Visual Basic NET and the NET Framework Just because thetitle says "Complete Reference" does not mean we need to cover every class and every method in NET,although many readers expect exactly that I remember a reader chewing on me about not covering ISAPI in
my SQL Server 2000: The Complete Reference." You call this a complete reference?" he said "Where's the
stuff on using ISAPI to connect SQL Server to the Web?" I wrote the guy back and said "Perhaps I'll addsome stuff about herbal remedies as well," only to be told he would hold me to that statement
To cover everything you need several volumes However, I am fortunate to have a publisher and a greateditorial team that has been willing to allow me to write more than one book Otherwise, we would probablyhave been looking at around 2000 pages
This book is my second on Visual Basic NET The first book, Visual Basic NET Developer's Headstart, is an
introduction to Visual Basic NET It's designed as a quick read to place you on familiar footing with VisualBasic NET It's especially useful if you come from the world of Java and Delphi, and want to be sure VisualBasic NET is for you
Foreword
Trang 21The book you are holding is aimed at core material and fundamentals The Introduction will fill you in withthat aspect of it.
I encourage you to send me your contributions, comments, and any suggestions on fixing or enhancing thematerial presented in this book You can write me at jshapiro@sdamag.com or visit www.sdamag.com Anycontribution you wish to make will be considered and you'll be asked permission to include it in future
editions or in the solutions
I sincerely hope you will enjoy reading this book and gain the enrichment that I have garnered from writing it
Acknowledgments
Many people made this book possible Besides editors and production people and writers, authors, testers,and reviewers, a great many people who did not have a direct involvement in this book nevertheless providedcontributions which were indispensable I would like to thank these dear friends first
During the early stages of this book, I relied heavily on my coworker and assistant, Saby Blanco, who wassadly taken from us without warning in late 2001 (I know God had a reason for recalling Saby in a heartbeat;
I just wish I knew what that reason was) I have dedicated this book to his memory and to thank him for hisfriendship and help He is sadly missed by many He was a terrific person
My wife and dear friend, Kim, has certainly had it rough in recent years, but without her unfaltering
commitment and support it would have been very difficult to reach this stage in the life of not only this bookbut in my other books as well
A special thank you to my sister, Lesley Kalish, for her assumption of many of my family responsibilities thatmade it possible for me to dedicate the time I did to this project I owe the same level of appreciation to myuncle, Charlie Frank, for his support, love, and friendship
I also owe more that a few words of thanks to my wife's family, the Zagnoevs, and in particular to my
father−in−law and mother−in−law, Barney and Entha Zagnoev, whose support in this "venture" and severalothers in the not−too−distant past, has meant a great deal to me
Many coworkers and collegues in the past years made it possible for me to put the words and code in thesepages between book covers They include Steven Cohen at TempArt who always happens to call just whenyou think it's time to give him a shout; Armando Blanco for his support in various technical fields over theyears and for his friendship; and Mike Costolo at C&L Insurance, Inc., who deserves a special thank you forhis support, especially during the weeks and months this book had me deep in living in an alternate reality.Two people deserve special thanks for the effort and support they have given me over the past eight
yearsespecially with respect to my career They are Stephen Kain, of the law firm Polatsek and Sclafani, and
my book agent, David Fugate, of Waterside Productions, Inc
No author can boast that he or she did a book single−handedly And no matter how much effort goes into thecreative side, without the help and dedication of editors and production people a good book can very quickly
go bad On that note, I would first like to thank the Production Editor at Osborne, Elizabeth Seymour, forgoing more than the extra mile for me Besides the hard work and commitment to the publishing task, hersupport, understanding, and tolerance (of me) are greatly appreciated
I also would like to thank my publishers and the all the production and editorial staff that helped keep this
Acknowledgments
Trang 22book on track In particular, I owe my publisher McGraw−Hill/Osborne for support and patience during thelong haul Special thanks and appreciation are due to my editor, Ann Sellers, for her commitment and support,during the approximately 18 months it took to publish this book, from conception to reality I am especiallyindebted to Ann for the opportunity she has given me in this venture.
My technical reviewers, Lou Boni and Amir Liberman, of Ziphex Consulting, Inc (www.ziphex.com), andJared Kalish all deserve a special thank you for the extra effort each made to not only read my chapters butalso to test my code I am especially indebted to my nephew, math whiz Jared Kalish, for his direct help inreviewing many of the pages I thought I had lost my way with His blunt "Am I supposed to understand whatthis means?" style of editorial critique and review is directly responsible for a lot of polish
I have received a lot of help from Microsoft over the past five or so years that I greatly appreciate I especiallyfeel a debt of gratitude to Stacey Giard (.NET Developer Support Group PM) for her commitment, and to EricFoster at Waggener Edstrom (Wagged) for the help he has given me with all my books
Acknowledgments
Trang 23Before I introduce the chapters I want to tell you what this book is not It is not a book that caters to
migrating from the earlier versions of VB to Visual Basic NET
There are several reasons for not talking about what was and what now is In many cases, the effort to migrate
is not worth your time; you might as well start from scratch Besides, you must learn the new language Also,anything written in classic VB is unlikely to carry over well from the design and architecture points of view(especially the much earlier versions of VB) While I don't know VB prior to VB 5 and 6 very well, I knowenough about the latest versions to tell you that there is a huge difference between classic VB and VisualBasic NET You will undergo a shift in psyche, from being a VB programmer to being a Visual Basic NETprogrammer You have to change the way you thinkthinking in objectsnot only change the way you writesoftware Now is a good time to rebuild your VB application from ground level and put it on a solid
object−oriented foundation
While I have made a few notes in places about the differences, it is only to reflect on interesting points andanomalies I believe that if you are an expert in "classic" VB you will know exactly where to look to find thedifferences; you'll adapt both personally and with the software with relative ease I work with VB 6 every day
I also work with VB programmers every day, some of them with one leg in VB 6 and the other in NET Wedon't run to find a book that explains the differences between interfaces and arrays, for example We get into itand find out the differences at the moment we are most disposed to encounter them
If, however, you need to understand how involved migration will be you can simply open your VB apps inVisual Studio NET and let the upgrade tool tell you what you are in for
If you are not an expert in classic VB and come from Delphi or Java, any discussion about the differences is awaste of time And if you are new to programming I strongly urge you not to dilly−dally in classic VB
because that will cause frustration when you do change to Visual Basic NET Just come on in and get started the OO water is just fine
The book you are holding aims to impart as much information as it can to allow you to become familiar withkey concepts as quickly as possible I believe in the cliché that if you give a poor person ten bucks you feedhim or her for a day, but if you give the person a fishing rod then perhaps they will go off and start a fishingfactory that turns out the world's finest lox
Once you understand the core constructs and fundamentals, like control−flow, iteration, operators, methods,and properties, and then the advanced, yet still core, object−oriented concepts like inheritance and
polymorphism, you will be ready to take on anything in Visual Basic NET
The marvel of the NET Framework is that once you have a grasp of these core concepts, using the classes andthe facilities in the base class libraries and the advanced libraries is relatively straightforward I liken it tolearning how to drive a car Once you know how to change gears, park, accelerate, and so forth, you havewhat it takes to get into any car and drive away
This became very clear to me during the writing of this book when I was assigned to create an ASP−basedapplication and decided to do it in ASP.NET instead There was no mode change or gear shift for me at all.Sure, the Web−related elements, which apply to all languages, are a different matter This book would not bedoing justice to its cause or readership if it suddenly started going into XML basics or HTML layout Theso−called code behind the Web−based application is the same code you write for standard Windows
applications and services That's the marvel of NET
Trang 24When it came to ASP.NET related code, like instantiating session objects, I found that everything I knewabout core Visual Basic applied to these ASP related constructs It was as if they were simply objects you use
in standard Windows applications
You will also not find much more than passing references about ADO.NET, GDI+, ASP.NET, and the
network libraries in this book I took this course for a number of reasons The first is that I don't consider thediscussion core reference material Giving you a book of 50 chapters averaging 20 pages a chapter, just to sayADO.NET does this and ASP.NET does that is not a book I consider any help toward achieving the
fundamental understanding of how NET and Visual Basic NET works For this reason, many of the chaptersare long and complex I have made every effort to cover the concepts as thoroughly as possible
Another reason is that once you have mastered the fundamentals, and learned to think in object semantics andthe construct syntax, you will be able to incorporate these technologies with your eyes closed This is whysome of these technologies only feature in places in the code examplesbecause they were needed in the codeexamples Once you know how to access an array and iterate through its elements, accessing a data set anditerating through its elements is practically the same thing The only difference is in one case you reference
classes at System.Array and in the latter case you reference classes at System.Data.
So sophisticated is Visual Basic NET, the common language runtime, and the NET Framework, that evencryptic and hard to understand COM or ActiveX technology melts away when wrapped inside NET I haveimported dozens of COM objects, fearing pain worse that root canal, to find myself up and running with themwithin minutes as if they were simply another bunch of NET objects
I also chewed long and hard on whether to get into reflection, garbage collection, attributes, and the like butfelt, based on my experience with Visual J++, that you'll hardly need to deal with these concepts for most ofyour applications, especially in a book that boasts core coverage You might, however, find yourself calling
on reflect methods, or trying to do something odd with the garbage collector, on very few occasions or whenyou need to start working on sophisticated applications, such as those that need to invoke methods remotelyThe same is true for threading, although I felt it important to discuss the basic concepts in a small part of thebook dealing with Windows Forms and user interfaces
Now to what this book is about It's certainly about the fundamentalsParts I and II deal with the core
constructs of the language, of Visual Basic NET, and of using Visual Studio NET By the time you are wellinto Chapter 7 you will be writing Visual Basic NET code like a pro
Part III chapters take you through higher−level concepts like inheritance, composition, encapsulation, andinterfaces The chapters progress from providing a grounding in OO concepts in Chapters 8 through 11, toadvanced OO and code construction concepts covered in the remaining chapters
I decided to exclude a glossary because there are many fine general programming books in the world thatsupply that need Apart from delegates, which have been given special coverage in this book, Visual Basic.NET and the NET Framework does not stray from the standard procedural and object−oriented programmingconcepts and constructs in any way that would require a glossary of terms and concepts
While I have designed the book to be tackled logically from the first chapter to the last, here is a brief
description of the chapters to help you pinpoint parts you may wish tackle first
Introduction
Trang 25Chapter 1
The first chapter is not so much about Visual Basic NET as it is about programming in general and
programming in NET in particular Experienced programmers will likely skim over this chapter, but
newcomers would benefit from the background to programming in general, and from finding out what VisualBasic NET and the NET Framework have to offer
The chapter takes you through ages of procedural and structured programming, and into the object−orientedparadigm We will discuss modularity, class cohesion, and related topics
The largest section in this chapter goes into what makes a pure object−oriented language It discusses theso−called "three corners of OO": inheritance, polymorphism, and encapsulation It also points out how manyconstructs, like encapsulation, are rooted in programming models, pre−OO Most important is that you'll seehow Visual Basic now fits the bill as an extremely powerful and pure OO language
The chapter covers the differences between object−oriented programming (OOP) and object−based
programming (OBD) There is also a discussion about frameworks
The concept of patterns in software development is a very important subject The subject of patterns is
introduced in this chapter Several chapters go into key structural and behavioral patterns in detail; theseinclude Composite, State, Bridge, and Singleton You will see how many patterns that have been used foryears in OO software development lay the foundations for many sophisticated technologies in NET
Delegates are a case in point
Chapter 2
It is important to get up to speed with the NET Framework and the common language runtime (CLR) as soon
as possible While it is true you can install the CLR and forget it for many applications, there are a lot ofthings you need to be aware of when it comes to how your code is executed This chapter goes into Microsoftintermediate language, how your application code gets packaged into assemblies, and how the runtime locatesand runs your code
When I first started this book I thought it would not be necessary to go into the CLR in any detail; maybe givethe subject a few paragraphs Then I tried to deploy an application for a client to the production servers, only
to discover the code was unable to run due to some obscure security condition While this chapter presents thebasics of security (the runtime environment and the CLR), the information I gained from learning about theCLR made all the difference A few tweaks here and there, and the code was up and running
You need to know about the assembly cache, side−by−side execution, the Common Language Specification,and NET security While you do not need to become a guru on all the subject matter covered in Chapter 2,you'll have the confidence to move your software off your development workstation and know what it needs
to run with in the world at large
Chapter 3
This chapter aims at making you productive with Visual Studio NET as quickly as possible The chapter hasbeen designed to have you learning important points from the get−go, so that you'll be able to have codecompiled and running before you reach the end of the chapter
Chapter 1
Trang 26You'll learn about the important features, windows, and tools in Visual Studio, and how to load the VisualStudio solution and projects that partner this book The chapter also includes a small applicationnot exactly akiller version of "hello world"but enough to get your feet wet.
Chapter 4
There's a lot of ground to cover in this book and Chapter 4 gives you the lay of the land The first part tellsyou which chapters to turn to for coverage of certain constructs It also provides information on NET codewriting style, such as whether to use Hungarian notation (which is discouraged), what should be cased incamel casing, and what should be cased in Pascal casing
The chapter also goes into the various declaration spaces and contexts of a NET program For example, it
covers the compiler options (Option Explicit, Option Strict, and Option Compare), namespace declarations
and the concept of namespaces, class characteristics, and the class members This chapter covers variables,constants, important keywords, conversion, scope, and lifetimes
Chapter 5
I got somewhat carried away with this chapter It started as a big section in Chapter 4 and then grew to a pointwhere it deserved to be its own chapter This chapter is unique for a number or reasonsnot only have I goneover every operator bit for bit, but I have also covered some stuff that is not currently in Visual Basic NET atall: operator overloading
There is a good reason for why I did this Operator overloading is important for a lot of reasons and there hasbeen quite a debate over whether Visual Basic NET, unlike C# but like Java, should have supported it Idecided to get into the subject for the sake of providing Visual Basic programmers with an understanding ofwhat operator overloading is useful for and if it is necessary to have in Visual Basic NET Once you haveread this chapter you will be able to fathom if the subject is worth pursuing with Microsoft or whether youwould prefer they spent their time on more important issues
I delved into the subject of shift operations and the shift operators in Visual Basic NET The problem youhave here is that there are no shift operators in Visual Basic Only C# has them I decided to show themanywayonly I had to write the examples in C# Surprised? You should be The C# section is important for tworeasons It shows you what you can do with shift operators (which may make you envious of C#
programmers), and at the same time it shows you how you can incorporate another NET language into a VBproject with relative ease
Do not be surprised to find a number of tables and lists in various places that include some C# items alongsidethe Visual Basic ones There are two reasons I did this First, the framework classes are written in C# so it
helps when you encounter terms like sealed and static that you know what they mean to your Visual Basic
code Second, switching out to C# to knock up something you need to incorporate in a Visual Basic
application is not to be discouraged
The chapter also looks at short−circuiting in operators It includes a section on numbering systems, which weall need to be sharp about
Chapter 4
Trang 27Chapter 6
This chapter deals exclusively with flow−control, iteration, and the conditional constructs Without thesefundamental facilities we cannot program any logic into our software We would not be able to provide choice
or make selection
The chapter covers all constructs, and touches a little on the legacy ones that I have never been enamored with
as a VB 6 programmer I found it very hard to cater to error handling with the On Error construct, and after
having coded with exception handlers for years, it was difficult getting used to the very un−object orientedway VB error handling had to be dealt with
I also got into so much trouble with Goto in my early programming days (with Dbase and the like) that I now hate this facility with a passion While I cover Goto in this chapter, I have made it clear that it is not needed in NET at all Apart from the single example of Goto in this chapter, the construct is not covered anywhere else
in the book nor is it used in any of the software projects
Chapter 7
Methods are what make your objects work They come in two flavors: functions and sub−routines The latter
is known as a Sub in Visual Basic Functions return values while Subs do not This chapter deals with
everything you need to know about methods It deals with method characteristics, parameter lists, returnvalues, pass−by−value, and pass by reference
This chapter also covers the polymorphic facilities of methods, such as overloading, overriding and
shadowing It explains the difference between static or shared methods, and instance methods, and it explainsthe purpose of abstract, virtual, and final methods
I also decided to cover several general method topics in this chapter: Recursion, and method performance andanalysis If you are up for some teeth−grinding, you can tackle some computer science in a section that
introduces O−notation and the running−time analysis of methods.
This chapter also introduces exception handling, a precursor to Chapter 11, which covers exception handlingexclusively and in much more depth
Chapter 8
Visual Basic NET and the NET Framework provide outstanding support for value types, structures or structs,and enumerated types (enumerations or enums) This chapter covers the object reference model, the differencebetween the objects that live on the stack (a more efficient region of memory), and the objects that live inheap memory
The chapter explains the concept of boxing, how objects get moved between the stack and the heap
Chapter 9
Understanding the basics of object−oriented software development is a prerequisite to comprehending themore advanced chapters This chapter covers all aspects of classes and objects, from class characteristics andhow classes are constructed and relate to each other, to how classes become objects
Chapter 6
Trang 28I also cover modeling in depth in this chapter and provide a small introduction to UML This section includes
a guide to the UML symbols used in a number of class diagrams throughout the book
The chapter also covers inheritance in detail, and explains the differences between inheritance, aggregation,and composition We investigate how to construct base classes, abstract classes, and how to decide howclasses should relate to each other The chapter also covers static classes and how to seal a class
The chapter covers everything you need to know about working with interfaces from declaration and
definition to implementation, instantiation, and bridging
Chapter 11
I consider exception−handling so important that it deserves a chapter of its own as well This chapter follows
up on the short introduction to exception handling introduced in Chapter 7 It not only covers the ins and out
of using exception handling in your code, guarding code in Try Catch Finally constructs, but also shows you
how to create custom exception handling objects
Chapter 12
Data structures and collections are where you store the data you work with in your programs They includearrays, lists, stacks, and queues This chapter is extensive and deals with the specifics of the most importantdata structures The first part of the chapter deals with declaring and using the likes of stack objects andqueues It also introduces the key interfaces that are implemented in collection classes, which provide thesupport for iteration and framework wide constructs
The chapter then delves into arrays It looks at how to fill arrays, access array elements, iterate over arrays,and how to pass arrays to methods Later in this chapter, we look at sorting and investigate how to writesorting algorithms like quicksort, bubble sort, and so on There are two motives behind the work with sortingalgorithms First, they cover important method construction issues, like method decomposition and how todivide units of work in your algorithms Second, these sections bring us down from the lofty abstractions ofobject and classes in the previous chapters In short, the chapter lets us get down to some gritty code writing
Chapter 13
Patterns are as critical to object oriented software as blueprints are to architects This chapter investigatesseveral of the most important patterns in OO These include the Singleton pattern, the Bridge and Strategypatterns (which make extensive use of interfaces), and the State pattern
Chapter 10
Trang 29The chapter specializes in the Composite pattern and looks at composition and aggregation in some detail Itcovers the creation, from design and specification, of a full−blown linked list class, that you can emulate and
incorporate in your code To iterate the list I show you how to implement the collection interfaces, IList, ICollection, and IEnumerable You will also learn how to build a collection class and an iterator for
traversing it by implementing the IEnumerator interface.
Chapter 14
If you don't understand delegates, then this is the chapter to turn to It tackles the subject of Delegate objects, Adapters and delegation head−on This subject has its roots in Visual J++ and is one that gives programmers
a lot of trouble Few constructs create as much confusion and debate as the Delegate class and how to use it.
Chapter 14 is closely tied to Chapter 13, covering patterns, and Chapter 10, which covers interfaces Apartfrom implementation inheritance discussed in Chapter 9, I believe that unless you understand polymorphism
as well as you understand your mother tongue, you will struggle with everything from services to user
interfaces to multithreaded applications I may have gone overboard on the polymorphism subject, but there is
a very good reason for it If you don't understand or know how to use or program against interfaces anddelegates, then you can't move up to the more intense and more complex technologies you need to master.And you can practically forget about getting into building controls and components, let alone how to buildsophisticated event−driven programming
This chapter also looks at the debate between using interfaces and adapter class for event−driven software vs
the Delegate We examine how Delegates are used as object−oriented function pointers While I touch on the
subject of callbacks and asynchronous programming, this chapter deals mainly with simple method pointing
It takes recursion used with the sort methods in Chapter 13 and shows how to replace it with Delegates.
Chapter 15
Manipulating data and getting data into and out of your application are other core requirements for you tomaster Chapter 15 covers string handling and I/O, and several important namespaces and classes that cater toI/O
After discussing string manipulation and regular expressions, the chapter goes into an extensive investigation
of all the file, directory, and I/O classes These include the various stream classes, and text readers and
Trang 30Many of the conventions used in this book are self−evident However, I have added a number of symbols inmany tables that differentiate between properties, methods, fields, static methods, and instance methods.These symbols are listed in the following table
A number of tables provide lists of class members These tables will give you an idea of what constructs areavailable to the class and may or may not correspond to an element further explained in the text However, inmost of the cases the tables are abridged They especially do not list the members that are always inherited
from the root Object Defer to the NET SDK for the full picture.
Chapter 17
Trang 31Part I: Introduction to Visual Basic NET
Chapter List
Chapter 1: Software Development and Visual Basic NET
Chapter 2: Visual Basic NET and the NET Framework
Trang 32Chapter 1: Software Development and Visual Basic NET
Overview
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 experience with 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 howtrue 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 introduce you to the OO conceptsthat all Visual Basic programmers need to know This chapter introduces these software developments and
OO concepts early on, to help you derive the most benefit from this book and from Visual Basic NET
We begin by reviewing the evolution of software development over the past few decades Then we shall seehow Visual Basic NEThereon referred to as Visual Basic has risen to meet the challenges of a demandingindustry, answering the world's thirst for software
Visual Basic and the Difficulty of Developing Software
Whether silicone− or carbon−based, what makes computers tick is simply the groupings of the numbers 1 and
0, combined in sequences to form instructions This is known as softwarehow 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 to communicate; to controldevices; to display, project, and render images; to model, design and manufacture widgets; to move objects; toperform highly complex computations and calculations, and so on
Software is an extremely complex science At the same time it is an art formthe software developer must becreative in designing and writing software that simulates and addresses real world scenarios Developers arerequired to do much more than just write code for complex mathematical algorithms or to simply transferinformation from point A to point B
Software development is time−consuming: The combination of both time and complexity makes it a very
costly process Unless a software engineer knows practically everything there is to know about the core
language syntax and grammar and has experience using it, a development process can rapidly expand beyond
the range of affordability "Core language" doesn't mean peripheral or collateral technologies, or libraries likethe database libraries (ADO.NET) or the Internet communications libraries, or the Web development
technologies (ASP.NET), but the foundation used to create all these collateral technologies This does notmean that these collateral technologies are not importantthey are very importantit means that you cannot hope
to use or even create the collateral technologies or components unless you first understand the foundations,processes, and facilities used to build them
Trang 33Reducing Complexity and Time−to−Market with Reuse
There have been many horror stories of how a miscalculated value caused a machine to explode, or how abank 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 software components to avoid having torewrite and retest the product We in the software industry know that software is an iterative process It is also
a refining process Without the ability to reuse what has been refined or what currently works well for the task
at hand, we will not advance as quickly as we need to in the coming decades If we had not been able to reusewhat 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 sort in 1960; it is used today in
every modern language (we will cover this algorithm in Chapter 12, "Arrays and Other Data Structures,"
along with bubble sort, and in Chapter 14 in 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
emergence of formally cataloged patterns for software design (There are also a number of algorithms that arepatented and that we can't use The sirens of the data compression wars are still ringing in many companies.)Software development has certainly changed over the past few decades The demand for reusable code, andthe ever−increasing demands on software writers to turn out better code, have resulted in improved softwaredesign and implementation techniques that facilitate today's software−engineering principles and
requirements Had not Visual Basic been adapted for the need, had it not risen to the challenge, it would havebeen replaced by something else
Software Development and Software Engineering
Software engineering is not easy to define; indeed, many argue that it is not a form of engineering at all andthat its designers are not really engineers But software developers are engineers and include in their ranksmany professionals with formal training and experience According to Webster's dictionary, "[software]engineering is the application of 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 "provides the equipment, systems,and tools to facilitate all forms of engineering practice" (this author's words) Modern software developmenthas also borrowed greatly from other related disciplines such as civil, electrical, mechanical, and structuralengineering especially in the fields of analysis, design, and construction Even the concept of patterns,
discussed later in this chapter, is borrowed from civil engineering
Note While many excellent software engineers are graduates of computer science schools, programmers with
an engineering background have the benefit of forward training in design and construction
The software industry emerged in the mid−20th century with the advent of the modern computer and hasprogressed through three distinct "ages" since then:
The Procedure−Oriented Age Procedure−oriented programming was largely concerned with
computational results rather than datathe focus being on procedures, or just code, as islands of
functionality Software systems were not organized in any meaningful structure and were merelycollections of files containing huge functions and procedures that were processed as required fordiscrete calculations Data was external to the functiona black boxand easily accessible because it was
•
Reducing Complexity and Time−to−Market with Reuse