Weitere ähnliche Inhalte Ähnlich wie Coding Standards in the Real World Webcast Recording and Resources Ähnlich wie Coding Standards in the Real World Webcast Recording and Resources (20) Kürzlich hochgeladen (20) Coding Standards in the Real World Webcast Recording and Resources1. Coding Standards
in the Real World
3/25/2014
http://submain.com/webcasts/coding-standards-in-the-real-world/
for the webcast recording, slides and ebook download
2. Webcast Housekeeping
Main session – GoToWebinar
Audio
Connect viaVoIP
Plug in a headset or turn up your
speakers
Connect via Phone
Select “UseTelephone” after joining
the webinar
Call 1 (415) 655-0063
Access Code: 575-649-883
Audio PIN: Shown after joining the webinar
3/25/2014 Copyright © SubMain 2014 Slide 2
Overflow session – Meeting Burner
Audio
Connect viaVoIP
Plug in a headset or turn up your
speakers
Select “Headset/Mic” in Audio Options
Connect via Phone
Select “Dial In” in Audio Options
Call 1 (949) 229-4400
PIN: 1066921#
3. Webcast Housekeeping - continued
Asking A Question
GoToWebinar - use the Questions window in the
panel on the right of your screen
Meeting Burner – use the Ask a Question button
in the top left corner
Questions will be addressed at the end of the
webcast
Recording
A recording and ebook download link will
be sent to all registrants within a few days
3/25/2014 Copyright © SubMain 2014 Slide 3
5. David McCarter
Microsoft MVP
RockThe Nation ConferenceTour
HTTP://BIT.LY/DNDRTNT
David McCarter’s .NET Coding Standards
BIT.LY/DOTNETDAVESTORE
dotNetTips.com
700+Tips,Tricks, Articles, Links!
Open Source Projects:
CODEPLEX.COM/DOTNETTIPS
San Diego .NET Developers Group
Speaking at an event near you!
HTTP://BIT.LY/DNDRTNT
@realdotnetdave davidmccarter
3/25/2014 Copyright © SubMain 2014 5
7. Poll
Have you tried to implement team guidelines within
your team/organization?
3/25/2014 Copyright © SubMain 2014 Slide 7
8. Why Are Standards Needed?
Code Clarity/Easier to Understand
Easier to Maintain
Reduce Bugs
SimplifyCode Reviews
Shorter learning curve for new team members
Consistency across large and distributed teams
Comply with internal or regulatory quality initiatives
3/25/2014 Copyright © SubMain 2014 Slide 8
9. Business Benefits
Improve software quality
Accelerate time to market
Enhance customer satisfaction
Reduce long term cost
Improve productivity
3/25/2014 Copyright © SubMain 2014 Slide 9
10. WorkedWith Someone Else’s Code?
3/25/2014 Copyright © SubMain 2014 10
No Documentation Coding Standards
Magic Numbers Tightly Coupled Code
Large Classes GlobalVariables
Bad Names Broken Code
Bad Formatting Improper Scoping
11. Cost Of Fixing Bugs
1 5x
10x
20x
50x
>150x
Requirements Design Code Dev Testing Acceptance Production
RelativeCosttoFixDefect
3/25/2014 Copyright © SubMain 2014 11
Source: Barry Boehm: “EQUITY Keynote Address”, March 19th, 2007
12. Why Coding Standards Fail
35%
23%
26%
10%
6%
Developers kept forgetting to abide the
guidelines
Resistance among the team members
Couldn't get a concensus on which standard
to follow
Managemen thought is was too expensive
and not worth the investment
Other
3/25/2014 Copyright © SubMain 2014 12
Source: SubMain survey of developers and teams
13. Examples of Good & Bad
Coding Practices
3/25/2014 Copyright © SubMain 2014 13
14. Top 10 Coding issues
1. Design / Do not declare externally visible instance fields
2. Performance / Do not check for empty strings using Equals
3. Performance / Remove unused locals
4. Exception Handling / Do not handle non-CLS-compliant exceptions
5. Performance / Do not initialize unnecessarily
6. Performance / Remove unused private methods
7. Error Handling / Do not re-throw exceptions explicitly
8. Design /Type that contains only static members should be sealed (NotInheritable)
9. Usability / Mark all non-serializable fields with "NonSerialized" attribute
10. Security / Do not declare read only mutable reference types
3/25/2014 Copyright © SubMain 2014 14
Source: SubMainCodeIt.Right telemetry data
15. Class Design - Unacceptable
public class OrderData
{
public string ORDER;
private string facilityID = "";
public string OrderNumber = "";
public string openClosed = "";
public string transType = "";
public string dateOpened = "";
public string dateClosed = "";
public string dateShop = "";
public OrderData(string _ORDER)
{ this.ORDER = _ORDER;}
…
}3/25/2014 Copyright © SubMain 2014 16
16. Class Design - Proper
public enum TransactionType
{ None, Order, Payment, Refund }
public class OrderData
{
public OrderData()
{}
public TransactionType TransactionType { get; set; }
public DateTime OpenedOn { get; set; }
public string FacilityId { get; set; }
public string Order { get; set; }
public string OrderNumber { get; set; }
TurnedTransactionType
into enum
Set OrderData properties
another way
ModifiedTransactionType
property
New properties using
proper types
3/25/2014 Copyright © SubMain 2014 17
17. Class Design - Proper
3/25/2014 Copyright © SubMain 2014 18
public bool IsClosed { get; private set; }
private DateTime? _closedOn;
public DateTime? ClosedOn
{
get
{
return _closedOn;
}
…
Set IsClosed set accessor to
private. Should only be set
when ClosedOn is set.
Changed ClosedOn to
nullable type
18. Class Design - Proper
3/25/2014 Copyright © SubMain 2014 19
set
{
if (_closedOn.GetValueOrDefault() != value.GetValueOrDefault())
{
IsClosed = false;
if (_closedOn.HasValue && _closedOn.Value > DateTime.Now)
{
throw new ArgumentOutOfRangeException();
}
_closedOn = value;
IsClosed = true;
}
}
Don’t set value if
same
Throw Exception if
value is invalid
Set IsClosed
Validate!
19. Exception Example
3/25/2014 Copyright © SubMain 2014 20
try { //Code removed for brevity
if (orderCustomerID.ToUpper() != this.customerInfo.customerID.ToUpper())
{
string str9 = "ERROR: Bad Customer ID: " + this.customerInfo.customerID + " :";
this.logger.WriteLine(str9);
Util.SendMail("cs@acme.com", "admin@acme.com", "Bad Customer ID", str9);
flag = false;
result = Result.eBadID;
throw new Exception(message);
}
}
catch (Exception exception) {
if (exception.Message.StartsWith(message))
{ throw new Exception(message); }
}
20. Exception Example – Proper Design
3/25/2014 Copyright © SubMain 2014 21
//Code removed for brevity
if (customerId.ToUpper() != this.customer.Id.ToUpper())
{
throw new InvalidOperationException(String.Format(
Properties.Resources.CustomerIdIsInvalid,
this.customerInfo.customerID));
}
No need for most of
the previous code
If id isn’t valid bomb
out of method
Use resources for
globalization
21. DealingWith &Throwing Exceptions
Only useTry/Catch when the code needs to deal with
a specific Exception type
Clean up things like database connections & file handles
Possibly do a retry.
Never catch the Exception base type
In API Dll’s
Throw meaningful Exceptions
Use Exception types from framework
Create custom Exception types if needed
3/25/2014 Copyright © SubMain 2014 22
22. ReferenceTypes
finally
{
if (null != sqlDataReader)
sqlDataReader.Close();
if (null != this.connection)
this.connection.Close();
if (null != this.BMSConnection)
this.BMSConnection.Close();
}
3/25/2014 Copyright © SubMain 2014 23
23. ReferenceTypes - Fixed
using(var sqlDataReader = new SqlDataReader)
{
//SqlDataReader code goes here
using(var connection = new SqlConnection)
{
//SqlConnection code goes here
using(var BMSConnection = new SqlConnection)
{
//SqlConnection codes here
}
}
}
PreventVirtual
Memory Leaks
• Always call Dispose on
IDisposable types!
• Use the using
statement
3/25/2014 Copyright © SubMain 2014 24
Calls Dispose on BMSConnection
Calls Dispose on connection
Calls Dispose on sqlDataReader
24. More Suggestions
Check access to database server, internet & web site
before calling!
Trap unhandled Exceptions in app
CurrentDomain_UnhandledException in WinForms
Application_Error in ASP.NET
DispatcherUnhandledException in WPF
3/25/2014 Copyright © SubMain 2014 25
27. Seven Steps - Overview
1. Get the business owner’s buy-in
2. Get initial consensus
3. Choose a base standard to follow
a. Customize the standard (optional)
4. Create our own team guidelines document
a. Prioritize what’s most important
5. Implement Code Reviews
6. Use code generation
7. Review status and give feedback
3/25/2014 Copyright © SubMain 2014 28
28. #1 - Get the Business Owner’s Buy-in
This is crucial for the success of coding standards
Benefits must be stressed
Produces more stable code with less bugs
Lowers maintenance costs
Lowers cost to implement new features
Need to know of the costs
Manual code review can increase costs
Staff time
First thing cut from schedule to make up for delays
3/25/2014 Copyright © SubMain 2014 29
29. #2 - Get Initial Consensus
Involve all parties
Management
Project Managers
Quality Assurance
Developers
Analyze options
Discuss possibilities
Achieve initial consensus – the best you can at this point
Helps process to get started
3/25/2014 Copyright © SubMain 2014 30
30. #3 – Choose a Base Standard to Follow
Focus on the most important aspects
Don’t get sucked into curly brace wars
Any standard is better than no standard at all!
Don’t reinvent the wheel - great coding standards exists
and should be considered
Microsoft Design Guidelines for Developing Class Libraries
SubMain .NET Coding Guidelines
David McCarter’s .NET Coding Standard (C# &VB.NET)
IDesign C# Coding Standard
Philips C# Coding Standard
3/25/2014 Copyright © SubMain 2014 31
31. #3.a - Customize the Standard (if needed)
With team buy-in, the standard can be customized for your
teams needs and requirements
Customization can include
Namespace naming
Assembly naming
Details on using strong named assembly key files
Workflow on checking code into source control
Deviating from common industry practices can
Make it harder for developers to follow
Make it harder for new developers to fit in
3/25/2014 Copyright © SubMain 2014 32
32. #4 – CreateYour Own Guidelines Document
Create document that reflects consensus reached in Step 2
Should be a live document that is changed based on team’s
experience
Prioritize what’s most important
Document should include two important areas
‘Required’ (should be small as possible)
‘Recommended’
Ensure that document includes any company “required”
standards that might exist
3/25/2014 Copyright © SubMain 2014 33
33. #5 - Implement Code Reviews
Code reviews are important to ensure standards are followed
Developers have a tendency to write code the way they have done in the past
Consistency is more important than personal style
Manual code review or pair programming
Avoid criticism during review
Should be a learning experience for all involved
Complement manual with Automated Review
Will 100’s of possible rules, this will find any that were missed
Speed up cycle for finding and fixing issues before found by QA
Or worse case found in production
Enable manual code review to focus on the proprietary business logic
Use tools – they do not forget the standards!
3/25/2014 Copyright © SubMain 2014 34
34. #6 – Use Code Generation
Consider use of code generation tools
Reduced repetitive coding
Ensure consistency and accuracy
Reduced bugs
Generate:
Data access code and datasets
Collections
Some tools available
CodeSmith Generator
Microsoft .NET Entity Framework
Microsoft .NETT4Templates
Many more
3/25/2014 Copyright © SubMain 2014 35
35. #7 – Review Status and Give Feedback
Review initial agreement
Make changes if necessary and update document
Notify team
Track progress & report back to business owner
Provide metrics of progress
Identify problem areas
Backup with objective data
3/25/2014 Copyright © SubMain 2014 36
37. Your Coding Standard Checklist
Starter Set
Naming Conventions
Formatting Style
Coding Patterns to Use
Coding Patterns to Avoid
Error Handling
Usage Guidelines
3/25/2014 Copyright © SubMain 2014 38
Advanced Set
Security
Design
Performance
Globalization
Maintainability
Other Best Practices
39. What is CodeIt.Right
Automated way to ensure your source code adheres to
(your) predefined design requirements
style guidelines
best coding practices
Static Code Analysis and Metrics
Automatic and safe refactoring
of issues into conforming code
Automated Code Review process
3/25/2014 Copyright © SubMain 2014 40
40. What is CodeIt.Right - continued
Instant Code Review – real-time code checking
OnDemand Analysis
Source Control Check-In Policy
Build Process Integration
Hundreds of rules
Security, Performance, Usage,
Design, Maintainability,
Exception Handling, Globalization,
Async, and more
3/25/2014 Copyright © SubMain 2014 41
41. CodeIt.Right Benefits
Improve Product Quality at the Source
Comply with internal or regulatory quality initiatives
Decrease the cost and time of Code Reviews
Reduce QA testing and focus
on meeting requirements
Continuous Code Quality Solution
3/25/2014 Copyright © SubMain 2014 42
42. So now, How CodeIt.Right Helps
3/25/2014 Copyright © SubMain 2014 43
43. Get the Business Owner’s Buy-in
Helps calculate cost savings
and ROI
Consistency enforcing
coding standards
Clear benefit of
Automated/Manual approach
Knowing benefits and costs will help bring business
owners onboard
3/25/2014 Copyright © SubMain 2014 44
44. Initial Consensus and Base Standard
Get initial consensus
Easier when tool offers most common guidelines out of the box
Fewer arguments about standards
Head start in often difficult step
Choose a base standard to follow
Out of the box, CodeIt.Right offers Microsoft Coding Guidelines
Free SubMain .NET Coding Guidelines adds to and improves on
the Microsoft Coding Guidelines
3/25/2014 Copyright © SubMain 2014 45
45. Customize Standard and Create Document
Customize the standard
Easily customize the base rule set to fit
your needs:
Custom profiles
Create and tweak existing rule instances
Override existing rule behavior
Create custom rules
Create your own guidelines document
Automatic guidelines document from
your profiles
3/25/2014 Copyright © SubMain 2014 46
46. PrioritizeWhat’s Important
Prioritize what’s more important
Any number of profiles can be created such as ‘Required’,
‘Recommended’, ‘Security’, ‘Performance’, etc
Use SeverityThreshold to address Critical Errors and then
drill down toWarnings
Exclude projects, files or specific violations
3/25/2014 Copyright © SubMain 2014 47
47. Automated Code Review
Instant Code Review
Drastically cuts costs of issues since they are found early
Automated Refactoring
Fix issues on the spot
Safe and tested refactorings
Continuous Code Quality
Real-time issue feedback
OnDemand Analysis
Source Control Check-In Policy
Build Process Integration
3/25/2014 Copyright © SubMain 2014 48
48. CodeGen and Feedback
Code generation
Refactoring to Patterns
CodeGen aware - options to skip generated code
Review status & give feedback
Easily find:
Largest violation categories
Code metrics status
Violations and fixes over time
Objective and accurate data
3/25/2014 Copyright © SubMain 2014 49
49. Q&A
Questions?
Email - customer-service@submain.com
Video - submain.com/codeit.right/video
Download the free CodeIt.Right trial at submain.com/codeit.right
3/25/2014 Copyright © SubMain 2014 50
1 (800) 936-2134
http://submain.com/webcasts/coding-standards-in-the-real-world/
for the webcast recording, slides and ebook download