ebook img

Professional refactoring in Visual Basic PDF

527 Pages·2008·4.028 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Professional refactoring in Visual Basic

Arsenovski ffirs.tex V3-03/20/2009 9:12am Pageiii Professional Refactoring in C# & ASP.NET Danijel Arsenovski WileyPublishing,Inc. Arsenovski ffirs.tex V3-03/20/2009 9:12am Pageiv Professional Refactoring in C# & ASP.NET Publishedby WileyPublishing,Inc. 10475CrosspointBoulevard Indianapolis,IN46256 www.wiley.com Copyright©2009byWileyPublishing,Inc.,Indianapolis,Indiana PublishedsimultaneouslyinCanada ISBN:978-0-470-43452-9 ManufacturedintheUnitedStatesofAmerica 10987654321 LibraryofCongressCataloging-in-PublicationDataisavailablefromthepublisher. Nopartofthispublicationmay bereproduced,storedinaretrievalsystemortransmitted inanyformorby anymeans,electronic,mechanical,photocopying,recording,scanningorotherwise,exceptaspermittedunder Sections107or108ofthe1976UnitedStatesCopyrightAct,withouteitherthepriorwrittenpermissionofthe Publisher,orauthorizationthroughpaymentoftheappropriateper-copyfeetotheCopyrightClearanceCenter, 222RosewoodDrive,Danvers,MA01923,(978)750-8400,fax(978)646-8600.RequeststothePublisherforpermission shouldbeaddressedtothePermissionDepartment,JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030, (201)748-6011,fax(201)748-6008,oronlineathttp;//www.wiley.com/go/permissions. LimitofLiability/DisclaimerofWarranty:Thepublisherandtheauthormakenorepresentationsorwarrantieswith respecttotheaccuracyorcompletenessofthecontentsofthisworkandspecificallydisclaimallwarranties, includingwithoutlimitationwarrantiesoffitnessforaparticularpurpose.Nowarrantymaybecreatedorextended bysalesorpromotionalmaterials.Theadviceandstrategiescontainedhereinmaynotbesuitableforevery situation.Thisworkissoldwiththeunderstandingthatthepublisherisnotengagedinrenderinglegal,accounting, orotherprofessionalservices.Ifprofessionalassistanceisrequired,theservicesofacompetentprofessionalperson shouldbesought.Neitherthepublishernortheauthorshallbeliablefordamagesarisingherefrom.Thefactthatan organizationorWebsiteisreferredtointhisworkasacitationand/orapotentialsourceoffurtherinformation doesnotmeanthattheauthororthepublisherendorsestheinformationtheorganizationorWebsitemayprovide orrecommendationsitmaymake.Further,readersshouldbeawarethatInternetWebsiteslistedinthisworkmay havechangedordisappearedbetweenwhenthisworkwaswrittenandwhenitisread. ForgeneralinformationonourotherproductsandservicespleasecontactourCustomerCareDepartmentwithinthe UnitedStatesat(877)762-2974,outsidetheUnitedStatesat(317)572-3993orfax(317)572-4002. Trademarks:Wiley,theWileylogo,Wrox,theWroxlogo,WroxProgrammertoProgrammer,andrelatedtradedress aretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliates,intheUnitedStatesand othercountries,andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheir respectiveowners.WileyPublishing,Inc.,isnotassociatedwithanyproductorvendormentionedinthisbook. Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprintmaynotbe availableinelectronicbooks. Arsenovski ftoc.tex V3-03/20/2009 9:17am Pageix Contents Introduction xvii Chapter 1: Refactoring: What’s All the Fuss About? 1 AQuickRefactoringOverview 1 TheRefactoringProcess 2 ALookattheSoftwareSituation 3 TheRefactoringProcess:ACloserLook 5 UsingCodeSmells 6 TransformingtheCode 6 AutomatingRefactoringTransformations 6 TheBenefitsofRefactoring 8 DebunkingCommonMisconceptions 10 NoProgrammerIsanIsland 19 RefactoringforBusinessPeople 20 C#andRefactoring 21 Summary 21 Chapter 2: A First Taste of Refactoring 23 SampleApplication:CaloriesCalculator 23 CaloriesCalculatorApplicationwithRecommendedDailyCaloriesAmountCalculation 24 GrowingRequirements:CalculatingIdealWeight 27 GrowingRequirements:PersistingPatientData 30 RefactoringinAction 31 DecomposingthebtnCalculate_ClickMethod 32 TheCalculateandDisplayDistancefromIdealWeightSegment 33 CalculatingCaloriesandIdealWeightbyGender 33 ThebtnCalculate_ClickMethodafterMethodExtraction 34 DiscoveringNewClasses 35 NarrowingthePatientClassInterface 38 RestructuringtheDistanceFromIdealWeightMethod 41 CreatingthePatientClassHierarchy 43 ImplementingthePersistenceFunctionality 48 SavingtheData 49 ImplementingPatient-HistoryDisplayFunctionality 57 Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagex Contents CaloriesCalculator,RefactoredVersion 61 Summary 63 Chapter 3: Assembling a Refactoring Toolkit 65 UsinganAutomatedRefactoringTool 66 ReSharperfromJetBrains 66 Refactor!ProfromDeveloperExpress 67 Refactor!forASPfromDeveloperExpress 68 VisualStudioRefactoringFeatures 68 Unit-TestingBasics:TheTestingHarness 70 WhyaUnitTestingFramework? 71 YourFirstTasteofNUnit 73 InstallingNUnit 74 WorkingwiththeSamples 74 ImplementingYourFirstTest 76 TheTest-DrivenApproach 84 OtherTestToolstoConsider 85 AboutVersionControl 87 VersionControlAsaBackupSystem 87 VersionControlandConcurrency 87 Summary 88 Chapter 4: Application Prototype: Rent-a-Wheels 89 InterviewingtheClient 90 InterviewingtheManager 90 InterviewingtheDeskReceptionist 91 InterviewingtheParkingLotAttendant 91 InterviewingMaintenancePersonnel 92 TakingtheInitialStepsintheRent-a-WheelsProject 93 ActorsandUseCases 93 VehicleStates 95 FirstSketchoftheMainApplicationWindow 97 Rent-a-WheelsTeamMeeting 97 MakingthePrototypeWork 98 ExaminingtheDatabaseModel 98 ExaminingtheC#Code 100 FastandFuriousApproachtoProgramming 104 Database-DrivenDesign 104 GUI-BasedApplication 104 Event-DrivenProgramming 105 x Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexi Contents RapidApplicationDevelopment(RAD) 105 CopyandPasteAsaCodeReuseMechanism 106 FromPrototypetoDeliveryThroughtheRefactoringProcess 106 Summary 106 Chapter 5: Basic Hygiene 109 EliminatingDeadCode 109 TypesofDeadCode 111 CommonSourcesofDeadCode 112 ReducingtheScopeandAccessLevelofUndulyExposedElements 116 ScopeandAccessLevel 118 CommonSourcesofOverexposure 119 DealingwithOverexposure 122 UsingExplicitImports 123 UsingSectionDepictsDependenciesinYourSystem 124 RemovingUnusedAssemblyReferences 126 BasicHygieneintheRent-a-WheelsApplication 127 Summary 128 Chapter 6: From Problem Domain to Code: Closing the Gap 129 UnderstandingtheProblemDomain 130 StepOne:GatheringtheInformation 131 StepTwo:AgreeingontheVocabulary 131 StepThree:DescribingtheInteractions 132 StepFour:BuildingthePrototype 133 NamingGuidelines 133 CapitalizationStyles 134 SimpleNamingGuidelines 135 GoodCommunication:ChoosingtheRightWords 136 RenameRefactoring 140 RenameRefactoringinVisualStudio 142 PublishedandPublicInterfaces 144 Self-ContainedApplicationsversusReusableModules 144 ModifyingthePublishedInterfaces 148 RenameandSafeRenameRefactoringintheRent-a-WheelsApplication 153 Summary 154 Chapter 7: The Method Extraction Remedy for Duplicated Code 155 EncapsulatingCodeandHidingtheDetails 155 InformationandImplementationHiding 156 xi Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexii Contents DecomposingMethods 159 CircumferenceCalculation—LongMethodExample 159 ExtractingCircumferenceLengthCalculationCode 162 ExtractingtheRadiusCalculationCode 165 Extractingthe‘‘WaitforUsertoClose’’Code 166 ExtractingtheReadCoordinatesCode 166 ExtractMethodRefactoringinVisualStudio 169 InliningMethods 171 TheDuplicatedCodeSmell 175 SourcesofDuplicatedCode 176 Copy-PasteProgramming 177 MagicLiterals 178 Extract Method and Replace Magic Literal Refactoring in the Rent-a-Wheels Application 179 Summary 180 Chapter 8: Method Consolidation and Extraction Techniques 183 DealingwithTemporaryVariables 183 MoveDeclarationNearReferenceRefactoring 184 MoveInitializationtoDeclarationRefactoring 187 SplitTemporaryVariableRefactoring 188 InlineTempRefactoring 192 ReplaceTempwithQueryRefactoring 194 IntroducingExplainingTemporaryVariables 197 DealingwithLongandNestedConditionals 198 MethodReorganizationandRent-a-Wheels 201 RemovingDuplicationinRent-a-Wheels 203 Summary 211 Chapter 9: Discovering Objects 213 ABriefObject-OrientedProgrammingOverview 214 ObjectsinOOP 214 EncapsulationandObjects 214 EncapsulateFieldRefactoringinVisualStudio 216 ObjectStateRetention 218 Classes 218 ObjectIdentity 219 ObjectsAsBasicBuildingBlocks 220 RootObject 221 ObjectLifetimeandGarbageCollection 221 xii Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexiii Contents DesigningClasses 223 UsingAnalysisArtifacts 223 ClassesAreNouns,OperationsAreVerbs 226 Classes,Responsibilities,andCollaborators 231 EmployingCardsinBrainstormingSessions 235 EntitiesandRelationships 239 DiscoveringHiddenClasses 240 DealingwithDatabase-DrivenDesign 241 MovingfromProceduraltoObject-OrientedDesign 244 SeparatingDomain,Presentation,andPersistence 252 DiscoveringObjectsandtheRent-a-WheelsApplication 257 Summary 265 Chapter 10: Advanced Object-Oriented Concepts and Related Refactorings 267 Inheritance,Polymorphism,andGenericity 268 Inheritance 268 ClassversusInterfaceInheritance 271 Polymorphism 273 Genericity 276 InheritanceAbuseandRefactoringSolutions 277 CompositionMistakenforInheritanceandOtherMisuses 281 RefactoringforInheritance—Print-SystemExample 288 DelegationInsteadofInheritanceInsidethePrintSystem 294 MakingUseofGenerics 308 InheritanceandGenericTypesintheRent-a-WheelsApplication 312 ExtractingSuper 312 EmployingGenerics 313 ExtractingtheDataObjectsProviderClass 314 Summary 318 Chapter 11: Code Organization on a Large Scale 319 Namespaces 319 NamingGuidelinesandNamespaceOrganization 320 NestedNamespaces 320 ChangingtheDefaultNamespaceName 321 EmployingUsingDirectives 321 Assemblies 323 BinaryReuse 323 NamespaceOrganizationGuidelines 325 DependencyConsiderations 330 xiii Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexiv Contents C#ProjectFileStructureOrganization 338 PartialClasses 339 NamespaceOrganizationandWindowsFormsInheritanceinRent-a-Wheels 345 ExtractingtheParentAdministrationFormUsingtheAbstractFormHelperPattern 345 NamespaceandAssemblyReorganization 353 Summary 355 Chapter 12: Refactoring to Patterns 357 DesignPatterns:What’sAlltheFussAbout? 358 DefiningDesignPatterns 358 ClassifyingPatterns 359 PatternElements 359 WeighingtheBenefitsofDesignPatterns 360 UsingPatterns 360 ExampleDesignPattern:AbstractFactory 361 UsingAbstractFactory 361 Solution 371 Consequences 374 DependencyInjectionPattern 376 ProblemUsingDependencyInjection 376 Solution 379 Constructor-BasedInjectionvs.Property-BasedInjection 380 WhatServiceImplementationtoInject 380 BenefitsoftheDIPattern 382 RefactoringtoDI 385 RefactoringtoPatternsandtheRent-a-WheelsApplication 385 EliminatingCodeThatDuplicates.NETFrameworkFunctionality 385 InjectingDataClassestoGUIClassesviaDependencyInjection 386 CRUDPersistencePattern 389 Summary 389 Chapter 13: LINQ and Other C# 3.0 Enhancements 391 TypeInferenceforLocalVariables 391 Auto-implementedProperties 393 ExtensionMethods 395 ObjectandCollectionInitializers 402 QueryingObjectswithLINQ 404 OldExampleinNewRobes 407 Object-RelationalMappingwithLINQtoSQL 414 LINQandtheRent-a-WheelsApplication 418 Summary 427 xiv Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexv Contents Chapter 14: A Short History of the Web for Developers and ASP.NET Tooling 429 Refactor!forASP.NET 430 InvokingRefactor!forASP.NET 431 ExploringtheRefactor!forASP.NETUserInterface 433 HTMLHistoryandItsLegacy 438 HTMLHistory 438 CatchingUpwiththeWeb 446 VisualStudioandXHTML 446 XMLandEncoding 447 VisualStudioDTDValidationforHTML 448 ServingStrictXHTML 449 Summary 451 Chapter 15: Refactoring ASP.NET Applications 453 RefactoringHTML 454 Well-FormedXHTMLDocuments 454 XHTMLValidity 456 ToolSupportforUpgradingLegacy,XHTMLNon-CompliantMarkup 458 Pretty-PrintingYourHTMLDocuments 459 SeparatingStructurefromPresentation 460 UsingHTTPtoYourAdvantagewithREST 467 RefactoringASP.NETCode 472 ASP.NETCodeModel:Single-filevs.Code-behind 472 MasterPages 476 WebUserandCustomServerControls 480 Rent-a-WheelsandASP.NETRefactorings 486 Summary 489 Appendix A: Rent-a-Wheels Prototype Internals and Intricacies 491 HandOverButtonClickEvent-HandlingCode 491 ReceiveButtonClickEvent-HandlingCode 492 ChargeButtonClickEvent-HandlingCode 492 ChangeBranchButtonClickEvent-HandlingCode 493 ToMaintenanceandFromMaintenance 497 AdministerFleetForm 498 DeleteButtonClickEvent-HandlingRoutine 498 NewButtonClickEvent-HandlingRoutine 499 ReloadButtonClickEvent-HandlingRoutine 499 FormLoadEvent-HandlingRoutine 499 xv Arsenovski ftoc.tex V3-03/20/2009 9:17am Pagexvi Contents AdministerFleetFormClassCode:Fields 501 NavigationButtonsClickEvent-HandlingRoutine 502 SaveButtonClickEvent-HandlingRoutine 503 DisplayButtonClickEvent-HandlingRoutine 505 Summary 509 Appendix B: Unleash Refactor! for ASP.NET 511 Index 515 xvi

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.