View
218
Download
0
Category
Tags:
Preview:
Citation preview
Best Practices ForBest Practices ForApplication DevelopmentApplication Development
Steven Wilssens & Jelle DruytsSteven Wilssens & Jelle DruytsCompuware .NET ConsultantsCompuware .NET Consultants
http://steven.wilssens.nethttp://steven.wilssens.nethttp://jelle.druyts.nethttp://jelle.druyts.net
2
GoalsGoals
Write better codeDocument your codeApply design patterns in your codeFeel confident about your code
Be proud of your code
3
AgendaAgenda
Developing CodeDocumenting CodeDesigning CodeTesting CodeBuilding Code
4
Developing CodeDeveloping Code
5
Exception HandlingException Handling
Handle exceptions consistently throughout your applicationMake exception handling code simpleBest practices:
Don't disclose security sensitive information to remote callersAdd context to exceptions by wrapping or replacing exceptionsLog and monitor all exceptions that occur
Developing CodeDeveloping Code
6
LoggingLogging
Log business and operations data for runtime application monitoringMake logging code simpleBest practices:
Provide tracing to support production debuggingProvide auditing for increased securityChange logging settings through configuration
Which messages go where (file, event log, email, ...)How the messages are formatted (templates)When to log (information, warning, error, critical)
Developing CodeDeveloping Code
7
Data AccessData Access
Read and write to commonly used databases in a simple and efficient wayMake data access code simpleBest practices:
Perform multiple updates within one transactionHandle different database providers transparently Separate logical from physical databasesChange connection settings through configuration
Provider type (SQL Server, Oracle, OLE-DB, ODBC, ...)Connection string
Developing CodeDeveloping Code
8
CachingCaching
Eliminate expensive data retrieval by keeping a local copyMake caching code simpleBest practices:
Provide different cache invalidation mechanisms (absolute time, sliding time, file change, database change, ...)Provide different cache stores (in-memory, database)Use a local cache for offline operations on disconnected smart clientsDon't be afraid to use the ASP.NET cache anywhere for non-persistent storage (even in Windows Forms)
Developing CodeDeveloping Code
9
CryptographyCryptography
Encrypt or hash sensitive information before persisting it; decrypt or compare when reading it backMake cryptography code simpleBest practices:
Never store passwords directly, only hash valuesOnly decrypt data if absolutely necessary (use a hash where possible)Use symmetric keys to encrypt and decrypt data across multiple machinesUse Windows DPAPI for cryptography on a single machine without using keys
Developing CodeDeveloping Code
10
SecuritySecurity
Authenticate and authorize users using one or more security systemsMake security code simpleBest practices:
Use an authentication system to see if a user can access a systemUse an authorization system to see if a user can perform a certain taskCache authentication or authorization data for the duration of a logon session
Developing CodeDeveloping Code
Enterprise Library 2.0Enterprise Library 2.0
12
Enterprise Library 2.0Enterprise Library 2.0
Set of reusable components from MicrosoftConsistentExtensibleEasy to useIntegrated
Source code you compile yourselfFreeNot a Microsoft productTested through many unit tests
Use only the blocks you needVisual configuration tool
Developing CodeDeveloping Code
13
Key Changes From 1.xKey Changes From 1.x
Configuration Application Block no longer exists
Configuration now built on System.ConfigurationLogging Application Block
Much improved flexibility and performanceData Access Application Block
Simpler and much more powerfulSupports SQL Server, Oracle, OLE-DB, ODBC or any other managed provider
Security Application Block Most of it deprecated in favor of .NET’s Membership and Profile features
14
Data Data AccessAccess LoggingLogging
Enterprise Library 2.0 BlocksEnterprise Library 2.0 Blocks
Plug-inConfigConfig
Helpers Helpers & Design& Design
Instrumen-Instrumen-tationtation
ObjectObjectBuilderBuilder
CryptographyCryptography
Core
Block DependencyOptional ProviderDependency
Developing CodeDeveloping Code
SecuritySecurity
CachingCaching
ExceptionExceptionHandlingHandling
15
Enterprise Library 2.0Enterprise Library 2.0
16
Documenting CodeDocumenting Code
17
Why?Why?
Your code is not self-documentingUndocumented code is untestable codeEasier to plan next versionEasier to return laterBrings new team members quickly up to speedCreates happy customers
Documenting CodeDocumenting Code
18
How?How?
Put XML comments on your codeDocument all public and protected membersLearn and use the XML tags
Write additional contentUser's guide & Known issuesInstallation & Configuration guide
Generate documentationCHM, HTML, HxS, ...
Documenting CodeDocumenting Code
/// <summary>/// Write a new log entry to the default category./// </summary>/// <param name="message">Message body to log.</param>public static void Write(object message) { ... }
19
Documentation ToolsDocumentation Tools
CR_DocumentorNDoc (being updated for .NET 2.0)
Documenting CodeDocumenting Code
20
Designing CodeDesigning Code
21
Command Pattern and Command Pattern and Enterprise Library 2.0Enterprise Library 2.0
Designing CodeDesigning Code
22
Testing CodeTesting Code
23
TestabilityTestability
Allow unit testing of major part of applicationTests must be deterministicTests must be automatedTests must be efficient (execute quickly)
Testing CodeTesting Code
24
Dependency PrinciplesDependency Principles
Communicate with interfaces or base classesSeparate interface definitions from implementationsUse dependency injection to late-bind objectsExternalize environment dependenciesExternalize non-deterministic behaviorExternalize timing behavior
Testing CodeTesting Code
25
Unit TestingUnit Testing .NET .NET
NUnitVisual Studio Test
Testing CodeTesting Code
26
General PrinciplesGeneral Principles
Test cases must be independentReproduce bugs as test casesTest only public membersPlace tests in separate projectsHave a test project per test targetUse source control on test projects
Testing CodeTesting Code
27
Test-Driven DevelopmentTest-Driven Development
Write unit tests before or in parallel with production codeUnit tests help define the systemUnit tests are debugging driversDevelopers write the tests”It’s better to write and run incomplete tests than not to run complete tests”
Testing CodeTesting Code
28
Test Driven DevelopmentTest Driven Development
29
Code Coverage BasicsCode Coverage Basics
Records which parts of an application's code is being exercised by a test suite
Testing CodeTesting Code
30
Code Coverage BCode Coverage Best est PracticesPractices
Use code coverage to monitor your tests' effectiveness
Project managers can aggregate results as a project status indicatorTeam members can analyze source for specific missed lines of code
Set a high, but realistic target
Testing CodeTesting Code
31
Code Coverage PCode Coverage Pitfallsitfalls
Best quantifiable measureDoesn’t say a lot about quality of testsBeware of developer shortcuts
Testing CodeTesting Code
32
Code CoverageCode Coverage
33
Building CodeBuilding Code
34
Daily Build DefinitionDaily Build Definition
Daily builds are the results of a fully automated process which, by using source code, compiles, validates, and packages a software solution
Daily builds don’t have to run each day, as long as they run frequently
Building CodeBuilding Code
35
Introducing Daily BuildsIntroducing Daily Builds
”The build is the heartbeat. If there ain’t no heartbeat, it’s dead!”Must be fully automatedDifficult to doNo excuse for not doing daily builds: The more complex your system is, the more you need it
Building CodeBuilding Code
36
Daily Build BenefitsDaily Build Benefits
State of project becomes more transparentYou always have a product that can potentially shipCurrent test target always availableAnti-surprise deviceReduces overall integration effort
Building CodeBuilding Code
37
Team BuildTeam Build
38
Key PointsKey Points
Developing CodeUse Enterprise Library 2.0
Documenting CodeUse XML comments and NDoc to generate CHM files
Designing CodeCommand Pattern can be used to integrate many enterprise library 2.0 features
Testing CodeYou can take a pragmatic or a formal approach to unit testing
Building CodeUse build verification tests to verify soundness of a build
39
Enterprise Library 2.0http://msdn.microsoft.com/practiceshttp://practices.gotdotnet.com/projects/entlib
Code DocumentationXML Comments Quick Reference
http://jelle.druyts.net/2005/01/16/XMLCommentsQuickReference.aspx
NDochttp://ndoc.sourceforge.net/
CR_Documentorhttp://www.paraesthesia.com/blog/comments.php?id=701_0_1_0_C
Command Patternhttp://steven.wilssens.net/
40
Thank You!Thank You!
Thanks for your attention
We'll be happy to answer all your questions
Right after the sessionCompuware BoothCommunity Booth: Ask-The-Experts VISUG Booth
41
Recommended