Expert One-on-One Visual Basic 2005 Design and Development fills the gaps that these books leave sur-rounding Visual Basic development.. A good C# grammer can crank out a small applicat
Trang 1Expert One-on-One ™
Design and Development
Trang 3Expert One-on-One ™
Design and Development
Rod Stephens
Trang 4Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PAR- TICULAR PURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PRO- FESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAM- AGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS
IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks:Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, Expert One-on-One, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other coun- tries, and may not be used without written permission Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in
Trang 5Quality Control Technician
Laura Albert
Proofreading and Indexing
ConTextTechbooks
Trang 6About the Author
Rod Stephens started out as a mathematician but, while studying at MIT, discovered the joys of
pro-gramming, and has been programming professionally ever since During his career, he has worked on aneclectic assortment of applications in such fields as telephone switching, billing, repair dispatching, taxprocessing, wastewater treatment, and training for professional football players
Stephens has written 15 books that have been translated into half a dozen different languages, and morethan 200 magazine articles covering Visual Basic, Visual Basic for Applications, Delphi, and Java Hewrites three weekly newsletters (www.vb-helper.com/newsletter.html) that contain quick tips,tricks, and examples for Visual Basic developers
His popular VB Helper Web site (www.vb-helper.com) receives several million hits per month, and tains thousands of pages of tips, tricks, and example code for Visual Basic programmers, as well asexample code for this book
con-Currently, Stephens is an author, consultant, and instructor at ITT Technical Institute
Other Books by Rod Stephens
Visual Basic 2005 Programmer’s Reference ISBN: 0-7645-7198-2
Visual Basic Graphics Programming, Second Edition ISBN: 0-471-35599-2
Ready-to-Run Visual Basic Algorithms, Second Edition ISBN: 0-471-24268-3Ready-to-Run Visual Basic Code Library ISBN: 0-471-33345-X
Trang 7Thanks to Bob Elliott, Kevin Shafer, and all of the others who make producing any book possible.Thanks also to technical editor John Mueller for making sure I wasn’t putting my foot too deeply in mymouth and for helping to add extra depth to the book Visit http://www.mwt.net/~jmuellerto learn
about John’s books and to sign up for his free newsletter NET Tips, Trends & Technology eXTRA.
Trang 8Contents
Trang 14Chapter 14: Development Philosophy 391
Trang 15xviii
Trang 17xx
Trang 18Visual Basic 2005, together with the NET Framework, provides a wonderfully powerful developmentenvironment With these tools, developers can build amazingly powerful applications relatively quicklyand easily
With this power, however, comes great complexity Many books are available that discuss the VisualBasic language, and if you need to build a relatively simple application, those are generally sufficient
No books, however, address the complex issues that surround the development of more complicatedVisual Basic applications None discuss design, modeling, user-interface design, or testing for VisualBasic applications
These books also don’t cover some of the important advanced topics that don’t fit well into introductorybooks They generally don’t have the time to cover threading, reflection, advanced memory management,and printing in the depth necessary to make them useful for building really advanced applications
Expert One-on-One Visual Basic 2005 Design and Development fills the gaps that these books leave
sur-rounding Visual Basic development It explains the design activities that are necessary before VisualBasic development can begin It covers processes that occur after development (such as deployment,update management, and testing) that are essential to a successful Visual Basic project, but that are notpart of the language itself Finally, it covers advanced topics that are useful in real-world applications,but that are given little attention in other books
Why Visual Basic?
A Visual Basic programmer’s joke asks, “What’s the difference between Visual Basic NET and C#?About three months!” The implication is that Visual Basic NET syntax is easier to understand, andbuilding applications with it is faster Similarly, C# programmers have their jokes about Visual Basic,implying that C# is more powerful
In fact, Visual Basic is not a whole lot easier to use than C#, and C# is not significantly more powerful.
The basic form of the two languages is very similar, aside from a few stylistic differences A good C# grammer can crank out a small application as quickly as a Visual Basic developer can, and a good VisualBasic programmer can churn out object hierarchies and graphics code as effectively as a C# developer.What many developers forget, however, is that building a successful application goes far beyond spittingout mountains of code The code must work today, tomorrow, and for the entire life of the application.Far more important than the programming language is the way developers use the language I have seencode written in C, FORTRAN, and even assembly language that was so well structured and documentedthat practically anyone could modify the code with a minimal chance of adding obscure bugs I’ve alsoseen a 56,000-line Visual Basic project that was so poorly designed and documented that even develop-ers who had worked with the project for years could spend a week or more making a simple change,and have about a 50 percent chance of adding new bugs that would take another week or two to fix
Trang 19So, does that mean your choice of language is irrelevant? Almost, but not quite First, the developmentenvironment plays a very important role in modern application development Visual Studio providesunmatched tools for programming, debugging, and refactoring code IntelliSense makes it easier toremember what parameters a routine needs Auto-completion makes it easy to use longer, more descrip-tive variables Design-time syntax-checking highlights suspicious code as you type it XML commentsand attributes let you make classes, methods, and events even more self-documenting than ever before.All of these tools make writing effective, reliable, maintainable code in the Visual Studio languagesmuch easier than in many other languages that have less support from their development environments.Though Visual Studio provides all of these tools, it cannot force you to use them properly, and hereVisual Basic gives you a slight edge Visual Basic has always been a very descriptive language Its key-words are reasonably self-documenting and provide extra context to help you figure out what’s going
on A piece of C# or C++ code containing several nested loops inside a subroutine may end with a series
of many closing brackets There’s no extra information to help you remember what the brackets are ing You can (and should) add comments to make this obvious, but the language doesn’t force you to, somany programmers don’t bother
end-In contrast, Visual Basic ends a block of code with appropriate End Do, End If, End Sub, and otherstatements that make it obvious what type of block is ending Although you should still add comments
to indicate the purpose of the block of code that is ending, Visual Basic provides some basic annotation
by itself
Because Visual Basic is more descriptive than the other Visual Studio languages, it encourages ers to adopt a more descriptive style, too Every time you write a Forloop, you see keywords that helpconfirm the purpose and extent of the loop Visual Basic is transparent, so developers are more inclined
develop-to make their own code transparent
(The NET Framework also sets a good example by providing long, descriptive variable, class, method,and event names Class names such as SortedListand method names such as DrawRectangleare soeasy to understand that it’s easy to adopt similar habits of writing descriptive names.)
No programming language can force you to write good code But Visual Studio provides powerful toolsthat reduce barriers to writing good code They make it so easy to construct self-descriptive code thatthere’s no excuse to write dense, opaque code full of obscure, inconsistent abbreviations By performingits own chores in a self-descriptive way, Visual Basic gives you a little extra help in keeping your owncode lucid Use C# if you like, but I prefer to grab every advantage available
Who Should Read This Book
This book is intended for advanced Visual Basic programmers It assumes that you already have ence with Visual Basic 2005 and are comfortable with the language The book does not cover any languagefundamentals, and does not include any refresher material If you feel that you need more experience with
experi-Visual Basic, see my book experi-Visual Basic 2005 Programmer’s Reference (Indianapolis: Wiley, 2005).
The topics I present in this book are as advanced as possible In some cases, however, I have includedsimpler code to give background for a more advanced topic But the goal of every part of the book is toexplain advanced material that is either complex, hard to find in other places, or both
Trang 20Note that not all advanced material is complicated or difficult to understand For example, the followingstatement summarizes one of the most important concepts in this entire book:
In fact, this statement is so important that if you learn nothing else from this book, you will havereceived your money’s worth However, once you truly understand this idea (which I’ll discuss furtherlater in the book, notably in Chapter 14, “Development Philosophy”), it’s completely obvious Still, this
is an advanced concept I have never seen it written down explicitly in another book, and many ers only figure it out after years of debugging other people’s code
develop-How This Book Is Organized
This book’s chapters are grouped into four parts
Part I: Design
The chapters in this part of the book cover activities that occur before programming begins Theydescribe development and design approaches, and some useful design techniques Many programmersskimp on these phases, and later pay a huge price when their initial assumptions prove inappropriatefor the application
Chapter 1, “Language Selection,” describes some of the issues that you should consider when picking adevelopment language The book assumes you will use Visual Basic, but this chapter describes some ofthe language’s shortcomings While you may stick with Visual Basic, it’s worth understanding some ofthe language’s weak spots, and what you can do about them If you know where trouble may arise, youcan more easily cope with it In extreme cases, you may be able to move some of the more troublesomemodules into a library written in another language and call the library from your Visual Basic code.Chapter 2, “Lifecycle Methodologies,” discusses different lifecycle methodologies such as the waterfall,iterative prototyping, and staged delivery models It explains why Visual Basic is a particularly goodtool for building applications iteratively Most developers become accustomed to a particular methodol-ogy and never change Even if you know you will be using iterative prototyping to build your applica-tion, it’s worth taking the time to understand the best features of alternative approaches so that you cantry to steal the best ideas from them all
Chapter 3, “Agile Methodologies,” explains different development strategies, such as agile ment methods like extreme programming (XP), test-first development, and design by contract (DBC)
develop-It includes references to information on Microsoft’s Web sites about using Visual Studio for agile development
Chapter 4, “Object-Oriented Design,” discusses issues in object-oriented design It introduces theUniversal Modeling Language (UML) and gives some tips for designing an object-oriented system Itexplains how Visual Studio Team Suite and Visual Studio Team Architect support UML, and mentions afew other UML tools that developers can use It tells how to gain a complete understanding of an appli-cation by viewing design from different perspectives, such as user interface, document, and data per-spectives It explains how to get the greatest benefit from object-oriented ideas, such as encapsulation,polymorphism, loose coupling, and component-oriented design
Programs are written for people, not computers.
Trang 21Chapter 5, “User-Interface Design,” explains important user-interface concepts It explains the rule of
7 +/– 2 and tells how to use containers such as tab strips and scrolling controls to display large amounts
of data It discusses the merits and drawbacks of SDI and MDI applications, and examines menus, bars, and keyboard shortcuts It also explains techniques for customizing the user interface for particularusers and locales
tool-Chapter 6, “Data Storage Design,” discusses different data storage and retrieval strategies It exploresoptions such as relational databases, XML, flat text files, the System Registry, compiled in data, resourcefiles, and INI files It explains how a program can serialize and deserialize its data Note that this chapterdoes not cover relational database design in depth For example, it does not explain normalization andindexing in great detail, instead referring to other books for more information
Chapter 7, “Design Patterns,” provides an introduction to design patterns and anti-patterns in VisualBasic It explains what design patterns and anti-patterns are, describes some of the most useful, and
refers the reader to other books such as Visual Basic Design Patterns by Mark Grand and Brad Merrill
(Indianapolis: Wiley, 2005) for additional details
Part II: Meta-Development
The chapters in this part of the book discuss writing tools that are used by application developers Theseinclude add-ins that give design-time support to developers, custom controls and components that can
be placed on forms, and techniques that let the user execute scripts at run-time A good library of development tools makes later development easier and less error-prone
meta-Chapter 8, “Snippets, Macros, and Add-ins,” explains how to write add-ins for the Visual Basic 2005development environment It briefly describes code snippets and explains when it is appropriate to usethem rather than add-ins
Chapter 9, “Scripting,” explains how a program can allow the end user to write and execute scripts Ittells how to let the user execute SQL statements, VBA code, and VB NET scripts It explains how a pro-gram can expose its object model so that the user can control it with VB NET scripting This chapter alsotells how a developer can use the same scripting techniques to give an application new functionalityafter it has been compiled
Chapter 10, “Custom Controls and Components,” explains how to build custom controls It describes thethree main approaches for building custom controls: UserControl, subclassing, and from scratch Italso explains how to build a special particularly useful type of custom control called extender providers,
and includes examples of some extremely useful data validation extender providers.
Chapter 11, “Property Support,” explains how to build custom property editors for use by custom trols It also tells how to use type converters to allow editors such as the Properties window at designtime and the PropertyGridcontrol at run-time to edit complex properties of an object
con-Chapter 12, “Attributes and XML Comments,” explains useful attributes that you can use to “decorate”code These attributes make extra information available to other developers (or yourself) who use thecode later so that it is easier to use the code correctly
Trang 22Part III: Development
The chapters in this part of the book explain topics relating to the main body of the application’s opment work These chapters focus on the process of writing code, and some approaches that makewriting code more effective They do not dwell on language features and syntactic issues
devel-Chapter 13, “Documentation,” explains how a more complex project should be documented It describesthe special XML documentation comments supported by Visual Basic 2005, and provides advancedexamples that show how to use them to automatically generate documentation and help files
Chapter 14, “Development Philosophy,” explains advanced coding concepts that make development andmaintenance of complex applications easier It discusses ideas such as advanced design for testing,defensive and offensive programming, and writing code for people, not computers These ideas are par-ticularly useful in large projects with possibly changing staff because they provide context for newdevelopers moving onto a project
Chapter 15, “Coding Standards,” explains my particular set of coding standards that make reading codeeasier It explains the differences between my standards and those used by Microsoft and others Thesestandards offer a starting point for developing the rules that you decide to adopt No set of standards isperfect, but using any standard is better than not following any standard
Chapter 16, “Bug Proofing,” explains steps that developers can take to make bugs easier to find andrepair These methods are essential in large, complex applications This chapter explains shortcomings ofthe Try Catch Finallyblocks and shows how to work around them It explains how to use applica-tion-level events to catch all of an application’s errors, and discusses advanced methods that allow theprogram to record and recover from errors
Chapter 17, “Testing,” explains advanced debugging and testing techniques It explains black box, whitebox, and unusual condition testing It explains regression, routine, module, and integration testing, andtells how to estimate the quality of a project It describes the free NUnit testing tool and how it fits into atest-driven approach It also describes the unit-test support built into Visual Studio 2005 Team System.Chapter 18, “Deployment,” explains the deployment strategies available to Visual Basic 2005 applica-tions It shows how to provide extensibility by loading new modules and scripts into previously com-piled applications It also explains how to use serialization to allow backward and forward
compatibility
Part IV: Specific Techniques
The chapters in this section explain specific advanced techniques that are useful in many applications.Whereas the earlier chapters deal with general design and development issues, these chapters explainapproaches to handling particular tasks that arise on many development projects
Chapter 19, “Splash Screens,” explains how to quickly build impressive splash screens and Aboutdialogs It covers such techniques as shaped forms, rotated text, and links to Web pages While this isprobably the least advanced (but most fun) chapter in the book, you should give the topic its due Splashscreens and About dialogs are some of the first ways in which users and clients interact with an applica-tion, so they set the mood A good splash screen shows your enthusiasm for the application, and tellsyour user that you take care of the little details that make a program useful
Trang 23Chapter 20, “Printing,” explains how to print in Visual Basic NET It shows how to use the standard.NET printing techniques to wrap text across pages and flow text around objects It also describes a morenatural procedural approach to printing that is more intuitive for most developers, and lets you displayitems such as page-by-page counts that are difficult when using the standard NET printing model.Chapter 21, “Threading,” explains how to use the new threading tools provided by Visual Basic 2005.With computer hardware speeds leveling off, multi-threading is one of the best ways to improve perfor-mance of intensive applications, but it comes with its own set of risks and assumptions This chapterexplains some of the issues involved in multi-threaded applications, such as access to the user interfacethread and concurrency issues
Chapter 22, “Reflection,” explains one of the most powerful features in Visual Basic NET: reflection Itshows how a program can use reflection to learn about modules, objects, properties, and methods in itsown code, and in other assemblies It also explains how a program can use reflection to load modulesthat were written after the application was compiled
Chapter 23, “Memory Management,” explains memory-management issues It describes the garbage lector, shows how to implement and invoke Disposemethods, and how to use weak memory references
col-to improve memory management
How to Use This Book
There are two obvious approaches to using this book First, you can read it cover-to-cover That presentsthe book’s parts in their most natural order: design, meta-development, development, and specific techniques
Second, you can jump into the book to read about topics that currently interest you If you want to buildsome custom controls to perform data validation in text boxes, you can read Chapter 10, “CustomControls and Components.”
Many of the techniques described in this book are much more useful if you keep them in mind duringdevelopment It is more difficult to go back and retrofit good programming practices onto code that you
have already written For that reason, you should read relevant chapters before you need them You may
want to at least skim the entire book so that you have a good idea of what topics are covered That way,when you prepare to start a new development phase, you will know if a chapter contains informationthat you should look at more closely
What You Need to Use This Book
To read this book and understand the examples, you will need no special equipment You don’t reallyeven need Visual Basic, and many of these techniques apply to other languages as well
To use Visual Basic NET and to run the examples found on the book’s Web page, you need any puter that can reasonably run Visual Basic NET That means a reasonably modern, fast computer with
com-a lot of memory See the Visucom-al Bcom-asic NET documentcom-ation for Microsoft’s excom-act requirements com-and recommendations
Trang 24To build Visual Basic NET programs, you will also need a copy of Visual Basic NET The examplesshown here were written and tested in Visual Basic 2005 under Windows XP, but most will run with few
or no modification in earlier versions of Visual Basic NET and older operating systems Some of the grams may not run in the Vista operating system Visit the book’s Web site at www.vb-helper.com/one_on_one.htmfor updated Vista-compatible examples
pro-Much of the Visual Basic 2005 release is compatible with Visual Basic NET 2003 and earlier versions ofVisual Basic NET, so you can make many of the examples work with earlier versions of Visual Basic.NET You will not be able to load the example programs downloaded from the book’s Web site, how-ever You will need to copy and paste the significant portions of the code into your version of VisualBasic NET, and you may need to make a few changes If you get stuck, email me at RodStephens
@vb-helper.comand I’ll try to point you in the right direction
Don’t bother trying to run the examples with a pre-.NET version of Visual Basic such as Visual Basic 6.The changes between Visual Basic 6 and Visual Basic NET are huge, and many Visual Basic NET con-cepts don’t translate well into Visual Basic 6 With some experience in C#, it would be much easier totranslate programs into that language
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com The forums are a Web-based tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users The forums offer a subscription feature to email you topics of interest ofyour choosing when new posts are made to the forums Wrox authors, editors, other industry experts,and your fellow readers are present on these forums
sys-At http://p2p.wrox.com, you will find a number of different forums that will help you not only asyou read this book, but also as you develop your own applications To join the forums, just follow thesesteps:
1. Go to p2p.wrox.comand click the Register link
2. Read the terms of use and click Agree
3. Complete the required information to join, as well as any optional information you wish to vide, and click Submit
pro-4. You will receive an email with information describing how to verify your account and completethe joining process
You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post You can read sages at any time on the Web If you would like to have new messages from a particular forum emailed
mes-to you, click the “Subscribe mes-to this Forum” icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to tions about how the forum software works, as well as many common questions specific to P2P and Wroxbooks To read the FAQs, click the FAQ link on any P2P page
Trang 25The Book’s Web Site
On the book’s Web site, www.vb-helper.com/one_on_one.htm, you can do the following:
❑ Download the examples in this book
❑ Download other Visual Basic programming examples
❑ View updates and corrections
❑ Connect to the Wrox discussion group for this book
❑ Read other readers’ comments and suggestions
This book was written using Visual Basic 2005 under Windows XP The book’s Web page will includeany modifications that the examples need to run in the Vista operating system
If you have corrections or comments of your own, please send them to me at RodStephens@vb-helper.com I will do my best to keep the Web site as up-to-date as possible
Subscribe to one of my three newsletters at www.vb-helper.com/newsletter.htmlto receive weeklytips, tricks, and examples for Visual Basic programming I also announce any updates to my books in thenewsletters, so if you sign up, you’ll learn when there are updates
Trang 26Part I
Design
In this Par t:
Trang 28Language Selection
The chapters in this part of the book cover activities that occur before programming begins Theydescribe development and design approaches, and some useful design techniques Many pro-grammers skimp on these phases, and later pay a huge price when their initial assumptions proveinappropriate for the application
This chapter describes some of the issues that you should consider when picking a developmentlanguage The book assumes you will use Visual Basic, but this chapter describes some of the lan-guage’s shortcomings While you may stick with Visual Basic, it’s worth understanding some ofthe language’s weak spots and what you can do about them If you know where trouble may arise,you can more easily cope with it In extreme cases, you may be able to move some of the moretroublesome modules into a library written in another language such as C# or C++, and call thelibrary from your Visual Basic code For example, C++ and C# handle pointers more transparentlythan Visual Basic does If you need to use a library to control special-purpose hardware, it may beeasier to call that library’s routines from C++ or C#, particularly if the library was written in one ofthose languages
One of the other times I’ve found this sort of thing useful is with “unsafe” array manipulation for graphics processing A program can obtain a pointer to the memory containing an image’s pixel data A C# program can treat the pointer as a reference to an array, whereas a Visual Basic program must use API functions to copy the pointer’s memory into a new array and, after the program has finished manipulating the array, it must copy the result back to the pointer’s loca- tion If you place the graphics-processing code in a C# module and call it from Visual Basic, you can avoid these two memory copies and save some time.
Language Addiction
If you surf the Web looking for reviews of languages, you’ll find a very strong correlation betweenthe programming language a person uses and the language he or she thinks is best You can find lots of C# and C++ programmers who can tell you all about the bad points of Visual Basic,
Trang 29and plenty of Visual Basic developers who will tell you at length what’s wrong with C# and C++ Whenyou use a language extensively, that’s the one you find most natural, and anything else seems strange.
If you speak to developers who have used several languages extensively, you’ll generally get a very ferent response These developers tend to say that most languages do pretty much the same thing, just indifferent ways, and the choice isn’t that big a deal In particular, I know a lot of programmers who haveused both Visual Basic and C# for several years and they agree that the languages are practically identi-cal Many have a personal preference, but very few people with a lot of experience claim that one lan-guage is clearly superior to all others in all situations
dif-During my career, I’ve used quite a few languages, including Pascal, assembly, FORTRAN, C, C++, Delphi,PostScript (many developers don’t even know it’s a programming language), some graphics programminglanguages, various flavors of BASIC, and an assortment of Visual Basic versions such as VBA, VBScript,and Visual Basic versions 3 through 2005 Each of these languages has its strengths and weaknesses
Disadvantages
The following section describes some of the most common objections raised against Visual Basic andexplains whether these are real, significant objections; a problem that is easy to work around; or merely amatter of perception
Interpreted, Not Compiled
Visual Basic does not produce a compiled executable Instead it produces Intermediate Language (IL)code that is interpreted at run-time by the Command Language Runtime (CLR) This has a couple ofimportant consequences
First, interpreting code reduces execution speed Visual Basic uses a just-in-time (JIT) compiler so after aprogram has executed a piece of code, it should be compiled and run at faster speeds later However,running the code the first time will still be a bit slower than it will be in a truly compiled language.Second, a computer must have the CLR and the NET Framework installed to interpret the Visual Basicprogram’s IL code These not only increase the installation complexity, but they are also quite large and getting larger with each new release Whereas the Visual Basic 6 run-time libraries took about 1MB compressed, the NET Framework 2.0 needed to run Visual Basic 2005 programs weighs in at22.4MB compressed, and expands to 280MB of disk space when installed (610MB if you’re running 64-bit Windows)
Third, IL code is relatively easy to read, so even distributed as an “executable,” a Visual Basic or C#application is relatively easy to reverse-engineer Code obfuscators that rearrange code, rename variables
so they are harder to understand, and so forth are available, but the result is still easier to read than acompiled executable
Lutz Roeder’s excellent “Reflector for NET” program allows you to easily view IL code for NET
assemblies written in Visual Basic, C#, C++, IL, Delphi, and Chrome It will even display code in those
4
Trang 30languages that could have generated the IL code For example, you can load a compiled Visual Basic application and Reflector will show you C# code that is roughly equivalent This tool is also very useful for comparing the IL generated by similar pieces of Visual Basic and C# code — the results are not always the same You can download Reflector and some other useful tools at www.aisto.com/
roeder/dotnet.
How important are these objections? Programmers often focus on speed but, as I’ll argue later in thisbook, usability and correctness are more important than speed for most applications If an applicationspends most of its time waiting for user input and calling a database engine, pure CPU speed isn’t anissue With today’s fast computers and JIT compilation, speed is usually not a problem
C# uses IL just as Visual Basic does, so there’s no reason to think using C# will improve performance.
Some languages such as Delphi may give better performance because they use better compiler tion techniques Assembly can also give better performance, but only if you write good assembly code, and the difficultly is rarely worth it.
optimiza-Installing huge run-time libraries can be a serious issue If you’re developing software for use withinyour company, you may be able to require users to download a 22.4MB file that uses 280MB of diskspace when installed However, if you want to allow customers to download your program from theInternet, this may be a problem For example, a 56K modem would take almost an hour to download thefile Once customers have the run-time libraries installed, they will not need to download them forfuture Visual Basic applications, but downloading them the first time could be problematic Even withVisual Basic’s new Click-Once Deployment, it’s much easier for the user to run a self-installing Javaapplication on whatever browser he or she prefers
Finally, IL security can be a big issue for some applications Many companies are protective of their ware, and the chance of reverse-engineering has made many of them reluctant to adopt Visual Basic.NET For many applications, you can easily deduce the code from the user interface Any programmercan figure out how to make menus, dialogs, and reports Often, there is only a small part of the applica-tion that is proprietary If security is a real concern, you may be able to move that small piece of codeinto a library written in a truly compiled language such as C++
soft-When considering whether the reduced security provided by IL is a show-stopping issue, ask yourselfthese questions:
❑ How likely is it that someone will try to reverse-engineer the code?
❑ Does the program contain real proprietary information that you need to protect? Or, is most ofthe code obvious from the user interface?
❑ Can you pull the sensitive pieces out and compile them into a compiled library?
You can also use obfusticators to deter casual hackers Some of the latest obfusticators do a pretty goodjob of making the code so confusing that it will be easier for a hacker to rewrite the application fromscratch, rather than to sift through the scrambled code If you do use an obfusticator, you should also useLutz Roeder’s Reflector program to see what the resulting IL looks like If you’re not confused by theresult, a hacker won’t be either
Trang 31Language Features
Visual Basic has an intuitive, self-documenting syntax but it also has a few annoying quirks In anattempt to make every customer happy, Microsoft has left in some features and options that it probablyshould have removed These are generally syntactic annoyances and don’t cause much trouble if you areaware of them:
❑ Strict Type Checking — Type checking in Visual Basic NET is stricter than it was in Visual Basic 6,
but it’s still looser than in some other languages For example, by default, Visual Basic 2005doesn’t let you assign an Integer to a String (s = 12), but it will allow you to assign an Integer to
a Long (long_var = integer_var) Sometimes that’s what you want to do, but sometimes it’s
an indication that there’s something wrong with your design It also costs some execution time
as the value is converted from one data type to another
❑ Option Explicit — This option shouldn’t be optional, it should always be on I’ve never seen an
example where turning this option off was necessary
❑ Option Strict — This option should also always be on Unfortunately, there are very rare cases
when it’s convenient to bypass type checking and turn Option Strict off (for example, whencoercing parameters in and out of library function calls) If you must turn Option Strict off, do
so in the smallest module you can build to get the job done Use partial classes, if necessary, sothat Option Strict is on in the rest of the application
❑ IIF — Generally, an IIF statement is harder to read than a corresponding multi-line If ThenElsestatement, although I have seen cases where IIF can make a series of very simple state-ments easier to compare IIF is also less efficient than If Then Elsebecause it always evaluatesboth results even though only one is used Usually you can avoid IIF
❑ Pointers — Visual Basic uses references to refer to objects rather than actual pointers That makes
working with true pointers somewhat awkward For example, if an API routine returns apointer to a chunk of memory that contains one of several different data structures, it’s moredifficult to bully the result into the right kind of Structure type in Visual Basic than it is in lan-guages such as C++ that use pointers explicitly However, explicit use of pointers and manualmemory allocation leads to some of the most difficult kinds of bugs to find in C++ The timeswhen I’ve missed pointers have been pretty rare, so on the whole, Visual Basic is better off withreferences The Marshal class provides methods that coerce pointers from one data type toanother, so usually a Visual Basic program can produce the correct results with a little extrawork
❑ Strings — In Visual Basic, a String is more than a pointer to a series of characters in memory as it
is in C and C++ If your application performs extremely complex string manipulation, those guages may give better performance On the other hand, you can convert Strings in Visual Basicinto an array of characters, and then manipulate the entries in the array You couldn’t use C-style character pointer arithmetic, but you can use array indices
lan-❑ Garbage Collection — The garbage collection techniques used by NET take control of memory
management away from the developer The garbage collector can run at any time, and you havealmost no control over when or how it does its job You also cannot tell when an object will
finally be destroyed and its resources freed (this is called non-deterministic finalization) That
forces you to implement other methods such as the IDispose interface to allow the program tofree resources before an object is garbage-collected The garbage collector makes some of theseissues more complicated than necessary, but they should only be a real showstopper in real-timeapplications
6
Trang 32A famous story from the MIT artificial intelligence laboratory illustrates how garbage collection can hurt real-time systems A robotics application was supposed to track a thrown ball and catch it with a robot arm In one trial, the machine vision system found the ball, tracked its trajectory, calculated its future trajectory, and then stopped for garbage collection By the time garbage collection had finished and the computer moved the robot arm, the ball had hit the floor and bounced away.
❑ AndAlsoand OrElse— The AndAlsoand OrElseoperators perform logical evaluation withshort-circuiting For example, consider the statement A AndAlso B If Ais False, then there’s noreason to evaluate B, so Visual Basic doesn’t bother In the statement A And B, Visual Basic evalu-ates both Aand B, even if Ais False If Aand Bare simple Boolean values or variables, thisdoesn’t matter much If they represent time-consuming function calls, AndAlsoand OrElsecan
be much faster than Andand Or It would probably be better if Andand Orused short-circuitevaluation, because that is generally more efficient, but Microsoft left the definitions of Andand
Orthe way they were in Visual Basic 6 for backward compatibility
The only time when you would want to always evaluate Aand Bis if Aand Bwere routines that have side effects such as updating global variables or opening files Writing functions with side effects such
as these is a bad programming practice, so this shouldn’t be an issue anyway.
❑ Routine Libraries — Visual Basic doesn’t allow you to build a library that contains nothing but
functions and subroutines Instead, you must create a class library The user of the library mustmake an instance of the class, and then use the object’s methods to take action Though this cansometimes be an annoyance, it’s not too hard to live with
❑ Inline Code — Visual Basic does not allow you to include inline code written in other languages.
For example, you cannot include a small section of assembly or C# code to handle a particularlytricky or CPU-intensive task You can, however, place that code in a separate library written inanother language and call it from Visual Basic, although there will be a slight overhead in mak-ing the library call
❑ Macro Expansion — Visual Basic does not allow inline macro expansion as provided by C++ This
kind of macro expansion replaces a macro reference with a chunk of code at compile time Youcan get much the same effect by placing the code in a subroutine instead of a macro definition.This may make the code slightly less efficient, but it makes issues such as setting breakpoints inthe code much simpler
Multiple Inheritance
Some languages support multiple inheritance (where a class can inherit from more than one parent class).
For example, if you have a Vehicleclass and a Domicileclass, you could make the MotorHomeclassinherit from both to gain the properties and methods of both Vehicleand Domicile
Though it’s not too hard to come up with believable examples where multiple inheritance might makesense (MotorHome, HouseBoat, EmtFirefighter), I have yet to see a real application where that sort ofinheritance was absolutely crucial You can always implement classes such as these by using the facadedesign pattern For example, the EmtFirefighterclass would contain objects from the Emt(for “emer-gency medical technician”) and Firefighterclasses It would then delegate calls to its properties andmethods to those objects Although this would be less automatic, it would be easier to understand andwould also encourage a simpler, flatter object hierarchy
Trang 33Platform Dependencies
After you compile a Visual Basic application into IL, you use the CLR to execute the IL code Microsoftprovides support to use those libraries on Windows platforms, but, in theory, you could run on any plat-form that provides run-time support for IL
The Mono project (www.mono-project.com) is an Open Source effort to support NET applications invarious operating systems Currently, Mono lets you build and run NET applications on Windows,Unix, Linux, Solaris, and Mac OS X It also supports Java, Python, and other languages, in addition to C#and Visual Basic See the Mono Web site www.mono-project.comfor more information
Between NET’s native support on Windows and Mono, NET applications should run on the vast ity of PCs in use An application written in Java or another Web-based language can run on those operat-ing systems, and also on any other system that supports modern Web browsers, so such an applicationwould have slightly greater portability
major-Often, desktop applications built with Visual Basic provide a better user experience than those built withJava Desktop applications have fewer restrictions than Java applications, and some things that are triv-ial in Visual Basic are much more difficult in Java, particularly if the Java application needs to run in abrowser that doesn’t support the same features available on the desktop
However, there seems to be a growing feeling that “good enough is good enough” — that the restrictionsimposed by Java are worth the ability to run by simply pointing a browser at the appropriate URL
I prefer the performance and flexibility you usually get from desktop applications rather than Java, but there’s much to recommend the “good enough is good enough” philosophy When Visual Basic 3 was
released, I had spent just over a month working on a C++ application When I gave Visual Basic 3 a try,
I was able to reproduce everything I had built within that month in only four days There were some
things that Visual Basic 3 could not do that were possible in C++, but they meant extra work and were things I was willing to live without for the sake of a 75 percent reduction in development time I moved
to Visual Basic because it was good enough, so I can understand the idea that Java is good enough for
some applications.
Upgrading from Visual Basic 6
Visual Basic NET includes an upgrade wizard that converts Visual Basic 6 code into Visual Basic NET.Unfortunately, the wizard isn’t very good Microsoft claims the wizard can handle as much as 85 percent
of Visual Basic 6 code without intervention, but in practice, the results aren’t very good and a typicalapplication requires a lot of manual rewriting
However, this is still better than nothing Even if the wizard converts only a small fraction of the codecorrectly, it’s a head start that you wouldn’t get if you wanted to port a Visual Basic 6 application to C++
or Java
GUI Building
Believe it or not, the fact is that building graphical user interfaces (GUIs) in Visual Basic is so easy that itcan actually cause problems It’s extremely easy for an inexperienced developer to slap together an awk-ward interface that’s difficult for users to understand
8
Trang 34This is a problem with the developer rather than Visual Basic The development environment gives youthe tools you need to build a good or bad interface It’s up to the developer to learn how to use the toolswisely The fact that it’s more difficult to build GUIs in some other languages may force developers tospend more time on design, but that’s time you should spend no matter what language you are using.
Verbosity
Many C++ and C# developers think Visual Basic is too verbose and that code is easier to read and write
if it doesn’t include as many characters Though Visual Basic does require more typing, it is also moreself-documenting If the goal were to write programs as tersely as possible, all developers would useassembly code Only a tiny part of application development is spent actually typing code Far more time
is spent reading code and looking for bugs
In any case, Visual Studio’s excellent IntelliSense makes it unnecessary for programmers to type outmost class, variable, property, and method names in their entirety Usually, you only need to type a fewcharacters If Visual Studio can figure out what choices might match (as when you’re accessing anobject’s properties), it provides a list If you’re starting a new line, you can press Ctrl+spacebar to get alist of possible matches Then you can quickly select one without additional typing
I teach introductory Visual Basic courses where I always stress IntelliSense and, after a few weeks with the students, Ctrl+spacebar It’s particularly effective if you name controls and variables consistently.
For a text box, type txt and press Ctrl+spacebar to get a short list of the available choices After a few
weeks, the students become experts at using Ctrl+spacebar.
Power and Flexibility
Probably the silliest disadvantage to Visual Basic (but perhaps the one that has the most impact ondevelopers) is the perception that Visual Basic is less powerful than Java, C++, and C# Although thoselanguages are more difficult to learn, they are not significantly more powerful They all run on the samehardware and can all do more or less whatever the hardware supports In fact, C# and Visual Basic arepractically identical, aside from their syntactic differences
The fact that many pre-.NET Visual Basic developers were self-taught and that many came to VisualBasic via Visual Basic for Applications (VBA) makes Visual Basic seem more ordinary to many man-agers, and lends an extra mystique to Java, C++, and C#
Salaries for Java, C++, and C# programmers also tend to be higher than those of Visual Basic ers This is probably partly because of the perception that those languages are more powerful, the fact that they are more difficult, and the fact that there are far more Visual Basic developers available in the job marketplace.
develop-All of these facts sometimes lead management to prefer those languages to Visual Basic, although therereally isn’t much justification on the basis of power or flexibility
Advantages
Visual Basic does have some legitimate disadvantages, but it has many advantages as well The ing sections describe some of the most important advantages Visual Basic has over other common pro-
Trang 35Visual Basic’s syntax makes it much more self-documenting than other languages Its keywords arespelled out and easy to read Statements that close blocks such as End Doand Next employeeexplicitlytell you what block is ending — in this case a Doloop and a loop involving a variable named employee.This makes the code much easier to read than code that ends blocks with braces
The Nextstatement that ends a Forloop allows you to explicitly give the variable controlling the loop,specifying exactly which loop is ending Although you are not required to include this variable, youshould because it makes the code more self-documenting The following code shows a small example:
For i As Integer = 0 To 100
Next i
Unfortunately, you cannot similarly attach the name of the variable controlling an If Thenblock, Do
loop, or other structure That makes some sense, because these statements are often controlled byBoolean expressions rather than simple variables You can, however, include the controlling expressions
in a comment after the closing statement The following code shows how you might add comments to a
Doloop and an If Then Elseblock:
End If ‘ If num_employees <= 100 Then ElseIf <= 500 Else
As is shown in the last two comments, you don’t need to include every detail of the block; you just need
to include enough so that someone remembers the block to which the statement belongs
The NET Framework also uses nice, long, descriptive class, property, and method names, making it documenting as well That makes using the Framework easier, and provides a good example to encour-age Visual Basic developers to use similarly descriptive names
self-Prototyping and Simple Applications
It is extremely easy to build user interface prototypes with Visual Basic For many applications, you canput together a simple application in a few hours and get feedback from the customer before starting anyreally difficult development Providing a prototype quickly is far more effective than making users visu-alize what an application will look like through drawings or textual descriptions
Visual Basic is also extremely effective for building very simple applications In a matter of minutes, youcan build a basic database application that lets you add, query, update, and delete records in a database.Though you would need to spend some extra effort to make such an application bulletproof, adding val-idations, and so forth, you can quickly build prototypes or throwaway programs for your own use
10
Trang 36Visual Studio is an excellent integrated development environment (IDE) for programming and ging code IntelliSense makes it easier to correctly enter complex parameter lists Breakpoints andwatches make stepping through code easy The call stack browser lets you jump through the code to seehow pieces call each other
debug-Other languages provide their own IDEs and, though some such as Delphi’s are quite good, VisualStudio is an outstanding IDE
Language Relatives
Visual Basic is a close relative to several other languages, including the following:
❑ VBA (Visual Basic for Applications) — Used as a macro language by the Microsoft Office products
and can be used for scripting in other applications
❑ VBScript — Used in ASP applications to build interactive Web applications VBScript is very
similar to the Visual Basic language In contrast, JavaScript is more like VBScript than Java
❑ Visual Basic “Classic” — Although Visual Basic NET is different in many ways from Visual Basic 6
and earlier versions, the languages have much in common As the “Y2K problem” showed, software often lives far beyond its expected lifetime While Visual Basic NET is Microsoft’s path
of the future, legacy Visual Basic “Classic” applications will continue to need support and evendevelopment for many years to come
This makes translating code between these languages relatively easy, so applications that you write inone may be useful in others By using Visual Basic, you acquire skills and a code base that can be helpful
in building desktop, Web, and scripted applications
While the syntax details of Visual Basic and C# differ, the languages have a common enough structurethat it’s not too hard for a Visual Basic developer to read C# code Though translating C# code line-by-line into Visual Basic is not as straightforward as translating VBA code, it is relatively easy to get thegeneral idea of C# code and then rewrite it That gives Visual Basic developers another source for ideasand solutions to common problems
Garbage Collection
Although the garbage-collection scheme used by Visual Basic NET has its drawbacks, it also has someadvantages Memory allocation is often the most difficult part of C and C++ applications to debug andmaintain If you forget to free allocated memory, the application has “memory leaks” and uses more andmore of the system’s memory over time If you free the same memory twice, the memory system can crash
If you forget that you have freed a piece of memory and then later try to use it, the program may crash.The nature of these bugs often means problems are obvious only long after the program executes theincorrect code For example, suppose a program frees the memory holding an object It may be muchlater that the program tries to access that object, causing a crash Because the effects of these errors mayoccur long after their causes, these bugs can be extremely difficult to locate
Trang 37Visual Basic’s garbage collection scheme avoids all of these problems by removing your memory agement responsibility When the garbage collector runs, it frees memory that cannot be accessed by theapplication If a piece of memory such as an object reference is still usable by the program, the garbagecollector leaves it alone This prevents all of these memory-related bugs.
man-Large Talent Pool
It’s hard to find reliable data about the number of developers currently using Visual Basic At one time,Microsoft claimed there were more than 3.2 million Visual Basic 6 users (msdn.microsoft.com/isv/technology/vba/overview/default.aspx) They have also claimed more than 3.5 millionVisual Studio users (msdn.microsoft.com/vstudio/extend/vsta/default.aspx), although theydon’t specifically mention which version of Visual Studio, and 1 million Visual Basic NET users
(msdn.microsoft.com/netframework/technologyinfo/Overview/default.aspx)
Whatever the numbers, it’s clear that there are a lot of developers who use Visual Basic of one form or
another This in itself doesn’t mean Visual Basic is the best language, but it does mean that there is alarge pool of Visual Basic talent available It means there are active newsgroups and forums where youcan ask questions if you need help, and that there are plenty of developers that you can hire if you needextra hands on a project
If you only need your application to run on Windows operating systems, then Visual Basic is fine If youneed to run on other systems, you will need support for running IL code Mono may be an acceptablesolution for Unix, Linux, Solaris, and Mac OS X, and there have been rumors that Microsoft is bringingsupport for C# to the Mac OS, but support will probably be better on Windows platforms
Visual Basic does not provide multiple inheritance, so if your application architecture requires multipleinheritance, you may want to use another language I have never seen a real-world application that truly
required multiple inheritance, so if you only use it in a few places, you may be able to redesign the
appli-cation slightly to avoid it If all else fails, you can mimic multiple inheritance in limited cases by using afacade design pattern
Though Visual Basic NET is as fast as C# and is much faster than earlier versions of Visual Basic, it isstill an interpreted language, and a truly compiled language may give better performance for extremelyCPU-intensive applications Most applications are limited by factors other than CPU use, however.Many applications spend most of their time waiting for user input, database requests, network access, orfile access, and making the code itself faster may not help much If you are writing a high-performancereal-time application where every clock cycle counts, you may need to move to a truly compiled lan-guage However, for most applications, you can move selected CPU-intensive pieces of code into com-piled libraries and call them from Visual Basic when necessary
12
Trang 38Another consequence of the IL is that a Visual Basic NET application requires a 280MB run-time library.Even in today’s environment of cheap hard drives, that’s a lot of disk space More important, however, isthat downloading such a large library takes a long time That will prevent many users with only casualinterest from downloading your application from the Internet, particularly users with slower networkconnections Once customers have installed one NET application, the run-time library will already beinstalled so they won’t need to download it again However, the first installation can be painful.
Visual Basic’s interpreted nature also lets developers read IL code relatively easily That makes it muchsimpler to reverse-engineer Visual Basic or C# applications to either steal useful code or exploit weak-nesses in the code Obfusticators can make code much more difficult to read, but not as hard as trulycompiled code
Finally, many C, C++, and C# developers complain about Visual Basic’s verbosity You can reasonablyargue that this is a matter of personal preference, but I claim it’s something more Extra verbosity makesthe language more readable, and that’s absolutely crucial for debugging and maintaining any complexapplication You can add extra comments to C++ or C# code to make it more maintainable, but VisualBasic has extra help built in That leads to the most important concept in this book:
Programs are written for people, not computers.
If you were writing only for the computer, you would use 0s and 1s, or at least some form of assemblylanguage rather than a high-level language The computer doesn’t care what language you use It’s all 0sand 1s when the CPU executes it The reason you use a high-level language is to make programming,
understanding, debugging, and maintaining the code easier for people Any feature that makes the code
easier for a human to read and understand gives you an advantage that you should not lightly throwaway in the name of conciseness
Taking all of these factors into account, you need to decide whether Visual Basic is the right language foryour application Performance and capability are critical issues far less often than the ability of program-mers to write, debug, and maintain the code, so Visual Basic makes an excellent choice
Once you’ve picked a programming language, whether it is Visual Basic or something else, you’re stillnot ready to start writing code There are plenty of other tasks that you should perform before starting tobuild any non-trivial application Chapter 2, “Lifecycle Methodologies,” discusses different patterns forbringing a project through to produce a finished application The chapters after that one describe otherpre-coding design and development activities that you should study before you get down to the seriousbusiness of programming If you stint on these phases, you may start coding sooner, but you may laterpay a huge price when you need to debug and maintain the application
Trang 39Lifecycle Methodologies
An application’s lifecycle covers its entire existence, starting with a vaguely formed idea and ing through design, development, deployment, and use by customers The lifecycle may includeany number of revisions and new releases, and ends when the last copy of the application is nolonger used and the whole thing is relegated to history An application’s lifecycle may last 30 yearsand span dozens of releases and enhancements, or it may be cut short during design when devel-opers decide the application is impractical or doesn’t adequately meet customer needs
last-Whether an application is intended to last a month, a year, or indefinitely, you need to manage itslifecycle For a simple, one-use throwaway application, you may spend very little time in lifecyclemanagement For longer-lived applications, you may need to spend considerable effort to ensurethat the application moves as smoothly as possible from the idea stage to a usable product, andthat it remains usable as long as possible, or at least as long as it is needed
This chapter describes several different lifecycle methodologies that you can use to manage ent kinds of applications It discusses the strengths and weaknesses of each method, and explainswhich work best when developing in Visual Basic
differ-Lifecycle Stages
All lifecycle strategies use the same fundamental stages arranged in various ways In oneapproach, some stages may be made longer or shorter In another approach, some stages may bereduced practically to the point of non-existence, whereas others are repeated several times Often,different stages blur together with one overlapping another However, every approach uses thesame basic stages to one extent or another The following sections describe these basic stages
Trang 40Idea Formulation and Refinement
Every application begins as an idea Someone gets a notion about some program that might be useful.Sometimes the idea is only a vague notion, such as, “Wouldn’t it be great if we had a program that couldgenerate reports for us?” Other times, the idea may be fully formed from the start with the idea makerknowing exactly what the program must do
Once the basic idea is discovered, it should be discussed with others who might have different insightsinto the desired result As many people as possible should have a chance to provide input, making sug-gestions, additions, and improvements until you know pretty much what the application should do.Many different people might provide useful feedback in this stage of the lifecycle People who will even-tually use the application (the customers) know what they need to accomplish If the application willhelp with an existing process, the customers know how the process is currently performed Though theapplication doesn’t need to follow the same approach that the customers use now, it’s worthwhile exam-ining the current methods to see if they contain any useful ideas
The supervisors and managers of the final users also often have useful insights Even if these peoplewon’t use the application daily, they sometimes have a higher-level view of the environment in whichthe application will run They may be able to suggest ways to expand the scope of the application tohandle other related tasks They may also be able to restrict the scope of the idea to avoid duplicatingother efforts that may not be obvious to the end users
It is frequently useful to ask people to daydream during this phase Ask questions such as, “In an idealworld where anything is possible, what would you like the application to do?” The idea-makers maydecide they want a telepathic interface that can guess what items are in inventory at any given moment.Ideas like this one may sound outlandish to the customers, but recent innovations in radio frequencyidentification (RFID) do basically that Now is not the time to stifle creativity
Application architects, user interface designers, programmers, and developer types are often involved atthe idea formulation and refinement phase, but their participation is not necessary, and it is sometimeseven detrimental These people know which application features are easy to build and which are not In
an effort to keep the ideas realistic, they may inhibit the other idea-refiners and close down usefulavenues of exploration before their final payback is discovered Though one feature may be unrealizable,discussing it may spawn other more useful ideas It’s better to have lots of unrealistic ideas that are laterdiscarded than to miss a golden opportunity
Happy accidents are not uncommon Ice cream cones, chocolate chip cookies, the implantable pacemaker, penicillin, Post-it Notes, and Scotchgard were all invented by people trying to do something else (an ice cream seller ran out of bowls, Ruth Wakefield thought the chips would dissolve, Wilson Greatbatch was trying to make a device to record heartbeats, Alexander Fleming was studying nasal mucus but his
samples were contaminated by mold, the glue used by Post-its was an attempt to make a better adhesive tape, and Scotchgard came from efforts to improve airplane fuels).
Although you are unlikely to accidentally invent the next blockbuster three-dimensional action ture game while trying to build a better billing system, you may stumble across a better way to identify at-risk customers In a dispatch system I worked on, we added a mapping feature that let dispatchers see the routes that repair people were scheduled to follow We thought this was a minor feature, but it
adven-turned out to be the easiest way for the dispatcher to see where everyone was at the same time, so the
dispatchers used it all the time A fortunate accident.