Webcast: Coding Standards in the Real World
-
Upload
serge-baranovsky -
Category
Software
-
view
280 -
download
4
description
Transcript of Webcast: Coding Standards in the Real World
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
Webcast Housekeeping
Main session – GoToWebinar
Audio
Connect via VoIP
Plug in a headset or turn up your speakers
Connect via Phone
Select “Use Telephone” after joining the webinar
Call 1 (415) 655-0063Access Code: 575-649-883Audio PIN: Shown after joining the webinar
3/25/2014 Copyright © SubMain 2014 Slide 2
Overflow session – Meeting Burner
Audio
Connect via VoIP
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#
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
Introduction
Presenter
David McCarter
Microsoft MVP
(g)host
Serge Baranovsky
Principal, SubMain
3/25/2014 Copyright © SubMain 2014 4
David McCarter
Microsoft MVP Rock The Nation Conference Tour
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
Benefits Of Coding Standards
3/25/2014 Copyright © SubMain 2014 6
Poll
Have you tried to implement team guidelines within your team/organization?
3/25/2014 Copyright © SubMain 2014 Slide 7
Why Are Standards Needed?
Code Clarity/Easier to Understand
Easier to Maintain
Reduce Bugs
Simplify Code 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
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
Worked With Someone Else’s Code?
3/25/2014 Copyright © SubMain 2014 10
No Documentation Coding Standards
Magic Numbers Tightly Coupled Code
Large Classes Global Variables
Bad Names Broken Code
Bad Formatting Improper Scoping
Cost Of Fixing Bugs
1 5x10x
20x
50x
>150x
Requirements Design Code Dev Testing Acceptance Production
Rel
ativ
e C
ost
to
Fix
Def
ect
3/25/2014 Copyright © SubMain 2014 11
Source: Barry Boehm: “EQUITY Keynote Address”, March 19th, 2007
Why Coding Standards Fail
35%
23%
26%
10%
6%
Developers kept forgetting to abide theguidelines
Resistance among the team members
Couldn't get a concensus on which standardto follow
Managemen thought is was too expensiveand not worth the investment
Other
3/25/2014 Copyright © SubMain 2014 12
Source: SubMain survey of developers and teams
Examples of Good & Bad Coding Practices
3/25/2014 Copyright © SubMain 2014 13
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: SubMain CodeIt.Right telemetry data
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
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; }
Turned TransactionType into enum
Set OrderData properties another way
Modified TransactionType property
New properties using proper types
3/25/2014 Copyright © SubMain 2014 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
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!
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("[email protected]", "[email protected]", "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); }
}
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
Dealing With & Throwing Exceptions
Only use Try/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 ExceptionsUse Exception types from framework
Create custom Exception types if needed
3/25/2014 Copyright © SubMain 2014 22
Reference Types
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
Reference Types - 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
}
}
}
Prevent Virtual 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
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
More Suggestions
AppDomain.FirstChanceException event fire for ALL Exceptions BEFORE going up the call stack
Check out Aspect Programming… cool stuff!
3/25/2014 Copyright © SubMain 2014 26
Seven Step Approach for Successful Implementation
3/25/2014 Copyright © SubMain 2014 27
Seven Steps - Overview
1. Get the business owner’s buy-in
2. Get initial consensus
3. Choose a base standard to followa. Customize the standard (optional)
4. Create our own team guidelines documenta. 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
#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
#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
#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
#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
#4 – Create Your 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
#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
#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 .NET T4 Templates
Many more
3/25/2014 Copyright © SubMain 2014 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
Review
Business owner buy-
in
Initial consensus
Base standard
• Customize
Create team
document
Code Reviews
Code Generation
Review & Give
Feedback
3/25/2014 Copyright © SubMain 2014 37
Remember, team coding guidelines is a live document that evolves based on team’s experience
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
How CodeIt.Right Helps
3/25/2014 Copyright © SubMain 2014 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 refactoringof issues into conforming code
Automated Code Review process
3/25/2014 Copyright © SubMain 2014 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
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
So now, How CodeIt.Right Helps
3/25/2014 Copyright © SubMain 2014 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
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
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 documentAutomatic guidelines document from
your profiles
3/25/2014 Copyright © SubMain 2014 46
Prioritize What’s Important
Prioritize what’s more importantAny number of profiles can be created such as ‘Required’,
‘Recommended’, ‘Security’, ‘Performance’, etc
Use Severity Threshold to address Critical Errors and then drill down to Warnings
Exclude projects, files or specific violations
3/25/2014 Copyright © SubMain 2014 47
Automated Code Review
Instant Code ReviewDrastically 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 feedbackOnDemand Analysis Source Control Check-In Policy Build Process Integration
3/25/2014 Copyright © SubMain 2014 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
Q&A
Questions?
Email - [email protected]
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