2016 08-05 tulsa techfest coding standards
TRANSCRIPT
Tulsa TechFest 2016 | Fri, Aug 5th, 2016 | OSU - Tulsa | 70+ Speakers, 20+ Tracks & 85+ Sessions!
Please help us!Thank our Sponsors:
Tulsa TechFest 2016 | Fri, Aug 5th, 2016 | OSU - Tulsa | 70+ Speakers, 20+ Tracks & 85+ Sessions!
Please be courteous to your fellow attendees
and
set your phones to vibrate or silent mode!
Please Be Courteous!
Tulsa TechFest 2016 | Fri, Aug 5th, 2016 | OSU - Tulsa | 70+ Speakers, 20+ Tracks & 85+ Sessions!
Coding StandardsEffective Not Just Efficient
Mark ReynoldsSenior Solutions ArchitectSouthwestern Energy
4 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards
AbstractEvery project has a development standard.
Sometimes the standard is “if it was hard to write, it should be hard to maintain.”
Developing, and following, a corporate Best Practices standard will lead to continuity, maintainability, robustness, and pride.
5 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards ARE:• A set of guidelines
– for a specific programming language
– for programming styles, practices, and methods
– for software structural quality• Applicable to the human
maintainers and peer reviewers• May [should] be formalized and
followed by an entire team or company
• Not enforced by compilers
Coding Standards ADDRESS:• file organization• indentation• comments• declarations• statements• white space• naming conventions• programming practices• programming principles• programming rules of thumb• architectural best practices, etc.
Coding Standards: Definition
Source: 2015, Coding conventions, Wikipediahttps://en.wikipedia.org/wiki/Coding_conventions
6 Copyright 2016 Mark Reynolds. All rights reserved.
Theiyr’re
Coding Standards (Best Practices): Why use them?
• A Coding Standard is…• Similar to writing in accordance with APA or MLA
– Allows people to focus on content, not formatting
• Maintainability– Makes code readable– Makes code maintainable– Allows easier error identification– Encourages collective ownership– Demonstrates attention to quality and detail
Source: 2015, Drupal Coding Standards, Joe Shindelarhttp://www.pluralsight.com/courses/drupal-coding-standards
7 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Peer Review?
Source: 2013, The Truth About Code Review II, David Walshhttp://davidwalsh.name/code-review-2
Wait for it…
8 Copyright 2016 Mark Reynolds. All rights reserved.
• Commenting & Documentation
• Consistent Indentation• Avoid Obvious Comments• Code Grouping• Consistent Naming Scheme• DRY Principle• Avoid Deep Nesting• Limit Line Length• File and Folder
Organization
• Consistent Temporary Names
• Capitalize SQL Special Words
• Separation of Code and Data
• Alternate Syntax Inside Templates
• Object Oriented vs. Procedural
• Read Open Source Code
Coding Standards: Code Stability and RobustnessTop 15 Best Practices
Source: 2011, Top 15+ Best Practices for Writing Super Readable Code, Burak Guzelhttp://code.tutsplus.com/tutorials/top-15-best-practices-for-writing-super-readable-code--net-8118
9 Copyright 2016 Mark Reynolds. All rights reserved.
Getting Started• Naming Conventions• Editor Conventions• Code Stability and
Robustness• Maintainability• Teams and Testing
Advanced Checklist• Security• Error Handling• User Logging• Corporate Integration• Other
Coding Standards: Checklist
Source: Mark Reynolds, compilation
10 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Naming ConventionVariable Traceability
Source: Mark Reynolds, compilation
One of the most important coding standard
• Trace a variable from source to grave• Column in database: Flymm_Flam• Property in ORM Class: Flymm_Flam• Represented a local variable: flymmFlam• Class-Global variable: _flymmFlam• Constant: FLYMM_FLAM (avoid constants)• Button on Form: btnFlymmFlam (no consensus)• Method Parameter: FlymmFlam (no consensus)• More?
11 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• DO NOT use single letter variable – spell out the purpose
• Be environment aware – DO NOT use reserved words• Avoid abbreviations
– Use lastName, not nam– Unless they are well known like Xml, Html or IO
• DO NOT vary variables by case! (C#)
More Naming Standards
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
Be consistent ! ! !
12 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Naming Convention
• One class per file– Exception: request / response classes in WCF / SOA
• File name = class name
More Naming Standards
13 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Naming Convention
• Name Space Hierarchy (no consensus)– CommonFramework.Core.Extensions
More Naming Standards
14 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Naming Convention
• Use language value types, not system extensions– Use int, long, string, char– Avoid String, Int32, Char
– Use var whenever possible• (Others recommend only used when obvious on the right side)
More Naming Standards
15 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Editor Conventions
• Space v Tabs• Indention (typically 3 or 4)• Editor font, color and highlight
Common Standards
16 Copyright 2016 Mark Reynolds. All rights reserved.
Consideration of Failure Modes are one of the most important coding standards
Coding Standards: Code Stability and Robustness
• Consider failure at every juncture• Examine and handle faults that can be expected
– Null values returned– Non-numeric content
• Try-catch where the unplanned may exist– Data access– Foreign DLL interface
• Plan to clean-up unmanaged code
Failure Modes
Source: Mark Reynolds, compilation
When considering failure modes, when and how should a Unit Test be used?
17 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Focus on specific exceptions whenever possible• Do not catch the general exception (no consensus)• If caught, rethrow within the catch block (no consensus)• API assemblies should not log exceptions / events
More Try-Catch
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
private byte[] GetContents(string location) { try { return ContentManager.Archiver.GetArchive(location); } catch (FileNotFoundException ex) (Exception ex) { //Clean Up code LogWriter.WriteException(ex, TraceEventType.Error,); throw; return null; }}
18 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Use foreach, not traditional for and while loops– Not susceptible to boundary faults– Easier to Follow
• Use language readability enhancements– var foo = string.Empty;
• Use properties when possible
Code Features and Structure
Source: Mark Reynolds, compilation
19 Copyright 2016 Mark Reynolds. All rights reserved.
Header using statements• When you need clear
annunciation– use full namespace reference– omit the using in the header
• When using common C# / .NET references– minimize namespace reference– Include the using in the header
• When there is ambiguity– use enough namespace
reference
Body using statements• To aid in GC• Especially connection objects• Requires IDisposable• To aid in readability
Coding Standards: Code Stability and RobustnessUsing the using
Source: Mark Reynolds, compilation
20 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and RobustnessUsing the using
21 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Example extension methods– public static bool IsNullOrEmpty(this string content)– public static string Left(this string content, int numCharacters)– public static string Right(this string content, int numCharacters)– public static bool IsMatch(this string content, string regEx)– public static string ToTitleCase(this string mText)– public static int ToInt32(this object content, int defaultValue)
• Separate extension types into separate classes / files (string, int, file)
Extension Methods
Source: Mark Reynolds, compilation
22 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and RobustnessExtension Method Example
Source: Mark Reynolds, compilation
namespace Framework.Core{ public static class NumericExtensions { /// <summary> /// Converts an object into a standard int, if possible /// </summary> /// <author>Mark Reynolds</author> /// <param name="content">extended object variable</param> /// <param name="defaultValue">vaule to return if not convertable</param> /// <returns>resulting value - either the converted value or the default</returns> public static int ToInt32(this object content, int defaultValue) { try { if (content == null) return defaultValue; if (content.Equals(DBNull.Value)) return defaultValue;
int result; if (int.TryParse(content.ToString(), out result)) return result;
return defaultValue; } catch { return defaultValue; } } }}
23 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Constructor– Do not call code / methods from within (no consensus)– Parameter capture only
• No exposed variables– Use public (or protected) properties
• Permits validation processes• Permits events
Classes
Source: Mark Reynolds, compilation
24 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Practice Defensive Programming!• Watch for any code that might cause an exception
– accessing files– using objects
• Examples:– call File.Exists to avoid a FileNotFoundException– check an object for null– check a DataSet for rows– check an Array for bounds– check String for null or empty– clean up unused objects!
Defensive Programming
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
Al l data is bad unt i l ver i f ied
25 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Practice Defensive Programming!• Always check for valid parameter arguments• Perform argument validation for every public or protected
method• Throw meaningful exceptions to the developer for invalid
parameter arguments– Use the System.ArgumentException class– Or your own class derived from System.ArgumentException
• Use Code Contracts in .NET 4
Defensive Programming
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
26 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Code Stability and Robustness
• Use StringBuilder in most cases• Do not initialize value types with default values
– CLR handles this more efficiently (size, speed)
• Don’t hold synchronization lock any longer than necessary
More Code Stability and Robustness standards
Source: Mark Reynolds, compilation
27 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Maintainability
• Refactor for code reuse, low cyclomatic complexity values• If you can’t see your code on one screen in the editor, then it’s
probably too long!• Keep generics in mind• There are two kinds of programmers:
– Complexifiers are averse to reduction– Simplifiers thrive on concision
• If your method, class etc. seems huge or overly complicated, then you are most likely doing it wrong!– Refactor!– Ask a follow programmer!– Pair programming!– Code review!
Refactor!
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
28 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Maintainability
• Comment your logic in the code– Be through– Keep it short– Make the code speak for itself
• Mark changes– Date / time– Author– Change # / bug #
• Absolutely make the // TODO– Include who is responsible to complete– Include who originated the TODO
Comments
Source: Mark Reynolds, compilation
(no consensus)
Or not???
29 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityXML Comments
Source: 2013, C# Coding Standards and Best Programming Practice Part-1http://sharp-coders.com/microsoft-net/c-sharp/csharp-coding-standards-best-programmin-practice-part-1
30 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Maintainability
• Complete ALL Assembly Attributes• Utilize the System.CLSCompliant attribute
– Check out Stack Overflow
Assembly Attributes
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
31 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityCode Analysis
Source: 2012, .NET Coding Standards For The Real World , David McCarterhttp://www.slideshare.net/dotNetDave/net-coding-standards-for-the-real-world
32 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityConstants and Magic Numbers
Source: 2013, C# Coding Standards and Best Programming Practice Part-1http://sharp-coders.com/microsoft-net/c-sharp/csharp-coding-standards-best-programmin-practice-part-1
33 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityCurley Braces – separate line, always use
Source: 2013, C# Coding Standards and Best Programming Practice Part-3http://sharp-coders.com/microsoft-net/c-sharp/csharp-coding-standards-best-programmin-practice-part-3
34 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityAdd whitespace
Source: 2013, C# Coding Standards and Best Programming Practice Part-3http://sharp-coders.com/microsoft-net/c-sharp/csharp-coding-standards-best-programmin-practice-part-3
35 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: MaintainabilityUse #region (no consensus)
Source: 2013, C# Coding Standards and Best Programming Practice Part-3http://sharp-coders.com/microsoft-net/c-sharp/csharp-coding-standards-best-programmin-practice-part-3
36 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Maintainability
• Utilize the //TODO reminder• Work through warnings• Reformat class when completed
More Maintainability Standards
Source: Mark Reynolds, compilation
37 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Teams and Testing
• Before you check in code– Make sure it runs– Resolve all errors– Review [fix] all warnings– Resolve all conflicts– Verify the build (continuous integration)
Ya just GOTTA do it
Source: Mark Reynolds, compilation
38 Copyright 2016 Mark Reynolds. All rights reserved.
Coding Standards: Agile Development
• Test-first programming (or perhaps Test-Driven Development),
• Rigorous, regular refactoring,• Continuous integration,• Simple design,• Pair programming,• Sharing the codebase between all or most programmers,• A single coding standard to which all programmers
adhere,• A common “war-room” style work area. (no consensus)
Best Practices Become Agile Software Programming
Source: 2015, Agile Software Programming Best Practiceshttp://www.versionone.com/agile-101/agile-software-programming-best-practices/
39 Copyright 2016 Mark Reynolds. All rights reserved.
• Tools to add to Visual Studio• ReSharper
– http://www.jetbrains.com/
• Refactor Pro! For Visual Studio– https://www.devexpress.com/Prod
ucts/CodeRush/refactor_pro.xml
• StyleCop– https://stylecop.codeplex.com/
• CodeIt.Right– http://submain.com/products/codei
t.right.aspx
• VS Analyze or FXCop– https://msdn.microsoft.com/en-us/l
ibrary/bb429476(v=vs.80).aspx
• Reference Information• Design Guidelines for Class
Library Developers– http://DGForClassLibrary.notlong.c
om
• .NET Framework General Reference Naming Guidelines– http://namingguide.notlong.com
Coding Standards: FinallyThird party products
Source: Mark Reynolds, compilation
40 Copyright 2016 Mark Reynolds. All rights reserved.
Defensive Programming
• An approach to improve software & source code
• Addresses unforeseen circumstances
Objectives
• Qualityreduce # software bugs
• Comprehensibilityreadable & understandable
• Deterministicperform predictably despite unexpected inputs or user actions.
Defensive Programming
Source: https://en.wikipedia.org/wiki/Defensive_programming
41 Copyright 2016 Mark Reynolds. All rights reserved.
Defensive Example 1 - switch
Source: https://scottdorman.github.io/2008/07/04/what-is-ldquodefensive-programmingrdquo/
switch (Orientation) { case Orientation.Horizontal: break;
case Orientation.Vertical: break;
default: throw new System.ArgumentException(“Unexpected Operation); break;
}
Code that works and passes all testsBut is missing the Defense
42 Copyright 2016 Mark Reynolds. All rights reserved.
Defensive Example 2 – type cast
Source: https://scottdorman.github.io/2008/07/04/what-is-ldquodefensive-programmingrdquo/
private void button1_Click(object sender, EventArgs e){ ((Button)sender).Text = "You pressed a button";
Button button = sender as Button; if (button != null) { button.Text = "You pressed a button"; }
}
Code that works and passes all testsBut is missing the Defense
43 Copyright 2016 Mark Reynolds. All rights reserved.
Mark Reynolds
Mark Reynolds Vitae• Southwestern Energy• Lone Star College• Intent Driven Designs• Scan Systems• Sikorsky Aircraft• General Dynamics
SWN Email: [email protected]
Tulsa TechFest 2016 | Fri, Aug 5th, 2016 | OSU - Tulsa | 70+ Speakers, 20+ Tracks & 85+ Sessions!
Please Complete An Evaluation Form
Your input is important!You can access Evaluation Forms at:
http://TulsaTechFest.com
Fill them out!
You can win additional prizes!
Like a $50 Best Buy Gift Card!!
Winner drawn – Midnight, Sun Aug 7th!
Tulsa TechFest 2016 | Fri, Aug 5th, 2016 | OSU - Tulsa | 70+ Speakers, 20+ Tracks & 85+ Sessions!
Please help us!Thank our Sponsors: