Mua he 2009-2010

Thứ Sáu, 30 tháng 7, 2010

"Well, at Least It Compiled OK!"


The Value of Software Testing

JON PERKINS
Jon is a TMS Associate who has been developing applications with Visual Basic since version 1. He specializes in writing three-tier, client/server applications with Visual Basic and Microsoft SQL Server. He is also a Microsoft Certified Solution Developer and writes a regular Visual Basic column for EXE, a British software development magazine. His interests include New Age philosophy, jazz, opera, reading, cooking, and gardening. Jon and his wife, Alison, live in the Herefordshire countryside with their two cats, Solomon and Micha.
In the previous version of this book I made the rather bold statement, "It is my belief that software development is one of the most complex tasks that human beings are called upon to perform." This assertion led to comments like, "What about people who design nuclear reactors, or the space shuttle?". Sure, there might be a lot of tasks on a list above "Write Software," but we could argue that "Write Quality Software" should be high up on the list, too. Quality consists of many attributes, the most important being that a piece of software should perform exactly as designed. In this chapter, I will cover several ways to test Visual Basic code that illustrate this key concept: testing should be planned before code is written, and all code should be written with testing in mind.
Software development projects come in all shapes and sizes, and they also vary in their nature. In terms of business applications, a standalone telephone directory system for a medium-sized company probably exists at the "relatively simple" end of the spectrum. With an underlying Microsoft Access database and a few data-bound controls, it doesn't take much effort to put together, and because of the extensive use of pretested components it probably wouldn't be too challenging in terms of testing, either. However, at the other end of the spectrum might be a major banking application that facilitates the processing of all branch-level account activity using a remote ActiveX server set via a local Microsoft SQL Server database, and then synchronizes each local set of data with the central bank's DB2 database. A system of this size is a much larger development effort that therefore requires a more thorough and comprehensive planning and design exercise, and the result is of course a greater amount of source code. The implications of a failure in the code could result in a loss of money for the bank, and this in turn leads to a loss of credibility in the business community. It is therefore imperative that the system works as expected.
Another example, perhaps closer to home for many of us, is the forthcoming Microsoft Windows NT 5. Back in the days when Windows NT existed as version 3.51, it had about 5 million lines of code. The last released version of Windows NT 4 Server was the Microsoft Enterprise Edition, which included Microsoft Internet Information Server, Microsoft Message Queue Server, and Microsoft Transaction Server (all now considered to be part of the base platform), and contained 16 million lines of code in all. At the time of this writing (April 1998) it is estimated that the final gold release of Windows NT 5 will have about 31 million lines of code. This new code also includes some fairly radical alterations to the existing technology (most notably the inclusion of Active Directory services). With so much code, the testing effort will be massive. In this particular case the 400 or so programmers are joined by another 400 testers, providing a ratio of one tester for every developer. The overall team also has around 100 program managers and an additional 250 people on internationalization.
Although software development has formal guidelines that lay down techniques for drawing up logic tables, state tables, flow charts, and the like, the commercial pressures that are frequently placed on a development team often mean that a system must be ready by a certain date no matter what. Some people might choose to argue with this observation, but it happens nevertheless. One of the biggest headaches for a software developer is time—or rather, the lack of it. When your project lead sits you down and asks you to estimate the amount of time that it will take to code up an application from a design specification that he or she has given you, it is difficult to know beforehand what problems will arise during the project. You are also faced with a bit of a dilemma between giving yourself enough time to code it and not wanting to look bad because you think that the project might take longer than the project lead thinks it will. The logical part of your mind cuts in and tells you not to worry because it all looks straightforward. However, as the development cycle proceeds and the usual crop of interruptions comes and goes, you find that you are running short of time. The pressure is on for you to produce visible deliverables, so the quality aspect tends to get overlooked in the race to hit the deadline. Code is written, executed once to check that it runs correctly, and you're on to the next bit. Then, eventually, the development phase nears its end—you're a bit late, but that's because of (insert one of any number of reasons here)—and you have two weeks of testing to do before the users get it. The first week of the two-week test period is taken up with fixing a few obvious bugs and meeting with both the users and technical support over the implementation plan. At the beginning of the second week, you start to write your test plan, and you realize that there just isn't time to do it justice. The users, however, raise the alarm that there are bugs and so the implementation date is pushed back by a month while the problems are sorted out. When it finally goes live you get transferred onto another project but quietly spend the next fortnight trying to get the documentation done before anyone notices.
I dread to think how many systems have been developed under these conditions. I'm not saying that all development projects are like this, and the problems are slightly different when there is a team of developers involved rather than an individual, but it's an easy trap to fall into. The scenario I've described indicates several problems, most notably poor project management. Even more detrimental to the quality of the final deliverable, however, is the lack of coordinated testing. The reason I so strongly tie in testing with the project management function is that a developer who is behind schedule will often ditch the testing to get more code written. This is human nature, and discipline is required (preferably from the developer) to follow the project plan properly rather than give in to deadline urgency. It is very important to report any slippage that occurs rather than cover it up and try to fit in the extra work. The discipline I'm referring to involves writing a proper test plan beforehand and then striving to write code that can be easily tested. The project management process should ensure that the creation of the test suite is also proceeding along with the actual development. I've seen projects fall woefully behind schedule and be very buggy because of poor project managers working with relatively good developers. If, among a team of developers, there is one poor developer, the rest of the team will probably make up for it. However, if the project manager is poor at performing the job, the effect on the project can be disastrous, often because of resultant low morale.
Software projects often run into trouble, more so when they are team developments. The industry average for software development projects is that typically about four in every five overrun their planned time scales and budgets, and less than half actually deliver everything that they are supposed to. In the fight to deliver a bug-free system as quickly as possible, project managers often end up negotiating with the end users for a reduction in functionality so that the developers can concentrate on the key parts of the system. The remaining functionality is often promised for delivery in the next version.
In this chapter, I'll start by covering the formalities—that is, descriptions of the various phases of testing that a well-managed development project undergoes. I'll then outline a few tips that I think will help with the testing of a Visual Basic program, and I'll finish up with a discussion of test environments. I've also included a few Microsoft Word 97 Quality Tracking templates on the CD that accompanies this book. Although most companies will have their own in-house versions of these templates, I've included them as starting points for people who do not already use them. The usage of each form should be self-explanatory because of its filename. The files are called:
BUILD LOG.DOT
BUILD REPORT.DOT
END USER FEEDBACK LOG.DOT
END USER FEEDBACK REPORT.DOT
TEST FAILURE LOG.DOT
TEST FAILURE REPORT.DOT
Notice that I have kept these templates generic—different businesses have different requirements and audit standards, so the templates can be modified as necessary. To install them on your machine, create a new directory called TMS under the Templates subdirectory in your Microsoft Office installation, and then copy the files to this location. Now start up Microsoft Word, and select the New command from the File menu. The templates should appear under the TMS tab of the New dialog box.
It's very easy to think of the debugging process as being synonymous with the testing process. Certainly, the distinction between the two processes blurs on small systems at the unit testing stage (to be defined a bit later). Other chapters in this book cover the debugging side of the software development process, which should allow the distinction to become more apparent.

Visual Basic Programmer's Guide to Successful Dating


How Does Y2K Affect Visual Basic?

STEVE OVERALL
Steve has played a major part over the past couple of years in The Mandelbrot Set's drive to raise awareness of the Year 2000 issue for Visual Basic developers. He has had articles published on the subject in both the Visual Basic Programmers Journal and, in Europe, the Microsoft Developer Network Journal. He lives in leafy Surrey with the mysterious "M," his record collection, and his plants. He fully intends to be in no fit state to be aware of any problems when the clocks strike midnight on December 31, 1999.
Hands up—how many of you have heard of the "Millennium Bug" or "Year 2000 Problem" or whatever else it has been called over the last few years? If any of you didn't raise your hands, you are either not open to suggestion or you are new to this planet. Welcome! We call it Earth.
Much has been written about this subject over the past few years. While there is a great wealth of information, most of it is aimed at the COBOL community, and what isn't tends to be very generic—limited to management guides and theoretical discussions. What I want to do in this chapter is simply look at the issue from a practical perspective, focusing on its particular relevance to Visual Basic. I will look at how Visual Basic stores and manipulates date information and, equally important, what its weaknesses are.
For me the issue is not so much what happens when the clocks strike midnight on a certain night in December 1999, but that many developers still do not fully understand how our language deals with this simple piece of data!

Minutiae

Some Stuff About Visual Basic
PETER J. MORRIS
In addition to being a "doer," Peet also thinks and talks about writing code and is a frequent speaker at international conferences, such as VBITS and Microsoft's DevCon and TechEd. This book is Peet's second foray into the world of book writing—his first occurred about the time he was working at Microsoft when he wrote Windows: Advanced Programming and Design (now as rare as duck's teeth), which was a pure API, C, and Assembler SDK book.
As you can probably guess from its title, this chapter is going to cover a rather broad range of information about Visual Basic. Think of this chapter as a Visual Basic programmer's smorgasbord. You'll learn about such topics as the advantages and disadvantages of compiling to p-code and native code. You'll get some hints on how to optimize your applications beyond just writing excellent code. And you'll also receive up-to-the-minute information on such scintillating subjects as types and type libraries. So let's begin!

Staying in Control


Effective Weapons in the War Against Bugs

MARK PEARCE
Mark is a TMS Associate who has been programming professionally for the past 19 years, working mainly in the investment banking industry. In recent years, Mark has concentrated on the design and development of effective client/server systems. His interest in zero-defect software comes from a previous incarnation as a professional chess player, where one mistake can lose you your next meal. Mark's current ambitions include making more money than he spends, not ever learning any flavor of Java, and finding the perfect mountain running trail.
"At least one statement in this chapter is wrong (but it may be this one)."
Peter Van Der Linden (paraphrased)
Program bugs are highly ecological because program code is a renewable resource. If you fix a bug, another will grow in its place. And if you cut down that bug, yet another will emerge; only this one will be a mutation with long, poisonous tentacles and revenge in its heart, and it will sit there deep in your program, cackling and making elaborate plans for the most terrible time to strike.
Every week seems to bring Visual Basic developers more powerful but also more complex language features, custom controls, APIs, tools, and operating systems. While Visual Basic 5 finally brought us a "grown-up" language with real enterprise pretensions, Visual Basic 6 arrives only a year later, along with a whole new raft of acronyms and concepts. The phrase "technological downpour," coined by a Microsoft executive, strikes a chord with both developers and their managers. In the midst of all this technological chaos, the deadlines become tougher and our tools often refuse to cooperate with one another. If whatever we build lasts at least until we've finished building it, we consider it an unexpected bonus. Yet we are expected to sculpt stable Microsoft Visual Basic code that gives our users more flexible, less costly, and easier-to-use systems.
From this chapter's point of view, the key word is "stable." It's no use being able to churn out ever larger and more capable systems with these new, improved, wash-whiter-than-white tools if all that we succeed in doing is producing more defects. Developers tend to take a casual attitude toward bugs. They know them intimately, including their origin and even their species. A typical programmer looks at bugs in the same manner as an Amazonian tribe member looks at the insect-infested jungle—as an inevitable fact of life. The typical user is more like a tourist from the big city stranded in the same jungle. Surrounded by hordes of disgustingly hairy creepy-crawlies with too many legs and a nasty habit of appearing in the most unexpected places, the user often becomes upset—which is hardly surprising. This different perspective is one that software developers need to consider if they expect to meet user expectations.

Developing Applications in Windows CE


My Two CEnts Worth

CHRIS DE BELLOT
During his career, Chris, a TMS Developer, has worked on a number of diverse applications. Chris has a great deal of experience in the three-tier client/server arena and is experienced in object design in Microsoft Visual Basic. A key member of the TMS team, Chris is highly respected for his knowledge, opinions, and experience in the design of user interface code, in particular the design of structured and reusable code, at both the code and business level. Chris is a Microsoft Certified Professional. In his spare time, Chris is a keen commercial aviation enthusiast and enjoys nothing more than landing 747s at London Heathrow's runway 27L using one of his many flight simulators.
I grabbed a beer and settled back down in front of a screen full of Visual Basic code. I'd been working on a killer app and had a few bugs left to find. Behind the project window I could see the news just starting. "Better stop," I thought, "and catch up on what's going on in the world."
My computer is connected to the television, which has a 29-inch screen. It's great for coding because I've finally got enough space for all my windows, and I have the benefit of being able to watch the TV at the same time. This, I tell myself, helps me to concentrate! Since Microsoft Windows CE took off in a big way, a whole load of new appliances have appeared on the market all incorporating Windows CE technology. My TV is just one example. Windows CE has the ability to address quite a few gigabytes of memory and the manufacturers have taken advantage of this by putting video memory in the actual television set; the 3-D video card is also built in. This means that I don't have to have these components stuffed into my PC. The processor and other components are still inside the PC case—the TV is just an I/O device that happens to have a large screen, plenty of RAM, and loads of disk space. The latter comes in handy when I use the Internet functionality built into the Windows CE operating system.
I have lots of other Windows CE devices—a stereo, an intelligent oven that can be programmed with menus on a CD-ROM. But my favorite device is my radio alarm clock. I'm really bad at getting up in the morning, and this little gadget lets me program any sequence of events, such as turning the radio on for half an hour, then chiming every 20 minutes until I get fed up and finally get out of bed. All of this was possible using conventional technology, but when Windows CE came out, the common platform was a real incentive for manufacturers to make all those devices that were perhaps too expensive to justify building before. After all, who in their right mind would take on developing a stereo with speech recognition? Oh well, it's getting a bit late now. I think I'll try out the roast lamb program in my programmable oven. It's just a shame the oven can't prepare the ingredients as well!
OK, so I don't really use my TV as a computer screen and I don't have all those gadgets—I just made it all up. But I do predict that in five years these sorts of gadgets will be commonplace. Windows CE has the potential to create a market in which affordable electronic devices can be built to cater to any need (well, almost!), so watch this space.

Programming With Variants

JON BURN
Jon has been programming with Microsoft Windows since the mid-1980s. Originally working with C, he now uses Visual Basic for all his programming tasks. He has worked on retail software, such as the PagePlus DTP package, and a lot of other custom software in the corporate environment. Jon has also taught programming and written various articles about it. He is currently working on graphics software for business presentations.Microsoft Visual Basic 6 further enhances the Variant data type from the previous version so that it can now hold user-defined types (UDTs). This creates yet another reason why you should become familiar with Variants and what they can do. In this chapter I will take an in-depth look at Variants and discuss the benefits and pitfalls of programming with them.

IIS This a Template I See Before Me?


Developing Web Applications

ROGER SEWELL
Roger's origins in programming lie in a small room in a Leicestershire school, where he spent many a happy hour punching out tape on a teletype terminal before connecting to a mainframe via an acoustic coupler modem and finding that his program didn't work. Between then and the start of his Visual basic programming career, he spent his time in the murky world of mainframes bashing out Fortran programs for scientists. Roger first saw the VB light in early 1994 and hasn't looked back since. Roger lives in Oxfordshire with his wife Kath and their young family. When not playing or watching sports Roger fights a losing battle against the jungle growing around the house.
When I first fired up Microsoft Visual Basic 5 (yes, I did say Visual Basic 5), I was surprised to be presented with a box asking me what type of project I wanted to develop. I was even more surprised to find that there were nine project templates to choose from—who would have thought that little old Visual Basic would grow into such a multitalented individual? Since that day I have become accustomed to the variety of development options given to us by Visual Basic, and now Visual Basic 6 offers us three new templates: Data Project, IIS Application, and DHTML Application.
I'll examine the IIS Application in this chapter, going through the process of developing a simple application for Internet Information Server (just in case you hadn't worked out the acronym).
This template and the new features embodied in it are intended to give Visual Basic developers the opportunity to develop Web applications without leaving (too often) the environment they know so well. I hope I'll be able to give you a feel for the development process, because it is different from the process of a normal Visual Basic project. I also want to get you thinking differently about how your application should be structured and how your users will interact with your application, because these design issues are probably the biggest change that you as a developer of a Web application (many such applications, I hope) are going to face.

Foreword

Since its inception in 1991, Microsoft Visual Basic has revolutionized the way developers create applications for Microsoft Windows. Through features such as IntelliSense, statement completion, ActiveX Control creation, a native code compiler, and database access, Microsoft has worked hard to keep developers well-equipped with the latest innovations in rapid application development. In Visual Basic 6 Professional and Enterprise Editions, Visual Basic has been expanded to make developers even more productive in what they do most often—access data, whether in a relational database (such as Microsoft SQL Server 7 or Oracle 8) or in a nonrelational data store (such as a directory service). Recognizing a rapid upsurgence in the adoption of the Web as a true cross-platform application environment, Microsoft has added new technologies to support client (Dynamic HTML) and server (WebClasses). These new features, along with literally hundreds of other enhancements and optimizations, bring the development of enterprise-wide, line-of-business applications within the reach of millions of developers who have mastered Visual Basic. In addition, these features provide the power and performance needed to create applications that run in mission-critical scenarios.
The Mandelbrot Set (International) Limited (TMS) is one of the companies that I see pushing the limits of Visual Basic most frequently. TMS is recognized worldwide as a leader in Visual Basic consulting and development. I've worked with TMS for some time now, and I've seen in their technical papers, books, and presentations that they are able to bestow a level of technical clarity not often seen in this industry. About once or twice a month, I'll get questions or insights from Peet Morris (the technical director of TMS) that are so advanced they rival the understanding of the product normally seen only by the chief architects of the product itself.
I first met Peet Morris at VBITS in San Francisco just about a year ago. I attended Peet's session and was immediately taken with his technical skill and knew that he would be an invaluable resource in the future. We immediately hit it off both technically and personally, and since then he's done sessions for us at conferences such as Microsoft TechEd this past summer in New Orleans. Peet's sessions were consistently among the most highly rated for their technical content. I eagerly anticipate Peet's visits to Redmond, where we talk about going out for a pint of Guinness but instead end up doing something trivial, such as watching the last episode of Seinfeld with friends while discussing the intricacies of Visual Basic's threading model or subclassing of date functions.
Understand that this book is not your canonical, learn-to-become-a-professional-programmer-in-x -days text. It's also not designed to provide you with a laundry list of all the new features of Visual Basic 6. This book is intended for the working professional, thus exploring in depth many of the topics that beginning books either ignore or gloss over. Drawing on the many and varied strengths of the experts at TMS, each chapter drills down into topics that are not often considered carefully in the course of day-to-day project development. The lessons learned from this book are the gems that one might unearth at a VBITS conference or in a technical course outside the classroom and away from the podium, where developers gain insight through open dialogue.
Life on the edge takes a lot of work and talent, and TMS has often had to learn the "how" the hard way. This book is your chance to benefit from their combined experience. If you're working with Visual Basic and trying to push the envelope, you'll find a lot of useful information here.
Sean P. AlexanderLead Technical Product Manager, Visual Basic Developer Tools DivisionMicrosoft Corporation

Taking Care of Business (Objects)


ADAM MAGEE
Adam Magee is a software developer who specializes in building enterprise applications. He has worked with many large companies in the United Kingdom and in Australia, helping them to implement tiered architecture solutions. His particular focus is on the design and process of building efficient, high performance, distributable business objects. Some developers would like to see Adam in a deep gully position but he prefers it at backward square leg.
Taking care of business every dayTaking care of business every wayI've been taking care of business, it's all mineTaking care of business and working overtimeWork out!
"Taking Care of Business"
by Bachmann Turner Overdrive
Business objects are big news. Everyone says the key to building distributed enterprise applications is business objects. Lots of 'em.
Business objects are cool and funky—we need business objects! You need business objects! Everyone needs business objects!
This chapter presents a design pattern for developing solid, scalable, robust business objects, designed for (and from) real-life distributed enterprise applications.
The architecture we propose at The Mandelbrot Set (International) Limited (TMS) for building distributed business object-based applications breaks down into various layers of functionality.
The data access layer (DAL) is the layer that talks to the data source. The interface of this layer should be the same regardless of the type of data source being accessed.
The business object layer is the actual layer that models the entities within your application—the real data, such as Employees, Projects, Departments, and so forth. In Unified Modeling Language (UML) parlance, these are called entity objects.
The action object layer represents the processes that occur on the business objects: these processes are determined by the application requirements. In UML, these action object layers are called control objects.
The client application layer, such as a Microsoft Visual Basic form, an ActiveX document, or an Active Server Page (ASP) on a Web server, is known as an interface object in UML.
This chapter concentrates on the middle business object layer and introduces the concepts of action objects, factory objects, and worker objects.

On Error GoTo Hell

A Methodical Approach to Error Handling
PETER J. MORRIS

Peet is the Technical Director and a cofounder of The Mandelbrot Set (International) Limited (TMS). Peet, a former Microsoft employee, is acknowledged industry-wide as a Microsoft Windows and Visual Basic expert and is a frequent speaker at events such as VBITS and TechEd. As a developer and lecturer, he has taught Windows (SDK) API, Advanced Windows API, Visual Basic (all levels), OS/2 Presentation Manager, C, C++, Advanced C and C++, Pascal, compiler theory, OWL, Smalltalk, and CommonView.

Since the first edition of this book was released, this chapter has been tidied up a little. I've added some new rules and sidebars about handling errors in components and controls, as well as some examples of handling errors on a server.

What is an error? The short answer is, "Something that's expensive to fix." Dealing with errors is costly in terms of both money and time. As you probably know already, your test cycle will be longer, more complex, and less effective if you don't build appropriate error handling into your code right from the start. You should do all you can to reduce and handle errors in order to reduce costs, deliver quality code, and keep to schedules.

One way to eradicate errors—a way that I'll dismiss immediately—is to write error-free code. I don't think it's possible to write such pristine code. A more realistic way to deal with errors effectively is to plan for them properly so that when they do occur:


The application doesn't crash.

The error's root cause (and thus cure) is relatively easy to determine.

The error is as acceptable and as invisible to the user as is humanly possible.
So what must we do to put a good error handling scheme in place? It's a deceptively simple question with a big (subjective) set of answers. I think that acquiring and then using some fundamental knowledge is where we should start:


Ensure that all your developers truly understand how Visual Basic raises and then dispatches and handles errors.

Make sure that those same developers understand the consequences of writing code that is hard to debug and the true costs of any unhandled error.

Develop a suitable error handling strategy that's based on your understanding of the preceding two points and that takes into account your budget and line of business.

Apply your strategy; demand self-discipline and team discipline.
Handling errors properly in Visual Basic is also a good idea because of the alternative: Visual Basic's default error handling rules are rather severe. Unhandled errors are reported, and then an End statement is executed. Keep in mind that an End statement stops your application dead—no form QueryUnload or Unload events, no class Terminate events, not much of anything in fact.

To help you develop an effective strategy for dealing with errors, I'll go over some ideas that I consider vital to the process. These are presented (in no particular order) as a series of tips. "Pick 'n mix" those you think will suit you, your company, and of course your development project. Each tip is empirical, and we have employed them in the code we write at The Mandelbrot Set (International) Limited (TMS). I hope they serve you as well as they have served us!