Professional Refactoring in Visual Basic€¦ · Professional Refactoring in Visual Basic® Danijel...

30
Professional Refactoring in Visual Basic ® Danijel Arsenovski

Transcript of Professional Refactoring in Visual Basic€¦ · Professional Refactoring in Visual Basic® Danijel...

  • Professional

    Refactoring in Visual Basic®

    Danijel Arsenovski

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page iii

    File AttachmentC1.jpg

  • To Paola

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page v

  • Professional

    Refactoring in Visual Basic®

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

    Part I: Introduction to Refactoring

    Chapter 1: Refactoring: What’s All the Fuss About? . . . . . . . . . . . . . . . . . . . . 3Chapter 2: A First Taste of Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Chapter 3: Assembling a Refactoring Toolkit . . . . . . . . . . . . . . . . . . . . . . . . 59Chapter 4: Rent-a-Wheels Application Prototype . . . . . . . . . . . . . . . . . . . . . . 87

    Part II: Preliminary VB Refactorings

    Chapter 5: Chameleon Language: From Weak Static Typing to Strong Dynamic Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

    Chapter 6: Error Handling: From Legacy to Structured in a Few Easy Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

    Chapter 7: Basic Hygiene: Eliminating Dead Code, Reducing Scope, Using Explicit Imports, and Removing Unused References . . . . . 173

    Part III: Getting Started with Standard RefactoringTransformations

    Chapter 8: From Problem Domain to Code: Closing the Gap. . . . . . . . . . . . . 197Chapter 9: The Method Extraction Remedy for Duplicated Code . . . . . . . . . 219Chapter 10: Method Consolidation and Extraction Techniques . . . . . . . . . . 243

    Part IV: Advanced Refactorings

    Chapter 11: Discovering Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Chapter 12: Advanced Object-Oriented Concepts and

    Related Refactorings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Chapter 13: Code Organization on a Large Scale. . . . . . . . . . . . . . . . . . . . . 371

    Continues

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page i

  • Part V: Refactoring Applied

    Chapter 14: Refactoring to Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407Chapter 15: LINQ and Other VB 2008 Enhancements . . . . . . . . . . . . . . . . . 439Chapter 16: The Future of Legacy VB Code. . . . . . . . . . . . . . . . . . . . . . . . . 465Appendix A: Unleash Refactor!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483Appendix B: Rent-a-Wheels Prototype Internals and Intricacies . . . . . . . . . 487Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page ii

  • Professional

    Refactoring in Visual Basic®

    Danijel Arsenovski

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page iii

  • Professional Refactoring in Visual Basic®Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-17979-6Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1

    Library of Congress Cataloging-in-Publication DataArsenovski, Danijel, 1973–Professional refactoring in Visual Basic / Danijel Arsenovski.

    p. cm.Includes bibliographical references and index.ISBN 978-0-470-17979-6 (paper/website)1. Microsoft Visual BASIC. 2. Computer software—Development 3. Source code (Computer science) I. Title.QA76.76.D47A772 2008005.2'762—dc22

    2008001376No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form orby any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permittedunder Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis-sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the CopyrightClearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online athttp://www.wiley.com/go/permissions.

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-ranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim allwarranties, including without limitation warranties of fitness for a particular purpose. No warranty may becreated or extended by sales or promotional materials. The advice and strategies contained herein may not besuitable for every situation. This work is sold with the understanding that the publisher is not engaged in ren-dering legal, accounting, or other professional services. If professional assistance is required, the services of acompetent professional 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/ora potential source of further information does not mean that the author or the publisher endorses the infor-mation the organization or Website may provide or recommendations it may make. Further, readers shouldbe aware that Internet Websites listed in this work may have changed or disappeared between when thiswork was written and when it is read.

    For general information on our other products and services please contact our Customer Care Departmentwithin 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, Wrox Programmer to Programmer, and relatedtrade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in theUnited States and other countries, and may not be used without written permission. Visual Basic is a regis-tered trademark of Microsoft Corporation in the United States and/or other countries. All other trademarksare the property of their respective owners. Wiley Publishing, Inc., is not associated with any product orvendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may notbe available in electronic books.

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page iv

    www.wiley.com

  • To Paola

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page v

  • About the AuthorDanijel Arsenovski is a software developer from Santiago, Chile. Currently, he works as Product andSolutions Architect at Excelsys S.A, designing Internet banking solutions for numerous clients in the region.He started experimenting with refactoring while overhauling a huge banking system, and he hasn’t lostinterest in refactoring ever since. He pioneered the use of refactoring as a vehicle for a VB 6 code upgrade toVB .NET. Arsenovski is a contributing author for Visual Studio Magazine and Visual Systems Journal, holds aMicrosoft Certified Solution Developer (MCSD) certification, and was named Visual Basic MVP in 2005. You can reach him at [email protected], and you can take a look at his blog athttp://blog.vbrefactoring.com.

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page vi

  • Acquisitions EditorKatie Mohr

    Senior Development EditorKevin Kent

    Technical EditorDoug Holland

    Copy EditorsS. B. KleinmanMildred Sanchez

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group PublisherRichard Swadley

    Vice President and Executive PublisherJoseph B. Wikert

    Project Coordinator, CoverLynsey Stanford

    CompositorCraig James Woods, Happenstance Type-O-Rama

    ProofreaderWord One

    IndexerJohnna VanHoose Dinse

    Credits

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page vii

  • Acknowledgments

    A number of people deserve credit for helping me out in getting this book to the finish line. I am quite awarethat dealing with a first-time writer is always a challenge and probably means much more work than usual. Solet me start with my Wrox team. I want to thank Kevin Kent, my development editor, for always being there forme and for his meticulous work. He was always there with exactly the right dose of guidance. I want to thankKatie Mohr for believing in this project right from the outset. Thanks to Doug Holland, my technical editor, forproviding that all-important safety net that every technical author needs. Also thanks to Chris Webb for puttingme in contact with the right people at the right moment.

    I want to especially thank Mark Miller from Developer Express for reviewing a great portion of themanuscript and giving invaluable feedback, particularly on sections related to the Refactor! for VBadd-in. Also thanks to the rest of the Developer Express team for giving me full access to their prod-ucts and for responding to my queries.

    I want to thank Dusan Miloradovic for his review and excellent feedback. Other people that provided feed-back and made me believe I was on the right track are Dan Mabbutt, Sandeep Joshi, Anthony Williams, Rod Stephens, and others.

    Thanks to Vukan Djurovic for convincing me that there is always a better way to write some code and toDiego Dagum for his interest in my work. Finally, thanks to Milos Milosavljevic for introducing me to theworld of Visual Basic.

    79796ffirs.qxd:WroxPro 2/22/08 4:57 PM Page viii

  • Contents

    Acknowledgments viiiForeword xixIntroduction xxi

    Part I: Introduction to Refactoring 1

    Chapter 1: Refactoring: What’s All the Fuss About? 3

    A Quick Refactoring Overview 4The Refactoring Process 4A Look at the Software Situation 5

    The Refactoring Process: A Closer Look 7Using Code Smells 7Transforming the Code 8The Benefits of Refactoring 9Debunking Common Misconceptions 12

    Visual Basic and Refactoring 14Visual Basic History and Legacy Issues 14Visual Basic Evolution 14Dealing with Legacy Issues Through Refactoring 16

    Summary 16

    Chapter 2: A First Taste of Refactoring 19

    Calories Calculator Sample Application 19Calories Calculator Application 20Growing Requirements: Calculating Ideal Weight 22Growing Requirements: Persisting Patient Data 24

    Refactoring in Action 26Decomposing the BtnCalculate_Click Method 27Discovering New Classes 29Narrowing the Patient Class Interface 32Putting Conditional Logic in the Patient Class 34Creating the Patient Class Hierarchy 37

    Implementing the Persistence Functionality 43Saving the Data 44Implementing Patient-History Display Functionality 52

    Calories Calculator, Refactored Version 56Summary 58

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page ix

  • x

    Contents

    Chapter 3: Assembling a Refactoring Toolkit 59

    Using an Automated Refactoring Tool 60ReSharper from JetBrains 60Visual Assist X from Whole Tomato 61Refactor! Pro from Developer Express 61Getting Started with Refactor! 61Exploring Refactor! for the VB User Interface 63Quick Tour: Available Refactorings 67

    Unit-Testing Basics: The Testing Harness 69Why a Unit-Testing Framework? 70Your First Taste of NUnit 72Installing NUnit 72Implementing Your First Test 74The Test-Driven Approach 82Other Test Tools to Consider 83

    A Few Words about Version Control 84Summary 85

    Chapter 4: Rent-a-Wheels Application Prototype 87

    Interviewing the Client 88Interviewing the Manager 88Interviewing the Desk Receptionist 89Interviewing the Parking Lot Attendant 90Interviewing Maintenance Personnel 90

    Taking the Initial Steps in the Rent-a-Wheels Project 91Actors and Use Cases 91Vehicle States 93First Sketch of the Main Application Window 94Rent-a-Wheels Team Meeting 96

    Making the Prototype Work 96Examining the Database Model 96Examining the Visual Basic Code 99

    Fast and Furious, a VB Approach to Programming 102Database-Driven Design 102GUI-Based Application 103Event-Driven Programming 103Rapid Application Development (RAD) 104Copy-Paste as a Code Reuse Mechanism 104

    From Prototype to Delivery Through the Refactoring Process 105Summary 105

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page x

  • xi

    Contents

    Part II: Preliminary VB Refactorings 107

    Chapter 5: Chameleon Language: From Weak Static Typing to Strong Dynamic Typing 109

    Option Explicit and Option Strict, the .NET Effect 110Setting Option Explicit On in Relaxed Code 111

    Understanding the Set Option Explicit On Refactoring 112Refactoring the Rent-a-Wheels Code to Explicit Form 114

    Setting Option Strict On in Relaxed Code 115A Slightly Artificial Example of Permissive VB code 116Convoluted Use of Variables Resolved by the Definition of New Variables 119Inferring Variable Type 122Putting It All Together with Type-Conversion Functions 125Dealing with Methods, Fields, Properties, and Other Members 127Applying Set Option Strict On Refactoring to the Rent-a-Wheels Application 132

    Static Versus Dynamic Typing and Visual Basic 135Late Binding in Visual Basic 6 and Prior 136Duck Typing 136Resetting Dynamic or Static Behavior at the File Level 138Providing a Statically Typed Wrapper for Dynamic Code 138

    Activating Explicit and Strict Compiler Options 141Setting Options in the Project Properties 141Changing the Default Behavior of the Visual Basic Compiler 142Setting Options in Source Files 143Using Item Templates to Set Options 143

    Summary 145

    Chapter 6: Error Handling: From Legacy to Structured in a Few Easy Steps 147

    Legacy Error Handling Versus Structured Error Handling 148Legacy (Unstructured) Error Handling 148Structured Error Handling 150

    The Benefits of Structured Error Handling 153Structured Versus Unstructured Code 153Exceptions as Types, Not Numbers 154Error Filtering 154The Finally Block 155.NET Interoperability 155

    Replacing the On Error Construct with Try-Catch-Finally 156Understanding the When Keyword 158Refactoring Steps for Replacing On Error with Try-Catch-Finally 158Replacing the On Error Goto Label with the Try-Catch-Finally Construct 159Replacing On Error Resume Next with the Try-Catch-Finally Construct 162

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xi

  • xii

    Contents

    Replacing Error Code with Exception Type 164Replacing System Error Codes with Exception Types 166Replacing Custom Error Codes with Exception Types 168

    Error Handling in the Rent-a-Wheels Application 169Application-Level Events in VB 2009 169

    Summary 171

    Chapter 7: Basic Hygiene: Eliminating Dead Code, Reducing Scope, Using Explicit Imports, and Removing Unused References 173

    Eliminating Dead Code 174Types of Dead Code 175Common Sources of Dead Code 176

    Reducing the Scope and Access Level of Unduly Exposed Elements 179Scope and Access Level 181Common Sources of Overexposure 182Dealing with Overexposure 186

    Using Explicit Imports 187Imports Section Depicts Dependencies in Your System 188

    Removing Unused Assembly References 191Basic Hygiene in the Rent-a-Wheels Application 192Summary 193

    Part III: Getting Started with Standard RefactoringTransformations 195

    Chapter 8: From Problem Domain to Code: Closing the Gap 197

    Understanding the Problem Domain 198Step One: Gathering the Information 198Step Two: Agreeing on the Vocabulary 199Step Three: Describing the Interactions 200Step Four: Building the Prototype 201

    Naming Guidelines 201Capitalization Styles 202Simple Naming Guidelines 203Good Communication: Choosing the Right Words 204Rename Refactoring 206

    Published and Public Interfaces 208Self-Contained Applications Versus Reusable Modules 209Modifying the Public Interfaces 212Safe Rename Refactoring in Refactor! 214

    Rename and Safe Rename Refactoring in the Rent-a-Wheels Application 217Summary 218

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xii

  • xiii

    Contents

    Chapter 9: The Method Extraction Remedy for Duplicated Code 219

    Why Keep Code Encapsulated and Details Hidden? 219Information and Implementation Hiding 220Decomposing Methods 223

    Circumference Calculation — Long Method Example 223Extracting Circumference Length Calculation Code 226Extracting the Radius Calculation Code 229Extracting the “Wait for User to Close” Code 229Extracting the Read Coordinates Code 229Extract Method Refactoring in Refactor! 233

    The Duplicated Code Smell 234Sources of Duplicated Code 235Copy-Paste Programming 236

    Magic Literals 237Introduce Constant Refactoring in Refactor! 239

    Extract Method and Replace Magic Literal Refactoring in the Rent-a-Wheels Application 240Summary 240

    Chapter 10: Method Consolidation and Extraction Techniques 243

    Dealing with Temporary Variables 243Move Declaration Near Reference Refactoring 244Move Initialization to Declaration Refactoring 248Split Temporary Variable Refactoring 249Inline Temp Refactoring 253Replace Temp with Query Refactoring 256

    Method Reorganization Heuristics 258Method Reorganization and Rent-a-Wheels 259

    Removing Duplication in Rent-a-Wheels 261Magic Literals, Comments, and Event-Handling Blindness in Rent-a-Wheels 263

    Summary 267

    Part IV: Advanced Refactorings 269

    Chapter 11: Discovering Objects 271

    A Quick Object-Oriented Programming Overview 272What Are Objects Anyway? 272Encapsulation and Objects 272Encapsulate Field Refactoring in Refactor! 274Object State Retention 276

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xiii

  • xiv

    Contents

    Classes 276Object Identity 277Objects as Basic Building Blocks 278Root Object 278Object Lifetime and Garbage Collection 279Messages 280

    Designing Classes 281Classes Are Nouns, Operations Are Verbs 284Classes, Responsibilities, and Collaborators 288Entities and Relationships 297

    Discovering Hidden Classes 298Dealing with Database-Driven Design 299Moving From Procedural to Object-Oriented Design 302Keeping Domain, Presentation, and Persistence Apart 308Discovering Objects and the Rent-a-Wheels Application 313

    Summary 320

    Chapter 12: Advanced Object-Oriented Concepts and Related Refactorings 323

    Inheritance, Polymorphism, and Genericity 324Inheritance 324Polymorphism 329Genericity 332

    Inheritance Abuse and Refactoring Solutions 334Composition Mistaken for Inheritance and Other Misuses 337Refactoring for Inheritance — Print-System Illustration 342

    Making Use of Generics 360Inheritance and Generic Types in the Rent-a-Wheels Application 364

    Extracting Super 364Employing Generics 364Extract Data Objects Provider Class 365

    Summary 369

    Chapter 13: Code Organization on a Large Scale 371

    Namespaces 371Naming Guidelines and Namespace Organization 372Nested Namespaces 372Changing the Root Namespace Name 372Using Import Statements 373

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xiv

  • xv

    Contents

    Assemblies 375Binary Reuse 375Namespace Organization Guidelines 377Dependency Considerations 381

    Visual Basic Project File Structure Organization 387Move Type to File Refactoring in Refactor! 388Partial Classes 390Inherited Form 390Abstract Form Inheritance 392Delegating Abstract Form Work to a Form Helper Class 392

    Namespace Organization and Windows Forms Inheritance in Rent-a-Wheels 394Extracting Parent Administration Form through Abstract Form Helper Pattern Application 394Namespace and Assembly Reorganization 402

    Summary 403

    Part V: Refactoring Applied 405

    Chapter 14: Refactoring to Patterns 407

    Design Patterns: What’s All the Fuss About? 408Defining Design Patterns 408Classifying Patterns 409Pattern Elements 409Weighing the Benefits of Design Patterns 410Using Patterns 410

    Example Design Pattern: Abstract Factory 411Name 411Problem 411Solution 420Consequences 424

    Dependency Injection Pattern 426Problem 426Solution 428Constructor-Based vs. Property-Based Injection 429What Service Implementation to Inject 430Consequences 431Refactoring to DI 434

    Refactoring to Patterns and Rent-a-Wheels Application 434Eliminating Code That Duplicates Functionality Available in .NET Framework 434Injecting Data Classes to GUI Classes via Dependency Injection 435CRUD Persistence Pattern 437

    Summary 438

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xv

  • xvi

    Contents

    Chapter 15: LINQ and Other VB 2008 Enhancements 439

    Type Inference for Local Variables 439XML Productivity Enhancements 440

    XML Literals 440Navigating XML with XML Axis Properties 444Extract XML Literal to Resource in Refactor! 444

    Querying the Objects with LINQ 445Old Example in New Robes 448Object-Relational Mapping with LINQ to SQL 451LINQ and the Rent-a-Wheels Application 454

    Summary 464

    Chapter 16: The Future of Legacy VB Code 465

    To Migrate or Not To Migrate 466Migration Cannot Be 100 Percent Automated 467VB 6 and VB .NET Code Can Interoperate 467Migration Tools and Libraries 469

    Preliminary VB 6 Refactorings 470Breaking the Monolith 470Dealing with Conditional Compilation 472

    Putting Your Migrated Code under a Testing Harness 472Introducing a Functional Testing Harness 472Implementing a Functional Testing Harness 473

    Upgrading Your Legacy Code 477Strict Static Typing 477Moving Design from Procedural toward an Object-Oriented Paradigm 477Introducing Inheritance 478Making Use of Parameterized Constructor 479Using Generic Containers for Additional Type Safety 479Upgrading Exception Handling 481Implementing XML Comments 481Releasing Resources in .NET 482

    Summary 482

    Appendix A: Unleash Refactor! 483

    Appendix B: Rent-a-Wheels Prototype Internals and Intricacies 487

    Hand Over Button Click Event-Handling Code 487Receive Button Click Event-Handling Code 488

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xvi

  • xvii

    Contents

    Charge Button Click Event-Handling Code 488Change Branch Button Click Event-Handling Code 489To Maintenance and From Maintenance Button Click Event Code 493Administer Fleet Form 494

    Delete Button Click Event-Handling Routine 495New Button Click Event-Handling Routine 495Reload Button Click Event-Handling Routine 495Form Load Event-Handling Routine 495Administer Fleet Form Class Code: Fields 498Left Button Click Event-Handling Routine 499Save Button Click Event-Handling Routine 500

    Display Button Click Event-Handling Routine 502Summary 506

    Index 507

    79796ftoc.qxd:WroxPro 2/23/08 8:45 AM Page xvii

  • 79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xviii

  • Foreword

    “Premature optimization is the root of all evil.”

    — Sir Charles Antony Richard Hoare, a British computer scientist, later paraphrased by Donald Knuth in his book, The Art of Computer Programming

    Days ago, watching a documentary about the life of South American movie director Fabián Bielinsky, I paidparticular attention to a thought he shared during an interview. He said that, when filming scenes, it usuallyhappens that a given scene isn’t taped as the director originally assumed it would be. Sometimes that sceneis reworked until the director gets what was originally wanted, while on some other occasions it’s just leftthe way it came, as it’s considered exponentially better than the initial sketch. So he concluded that the realart of making movies is deciding wisely when to do it again and when to just take what was gotten the firsttime around.

    Surprisingly, if that is the case for making movies, coding components is very similar to taping scenes.It’s always possible to get better approaches for a given algorithm. So, with the manager hat on ourheads, we must decide when to freeze an always possible improvement for the sake of the timeline,budget, delivery due dates, and general customer satisfaction, and when to go on and get more.

    So here is where we address the need for refactoring. Let’s start by defining — informally, as the author willdo it better ahead — what that means in software industry terms: refactoring is a series of techniques andmechanisms used to improve the quality — understandability, maintainability, modularity, extensibility, andso on — of code segments by reformulating their sentences in such a way that the general behavior remainsunchanged. In other words, the behavior of the affected components shouldn’t vary as a consequence of theprocess but their quality, and hopefully their longevity, should be increased.

    Experience shows us that some portions of our code will sooner or later be candidates for refactoring,and the reasons are numerous:

    ❑ From the user side, users aren’t completely sure about the exact application they want until theysee installed and running what they asked for us originally. That’s not a joke! In the beginning,they start requiring something they envision, but vaguely, and that’s natural — I’m by no meansaccusing them. An undesirable side effect of this back and forth is that our code could start los-ing a certain degree of cohesion; its different modules may start being coupled above the accept-able levels, as a consequence of last-minute changes because of time-to-market pressure.

    ❑ From our own perspective, the development side, we don’t have a clear idea either about howcoding will look while we are modeling. As do the users, we also think we have cool ideas (or justgood ideas at the end) until we try to put some of them into practice. Failing isn’t bad. What’s bad is refusing to change our minds just to avoid admitting that what we had considered a great ideawasn’t, in fact, so easy to implement. And here, again, when time adds its pressure, delivering acomponent code the quickest we can may also harm its quality.

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xix

  • ❑ From the technology perspective, finally, there’s an invisible, somewhat omnipresent pressureto go along with industry trends. Typical examples are evolved .NET or Java APIs — AJAX,Web Services, and so on — that make former versions, or general strategies like Service-Oriented Architecture (SOA), Model-View-Controller (MVC), Object/Relational Mapping(O/R-M), and so on, obsolete. Once again, while reacting to those trends, our existing code is subject to some handling that, as time goes by, may erode its quality.

    In the meantime, the real world shows us that making an effort to improve the quality of our code is something we innately tend to do. Considering that, refactoring techniques are nothing but thehighest degree of maturity of such spontaneous attempts, reinforced with some supporting tools available out there to guarantee the success of the process.

    The good news about this is that we may apply refactoring locally, at a component or method level, therewhere we are applying any other modification; or globally, at a module or application level, assigning it a range of the project. Deciding on the right refactoring dose will depend on the quality gap to close, theremaining time, the available budget — it will always be easier to justify the application of refactoringwhere we already have to do something else than where no updates have yet to be asked for — amongother factors.

    In this book, the author will address refactoring topics from the envisioning of their benefits to the current ways of putting refactoring into practice. Danijel Arsenovski has been involved in refactoringtechniques, both in the .NET and Java platforms, since their earliest versions. He has delivered speechesat several conferences, given talks, and held workshops on this subject, and driven successful refactor-ing projects in the banking industry.

    As one of the leaders in development tools, Microsoft has been committed to delivering best-of-breedresources to the people who deal daily with coding activities and software projects as a whole. Throughits undisputably winning Visual Studio IDE, Microsoft makes refactoring an out-of-box facility just aright-click away from your code. In these pages, Danijel will show you how refactoring may be practicedin Visual Basic as easily as you do copy-paste or any other editing activities!

    I dare tell you, dear reader, that you have one of the most proven and fundamental guides on these techniques. Enjoy reading this book!

    Diego DagumTechnical Evangelist, Microsoft Corp.Kingsgate, Winter 2007

    Foreword

    xx

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xx

  • Introduction

    Thank you for choosing this book and welcome to the fabulous world of refactoring. I hope you will findthis book useful as you go about your daily programming chores, as you discuss different design solutionswith your peers, when you are getting ready to attack some obscure legacy code, and even as you are goingover some lines in your mind that are keeping you awake at night. If this is your first encounter with refac-toring, I expect this book to profoundly change the way you program and think about code. This is not aneasy task to complete, and, ultimately, you will be the judge of how successful I was.

    I adopted refactoring in a systematic manner after I read the book Refactoring: Improving the Design ofExisting Code by Martin Fowler (Addison-Wesley, 1999). This book proved to be down-to-earth practical,helping me learn some indispensable techniques that I could apply in real-life projects right away. Thebook was not based on some complex theory, nor did it contain any complex mathematical formulas. It spoke in language immediately understood by anyone writing the code. Soon after I read the book, I noticed a number of changes in the way I program:

    ❑ I was able to detect with much greater certainty problematic code and design flows.

    ❑ I was able to think of solutions for those problems and resolve them effectively through refactoring.

    ❑ When talking to my peers, I was able to argue for my decisions in a clear and concise manner.

    Finally, I stopped looking at the code as some solid structure constant in time, and started viewing it as aplastic, moldable form that I can fashion to my liking and in accordance with my needs. This provoked a fundamental change in the way I treat code. I realized that there is a way to modify code in an efficient,predictable manner and improve its design in the process.

    Soon, the word about refactoring started to spread inside the team I worked with, and I saw more andmore of my coworkers taking the book from the shelf. A few even got their own copies. I was able tospeak with them using refactoring terminology and introduce refactoring as an integral part of the soft-ware construction process. Even the management proved to be forward-looking in this respect.

    Partly because of my own interest in learning different languages and technologies, and partly because ofthe necessities that I am often presented with at my workplace, I get to work with different teams and pro-gram in different languages. I tried disseminating refactoring when working with teams that program inVisual Basic in a similar manner I did with Java or C# teams. This proved to not go that smoothly. Soon Irealized there is very little information on refactoring available for Visual Basic programmers. While mostof the refactorings can be applied in a similar manner in any object-oriented programming language, thereare some subtle differences.There is no reason why a programmer should not learn to refactor by lookingat code examples written in his language of preference.

    This inspired me to think more about refactoring in Visual Basic and finally to write this book. I amconvinced that there is a real need for such a text and that this book will be of practical use to manywho program in Visual Basic.

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxi

  • I hope this book will help you write better code faster. I hope it will increase your productivity and have a positive impact on your coding performance. I expect that as a result you will create better, moresophisticated designs. Most importantly, I hope it will ease the burden of everyday tasks and put somefun back into what we all like to do best: program some great code.

    Whom This Book Is ForThis book is intended for experienced (intermediate to advanced) Visual Basic .NET developers thatwish to be introduced to the world of refactoring. To get the most out of the book, you should have agood command of Visual Basic .NET and especially object-oriented programming in general.

    If you are a beginning programmer, you will not be able to use this book as your primary source. Thisbook will not teach you the basics of programming in Visual Basic .NET. There is no reason, however,not to get acquainted with refactoring as early in your career as possible. As you learn to program yourfirst classes, you can use this book to learn how to design them properly and how to correct any mis-takes you might have introduced into your design.

    If you are a VB 6 programmer, then you will not be able to successfully apply many of the refactoringsthat I deal with in this book because of differences between Visual Basic 6 (or previous) programminglanguages and Visual Basic .NET. In the case, however, that you are trying to upgrade your VB 6 code to VB .NET, you might find this book of great use. I have dedicated a whole chapter, the last one in thebook, to the subject of upgrading VB 6 code to .NET. The chapter itself, however, builds upon materialexposed earlier on in the book.

    You might also find this book very useful as you are making the transition as a programmer from VB 6 toVisual Basic .NET. This book exposes some of the common mistakes that newcomers from VB 6 to VB .NETmake and teaches you how to deal with those mistakes.

    This book makes no assumption on the type or domain of your application. It can be a typical web appli-cation, a web service, a framework, a component, a shopping cart application, a new Facebook widget,or a shooter game, but whatever it is, as long there is some VB code in it, you will find the techniquesexplained in this book valuable.

    Most of the refactorings I deal with in this book are standard refactorings applicable in any fully object-oriented language. This means that if you program in some other object-oriented language, for exampleC#, as long as you are familiar with VB .NET syntax and you are able to read code examples, you will beable to use and apply the information exposed in this book.

    What This Book CoversI have tried to make this book a good introduction and thorough overview of refactoring in Visual Basic.This book teaches the basic refactoring concepts:

    ❑ Code Smells

    ❑ Refactoring code transformations

    Introduction

    xxii

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxii

  • ❑ Some basic object-oriented principles

    ❑ The use of a refactoring tool that can automate the refactoring process

    The book uses a single case study, relatively large in size for a book case study, to demonstrate practical,real-life application of refactoring over a realistically large code base.

    In addition to standard refactorings applicable to any object-oriented language, this book teaches VB .NET–specific refactorings. It also demonstrates some special uses of refactoring. For example:

    ❑ Refactoring as an integral part of upgrade of VB 6 code to VB .NET

    ❑ Refactoring for upgrade of VB .NET 2005 code to VB .NET 2008

    ❑ Refactoring for implementation of design patterns

    This book contains a good number of important smells and refactorings. However, this book does notrepresent a complete refactoring catalog; because of time and space limitations, some important refactor-ings had to be excluded. For example, it does not deal with refactorings such as Simplify Conditional orReverse Conditional, already available for automation in the Refactor! add-in from Developer Express. It also does not deal with many “reverse” refactorings, like Inline Method or Inline Class.

    This book is intended first of all to be an introduction to refactoring. My experience tells me that the first problem that programmers deal with when starting out on the refactoring path is poorly structuredcode, and refactorings such as Extract Method or Extract Class deal with this problem. Their opposites,Inline Method and Inline Class refactorings, help you deal with excessively structured code. They willaid you in eliminating constructs (methods or classes, for example) that are not needed any more. Thisoften happens after extensive refactoring is applied to the code base.

    This does not mean that “reverse” refactorings are less important. The need for them is more likely to appearlater on in the refactoring acquisition, once you have already grasped the basics of refactoring. Part of thelearning process is to understand that the knowledge acquisition process never really ends. For example,with each new version of the Refactor! add-in, new refactorings are added to the battery of supported refac-torings. People invent and devise new refactorings continuously. As you become proficient in the technique,you will invent your own refactorings and might eventually decide to share them with others.

    So I invite you to go beyond this book; don’t feel limited by the refactorings listed in this book. Look for andtry to invent new refactorings. This way, you will truly master the art of continuous code improvement.

    How This Book Is StructuredBecause this is the first book that deals exclusively with refactoring in Visual Basic and will probably bethe first book on refactoring for the reader, I hope this book will fulfill more than one purpose:

    ❑ Be a thorough introduction to refactoring in Visual Basic.

    ❑ Be a thorough reference on refactoring techniques and code smells that can be consulted duringeveryday programming sessions.

    ❑ Demonstrate how refactoring techniques can be applied in a real-life situation, by means of singlecase study, the Rent-a-Wheels application, that I analyze and modify at the end of each chapterthroughout the book.

    Introduction

    xxiii

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxiii

  • In order to accomplish that, the main book narrative reads just like those of any other technical books.New concepts are introduced and elaborated in logical progression from more basic to more complex.Simplified, illustrational code examples are given for each concept. This way, you can read this book inlogical order from beginning to end. This is something that you should probably do once or twice afteryou acquire this book and open it for the first time.

    In addition to this main narrative, you will see that the book is sprinkled with so called “definition boxes” ofsmells, refactorings, and object-oriented design principles. The purpose of these definitions is to give a con-densed overview of the subject. In the case of smells for example, this definition contains heuristics on howthe smell can be discovered. In the case of refactorings, there is a section called “Mechanics” that contains aform of recipe and describes the steps you need to perform in order to execute certain refactoring effectively.You should be able to consult these during your everyday work, to remind yourself how the refactoring isperformed, how a smell is discovered, and what refactoring can be used to eliminate it, and so on.

    At the end of the majority of chapters, you will find the discussion of how refactorings, smells, and princi-ples I talked about in the chapter reflected on the case study included with the book. You can downloadthe code for the chapter and browse it as you read about what happened to the case study in the currentchapter. The purpose of the case study is to present you with a more life like application of refactoring.Often in technical books you will find a selection of code samples that have been unrealistically simplifiedin order to prove point. While this makes the examples clearer and easier for the writer to prove the point,it often means the reader will confront much more complex situations in real life, with many unexpectedobstacles appearing if certain techniques are to be applied to production code. In this book, I tried to pres-ent reader with a much more realistic scenario by means of the “Rent-a-Wheels” study case.

    The book is divided into five major parts that lead the reader from more basic to more complex conceptsin logical progression.

    ❑ Part I, “Introduction to Refactoring,” lays the foundation for the book. For example, in Chapter 1I talk about refactoring in some general terms. This chapter also dispels some common misconcep-tions about refactoring. Chapter 2 gives you a taste of refactoring in practice right away. ThenChapter 3 goes over the tools that you will find indispensable in order to automate your refactor-ing work. Chapter 4 presents you with a case study used throughout the book.

    ❑ Part II, “Preliminary VB Refactorings,” covers some preliminary refactorings such as deadcode elimination and others that will help you prepare the code for major overhaul. You dealwith some VB-only problems such as strict versus weak typing, legacy versus structured errorhandling, and so on.

    ❑ Part III, “Getting Started with Standard Refactoring Transformations,” deals with some standard,core refactorings. You learn about the importance of choosing names for your code constructs andabout the devastating effects of duplicated code. You deal with standard refactorings such asExtract Method and go into the details of code structuring on a method level.

    ❑ Part IV, “Advanced Refactorings,” talks about some more advanced refactorings that let youget the most from object-oriented capabilities of your programming environment. Good object-oriented skills are essential for this part of the book. You will learn how to discover classes, create inheritance hierarchies, and reorganize your code on a large scale.

    ❑ Part V, “Refactoring Applied,” shows you how refactoring can be successfully applied in order to reach a more specific goal. For example, you will see how refactoring can be paired with designpatterns to produce even more sophisticated design. You will see some of the new features thatcome with the Visual Studio 2008 version of VB and how refactoring can be used to get the mostout of them. Finally, you will take a look back at VB 6, a Visual Basic .NET predecessor. You willlearn how to apply refactoring in order to update your VB6 code to Visual Basic .NET.

    Introduction

    xxiv

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxiv

  • What You Need to Use This BookIn order to successfully use this book, you will need the following software:

    ❑ Visual Studio .NET 2008 — You will need at least the Professional Edition in order to be able touse the Refactor! add-in. You will still be able to debug, execute code, and perform refactoringsmanually in the free Visual Basic 2008 Express Edition. If you use Visual Studio 2005, you willalso be able to get some use out of most of the book, except for Chapter 15, which deals exclu-sively with features available in Visual Basic 9 and Visual Studio 2008 only.

    ❑ Refactor! for VB add-in from Developer Express — Download the latest version of this freeVisual Studio add-in from the Developer Express site: www.devexpress.com/vbrefactor/.

    ❑ Microsoft SQL Server — You will need this in order to run the sample case study included in thebook. This can be MS SQL Server 2000 or 2005, and the Express edition will suffice for the appli-cation that comes with this book. You can use any operating system, like Windows XP, WindowsServer 2003, or Windows Vista, that can run the software I just listed.

    ConventionsTo help you get the most from the text and keep track of what’s happening, a number of conventions areused throughout the book.

    Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

    As for styles in the text:

    ❑ New terms and important words are highlighted when introduced.

    ❑ Keyboard strokes look like this: Ctrl+A.

    ❑ File names, URLs, and code within the text look like this: persistence.properties.

    ❑ Code is presented in two different ways:

    Monofont type with no highlighting is used for most code examples.Gray highlighting is used to emphasize code that’s particularly important in thepresent context.

    ❑ Also, bold is occasionally used within code listings to emphasize parts of code.

    Boxes like this one hold important, not-to-be forgotten information that is directlyrelevant to the surrounding text. This information includes some important defini-tions you encounter throughout the book. You might also look for these definitionswhen using the book in a reference-like manner.

    Introduction

    xxv

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxv

  • Smell, Refactoring, and Object-OrientedDesign Principle Boxes

    In addition to the conventions just mentioned, throughout the course of this book you will come acrossthree other types of boxed text: Smells, Refactorings, and Object-Oriented Design Principles.

    ❑ Smells — These boxes contain condensed definitions of code smells. A code smell is an impor-tant refactoring concept, and each box contains three sections:

    ❑ Detecting the Smell — Describes some simple heuristic on how to detect the code smellin your code.

    ❑ Related Refactorings — Lists the refactorings you can use in order to eliminate the smell.

    ❑ Rationale — Explains the negative effect of the code smell in more theoretical terms.

    ❑ Refactorings — The content these boxes gives comprises the bare basics of the refactoring. Eachbox contains the following sections:

    ❑ Motivation — Explains the beneficial effect this refactoring has on code and how thedesign is improved with its application.

    ❑ Related Smells — Lists the smells this refactoring can help you eliminate.

    ❑ Mechanics — Gives a step-by-step recipe on how to perform the refactoring.

    ❑ Object-Oriented Design Principles — In these boxes I define some of the crucial object-orienteddesign principles and often use some short code samples to illustrate them.

    Index of SmellsFor ease of reference, the following table indicates what smells are included in the book and the pagenumber where the box dealing with that specific smell can be found.

    Smell Page Number

    Comments 226

    Cyclic Dependencies 384

    Data Class 286

    Database-Driven Design 288

    Dead Code 174

    Duplicated Code 235

    Error Code 154

    Event-Handling Blindness 232

    Implicit Imports 372

    Introduction

    xxvi

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxvi

  • Index of RefactoringsThe following table indicates what refactorings are included in the book and the page number where thebox dealing with that specific refactoring can be found.

    Continued

    Refactoring Page Number

    Break Monolith 471

    Smell Page Number

    Implicit Narrowing Conversions 125

    Implicit Type Declaration 118

    Implicit Variable Declaration 113

    Large Class 298

    Large Namespace 377

    Legacy (Unstructured Error Handling) 153

    Long Method 225

    Magic Literals 236

    Monolithic Application 470

    Non-Coherent Namespace 378

    Overburdened Temporary Variable 249

    Overexposure 179

    Procedural Design 302

    Refused Bequest 337

    Superfluous Temporary Variable 254

    Unrevealing Names 201

    Unused References 191

    Using Fully-Qualified Names Outside Imports Section 188

    XML String Literals 441

    Introduction

    xxvii

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxvii

  • Refactoring Page Number

    Convert Procedural Design to Objects 307

    Eliminate Dead Code 176

    Encapsulate Field 275

    Explicit Imports 374

    Extract Class 281

    Extract Interface 346

    Extract Method 221

    Extract Namespace 382

    Extract Super Class 352

    Inline Temp 254

    Move Class to Namespace 380

    Move Declaration Near Reference 245

    Move Element to a More Enclosing Region 185

    Move Field 291

    Move Initialization to Declaration 248

    Move Method 289

    Move Type to File 388

    Pull Up Method 357

    Reduce Access Level 182

    Remove Unused References 192

    Rename 206

    Replace Complex VB Queries with LINQ 447

    Replace Error Code with Exception Type 164

    Replace Fully-Qualified Names with Explicit Imports 188

    Introduction

    xxviii

    79796flast.qxd:WroxPro 2/25/08 9:23 AM Page xxviii