SlideShare a Scribd company logo
C# CODING STANDARDS, GOOD
PROGRAMMING PRINCIPLES
&
REFACTORING
Eyob Lube
10/11/2013
Topics
1. Coding Standards
2. The Total Cost of Owning a Mess
3. Principles of Good Programming
4. General Naming Conventions
5. Capitalization Conventions
6. Capitalization Rules for Identifiers
7. Methods (Functions)
8. Bad Smells in Code
9. Refactoring
10. Tools for better coding
11. References
2
1. Coding Standards
Why do we need coding Standards ?
• First, you may not agree with everything I say… that’s ok!
• Creates a consistent look to the code, so that readers can focus on content, not layout.
• Enables readers to understand the code more quickly by making assumptions based on
previous experience.
• Facilitates copying, changing, and maintaining the code.
• Produces more stable, reliable code
• Pick a standard for your project or company and stick to it!
• Make the standard easily available to each programmer (print or online)
• Enforce via code reviews, and pair programming.
• If the standard is insufficient or is causing problems update it as needed, but it should not be
“hacked”
3
2. The Total Cost of Owning a Mess
If you have been a programmer for more than two or three years, you have
probably been significantly slowed down by someone else’s messy code. If
you have been a programmer for longer than two or three years, you have
probably been slowed down by messy code.
The degree of the slowdown can be significant. Over the span of a year or
two, teams that were moving very fast at the beginning of a project can find
themselves moving at a snail’s pace. Every change they make to the code
breaks two or three other parts of the code. No change is trivial. Every
addition or modification to the system requires that the tangles, twists, and
knots be “understood” so that more tangles, twists, and knots can be
added. Over time the mess becomes so big and so deep and so tall, they
can not clean it up. There is no way at all.
4
2. The Total Cost of Owning a Mess…
As the mess builds, the productivity of the team continues to
decrease, asymptotically approaching zero. As productivity decreases, management
does the only thing they can; they add more staff to the project in hopes of
increasing productivity. But that new staff is not versed in the design of the system.
They don’t know the difference between a change that matches the design intent
and a change that thwarts the design intent. Furthermore, they, and everyone else
on the team, are under horrific pressure to increase productivity. So they all make
more and more messes, driving the productivity ever further toward zero.(See Figure
below)
5
Productivity vs. time
Clean Code: A Handbook of Agile Software Craftsmanship
by Robert C. Martin
6
3. Principles of Good Programming
I. KISS Design Principle
"Keep it simple, Stupid!".
"keep it short and simple" or "keep it simple
and straightforward".
The KISS principle states that simplicity
should be a key goal in design, and that
unnecessary complexity should be avoided.
II. SOLID Principles of Object Oriented Design
a. The Single Responsibility Principle (SRP)
b. The Open / Closed Principle (OCP)
c. The Liskov Substitution Principle (LSP)
d. The Interface Segregation Principle (ISP)
e. The Dependency Inversion Principle (DIP)
7
a. The Single Responsibility Principle (SRP)
There should never be more than one reason for a class to change. Basically, this
means that your classes should exist for one purpose only.
8
b. The Open Closed Principle (OCP)
The Open/Closed Principle states software entities (classes, modules, functions, etc.)
should be open for extension, but closed for modification.
Wikipedia
At first, this seems to be contradictory: how can you make an object behave differently
without modifying it?
The answer: by using abstractions, or by placing behavior(responsibility) in derivative
classes. In other words, by creating base classes with override-able functions, we are
able to create new classes that do the same thing differently without changing the base
functionality.
c. The Liskov Substitution Principle (LSP)
The Liskov Substitution Principle states that Subtypes must be substitutable for their
base types.
Agile Principles, patterns and Practices in C#
Named for Barbara Liskov, who first described the principle in 1988.
9
d. The Interface Segregation Principle (ISP)
The interface Segregation Principle states that Clients should not be forced to depend on
methods they do not use.
Agile Principles, patterns and Practices in C#
Prefer small, cohesive interfaces to “fat” interfaces.
10
e. The Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend
on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Agile Principles, patterns and Practices in C#
Word Choice
Choose easily readable identifier names. For
example, a property named HorizontalAlignment is
more readable in English than AlignmentHorizontal.
Favor readability over brevity. The property name
CanScrollHorizontally is better than ScrollableX.
Do not use underscores, hyphens, or any other
nonalphanumeric characters.
4. General Naming Conventions
11
Abbreviations and Acronyms
• In general, you should not use abbreviations or
acronyms. These make your names less readable.
• Do not use abbreviations or contractions as parts
of identifier names.
• For example, use OnButtonClick rather than
OnBtnClick.
• Do not use any acronyms that are not widely
accepted, and then only when necessary.
General Naming Conventions
continued…
12
Meaningful Names
Names are everywhere in software. We name our
variables, functions, arguments, classes, packages, source files, directories…we
name and name and name. Because we do so much of it, we’d better do it well.
13
Meaningful Names…Continued
Use Intention-Revealing Names
• Choosing good names takes time but saves more than it takes. So
take care with your names and change them when you find
better ones. Everyone who reads your code (including you) will
be happier if you do.
• The name of a variable, function, or class, should answer all the
big questions. It should tell you why it exists, what it does, and
how it is used. If a name requires a comment, then the name
does not reveal its intent.
• int d; // elapsed time in days – the name d reveals nothing. It
does not evoke a sense of elapsed time, nor of days. We
should choose a name that specifies what is being measured
and the unit of that measurement.
• int elapsedTimeInDays
14
Meaningful Names…Continued
Use Intention-Revealing Names…
The varaible d could be renamed to one of the following:
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
Choosing names that reveal intent can make it much easier to understand and change
code. What is the purpose of this code?
public List<int[]> getThem()
{
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
if (x[0] == 4) list1.add(x);
return list1;
}
15
Meaningful Names…Continued
Use Intention-Revealing Names…
Why is it hard to tell what this code is doing? There are no complex expressions. Spacing
and indentation are reasonable. There are only three variables and two constants
mentioned. There aren’t even any fancy classes or polymorphic methods, just a list of
arrays (or so it seems).
The problem isn’t the simplicity of the code but the implicity of the code (to coin a
phrase): the degree to which the context is not explicit in the code itself. The code
implicitly requires that we know the answers to questions such as:
1. What kinds of things are in theList?
2. What is the significance of the zeroth subscript of an item in theList?
3. What is the significance of the value 4?
4. How would I use the list being returned?
16
Meaningful Names…Continued
Use Intention-Revealing Names…
The answers to these questions are not present in the code sample,but they could have
been. Say that we’re working in a mine sweeper game. We find that the board is a list of
cells called theList. Let’s rename that to gameBoard.
Each cell on the board is represented by a simple array. We further find that the zeroth
subscript is the location of a status value and that a status value of 4 means “flagged.” Just
by giving these concepts names we can improve the code considerably:
public List<int[]> getFlaggedCells()
{
List<int[]> flaggedCells = new ArrayList<int[]>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
17
Meaningful Names…Continued
Use Intention-Revealing Names…
Notice that the simplicity of the code has not changed. It still has exactly the same number
of operators and constants, with exactly the same number of nesting levels. But the code
has become much more explicit.
We can go further and write a simple class for cells instead of using an array of ints. It can
include an intention-revealing function (call it isFlagged) to hide the magic numbers. It
results in a new version of the function:
public List<Cell> getFlaggedCells()
{
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard)
if (cell.isFlagged())
flaggedCells.add(cell);
return flaggedCells;
}
With these simple name changes, it’s not difficult to understand what’s going on. This is
the power of choosing good names.
18
Meaningful Names…Continued
Avoid Disinformation
• Example: Do not refer to a grouping of accounts as an accountList
unless it’s actually a List. The word list means something specific to
programmers. If the container holding the accounts is not actually a
List, it may lead to false conclusions. So accountGroup or
bunchOfAccounts or just plain accounts would be better. (It’s also not
good to include the type into the name)
•A truly awful example of disinformative names would be the use of
lower-case L or uppercase O as variable names, especially in combination.
The problem, of course, is that they look almost entirely like the constants
one and zero, respectively.
int a = l;
if ( O == l )
a = O1;
else
l = 01;
19
Meaningful Names…Continued
Make Meaningful Distinctions
• It is not sufficient to add number series or noise words, even though the compiler is
satisfied. If names must be different, then they should also mean something different.
• Number-series naming (a1, a2, .. aN) is the opposite of intentional naming. Such
names are not disinformative—they are noninformative; they provide no clue to the
author’s intention.
• Consider:
• Public static void CopyChars(char a1[], char a2[])
• Public static void CopyChars(char source [], char destination [])
• Noise word are another meaningless distinctions. Imagine that you have a Product
class if you have another called ProductInfo or ProductData, you have made the names
different without making them mean anything different. Info and Data are indistinct
noise words like a, an, and the.
• Noise words are redundant. The word variable should never appear in a variable name.
The word table should never appear in a table name. How is NameString better than
Name?
Use Pronounceable Names
private Date genymdhms;
//generation date, year, month, day, hour, minute second
vs
private Date generationTimestamp
20
Meaningful Names…Continued
Compare
class DtaRcrd102
{ private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */ };
to
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;;
private final String recordId = "102";
/* ... */
};
Intelligent conversation is now possible:
“Hey, Mikey, take a look at this record! The generation timestamp is
set to tomorrow’s date! How can that be?”
21
Meaningful Names…Continued
Class Names
• Classes should have noun or noun phrase names like
Customer, WikePage, Account and AddressParser. Avoid words
like Processor, Data, or Info in the name of a class. A class name
should not be a verb.
Method Names
• Methods should have a verb or verb phrase names like
PostPayment, DeletePage, or SaveAccessors.
22
5. Capitalization Conventions
Casing Styles
The following terms describe different ways to case identifiers.
Pascal Casing
The first letter in the identifier and the first letter of each
subsequent concatenated word are capitalized. You can use Pascal
case for identifiers of three or more characters.
For example: BackColor
Camel Casing
The first letter of an identifier is lowercase and the first letter of
each subsequent concatenated word is capitalized.
For example: backColor
Uppercase
All letters in the identifier are capitalized.
For example: IO
23
6. Capitalization Rules for Identifiers
Identifier Case Example
Class Pascal AppDomain
Enumeration type Pascal ErrorLevel
Enumeration values Pascal FatalError
Event Pascal ValueChanged
Exception class Pascal WebException
Read-only static field Pascal RedValue
Interface Pascal IDisposable
Method Pascal ToString
Namespace Pascal System.Drawing
Parameter Camel typeName
Property Pascal BackColor 24
7. Methods (Functions)
• Should be very small (20 – 30 lines max ,not more
than 1 screen)
• Do one thing
• Use Descriptive Names
• Ideal number of arguments for a function is zero. Next
comes one, followed closely by two. Three arguments
should be avoided where possible.
• Prefer to pass by using a class variable instead of listing
5 or 10 function arguments.
• Arguments are hard they take a lot of conceptual
power.
• Delete commented out dead code, if anyone really
needs it, he should go back and check out a previous
version.
25
8. Bad Smells in Code
1. Duplicated Code
2. Long Method
3. Large Class
4. Long Parameter List
26
9. Refactoring
Refactoring is the process of improving your code after it has been written
by changing the internal structure of the code without changing the
external behavior of the code.
Reasons for Refactoring Code
1. Consolidating and eliminating “Like” or “Similar” Code
2. Breaking out an extraordinary long function into more manageable bites
3. Make error trapping easier to handle
4. Make code more readable and maintainable
5. Removing nested IF or logic Loops
6. Make it easier to document
7. Create Reusable code
8. Better class and function cohesion.
The benefits now are the following:
1. Similar code is now the same which is the way it was meant to be.
2. Since the code had the same purpose, it looks the same now and
behaves the same.
3. Code is in one spot instead of 5 – makes it easier for a base change
4. Error trapping is much more controlled.
27
10. Tools for better coding
1. Visual Studio
2. Resharper
3. Code Analysis
4. PowerCommands
5. FxCop
28
11. References
1. C# Coding Conventions (C# Programming Guide)
2. All-In-One Code Framework Coding Standards
3. Importance of Code Refactoring
4. Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
5. Refactoring: Improving the Design of Existing Code by Martin Fowler
6. .NET Coding Standards For The Real World (2012) by David McCarter on Jan 27, 2012
7. http://pluralsight.com/training
8. The S.O.L.I.D. Object Oriented Programming(OOP) Principles
9. Agile Priniciples, Patterns and Practices in C# By Robert C. Martin and Micah Martin
10. KISS principle
11. SingleResponsibilityPrinciple image
12. The Interface Segregation Principle (ISP) image
13. Dependency Inversion Principle (DIP) image
29
Q & A
THANK YOU!
30
Ad

Recommended

C# conventions & good practices
C# conventions & good practices
Tan Tran
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
Coding Best Practices
Coding Best Practices
mh_azad
 
Coding standard
Coding standard
Shwetketu Rastogi
 
Writing High Quality Code in C#
Writing High Quality Code in C#
Svetlin Nakov
 
Clean code
Clean code
ifnu bima
 
Clean code slide
Clean code slide
Anh Huan Miu
 
Clean code
Clean code
Alvaro García Loaisa
 
Software development best practices & coding guidelines
Software development best practices & coding guidelines
Ankur Goyal
 
Coding standards and guidelines
Coding standards and guidelines
brijraj_singh
 
The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Clean code
Clean code
Arturo Herrero
 
Best coding practices
Best coding practices
baabtra.com - No. 1 supplier of quality freshers
 
Java script arrays
Java script arrays
Frayosh Wadia
 
Coding standards
Coding standards
Mark Reynolds
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Clean Code I - Best Practices
Clean Code I - Best Practices
Theo Jungeblut
 
Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
Javascript
Javascript
mussawir20
 
Code Refactoring Cheatsheet
Code Refactoring Cheatsheet
Rachanee Saengkrajai
 
C# classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Coding standards
Coding standards
Mimoh Ojha
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Coding conventions
Coding conventions
systemcrashed
 
Arrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
Decision making and loop in C#
Decision making and loop in C#
Prasanna Kumar SM
 
Clean code
Clean code
Henrique Smoco
 
Introduction to kotlin
Introduction to kotlin
NAVER Engineering
 
Writing clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Automating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCop
BlackRabbitCoder
 

More Related Content

What's hot (20)

Software development best practices & coding guidelines
Software development best practices & coding guidelines
Ankur Goyal
 
Coding standards and guidelines
Coding standards and guidelines
brijraj_singh
 
The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Clean code
Clean code
Arturo Herrero
 
Best coding practices
Best coding practices
baabtra.com - No. 1 supplier of quality freshers
 
Java script arrays
Java script arrays
Frayosh Wadia
 
Coding standards
Coding standards
Mark Reynolds
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Clean Code I - Best Practices
Clean Code I - Best Practices
Theo Jungeblut
 
Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
Javascript
Javascript
mussawir20
 
Code Refactoring Cheatsheet
Code Refactoring Cheatsheet
Rachanee Saengkrajai
 
C# classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Coding standards
Coding standards
Mimoh Ojha
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Coding conventions
Coding conventions
systemcrashed
 
Arrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
Decision making and loop in C#
Decision making and loop in C#
Prasanna Kumar SM
 
Clean code
Clean code
Henrique Smoco
 
Introduction to kotlin
Introduction to kotlin
NAVER Engineering
 

Viewers also liked (20)

Writing clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Automating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCop
BlackRabbitCoder
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
C#/.NET Little Pitfalls
C#/.NET Little Pitfalls
BlackRabbitCoder
 
Presentation refactoring large legacy applications
Presentation refactoring large legacy applications
Jorge Capel Planells
 
Principles of programming
Principles of programming
Rob Paok
 
Cmp2412 programming principles
Cmp2412 programming principles
NIKANOR THOMAS
 
Clean code em C#
Clean code em C#
Gustavo Araújo
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Car Decals
Car Decals
TomasSFailla
 
Ficha de videos
Ficha de videos
Maria Ramirez
 
Resharper
Resharper
Hanokh Aloni
 
Docker workflow
Docker workflow
Sion Williams
 
The Little Wonders of C# 6
The Little Wonders of C# 6
BlackRabbitCoder
 
Clean Code
Clean Code
Bruno Lui
 
24 Resharper Tricks Every .Net Developer Should Know
24 Resharper Tricks Every .Net Developer Should Know
Lee Richardson
 
Developer workflow with docker
Developer workflow with docker
Lalatendu Mohanty
 
Windows Phone Application Development
Windows Phone Application Development
Jaliya Udagedara
 
C# 7
C# 7
Mike Harris
 
Developing multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd edition
Steve Xu
 
Writing clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Automating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCop
BlackRabbitCoder
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
Presentation refactoring large legacy applications
Presentation refactoring large legacy applications
Jorge Capel Planells
 
Principles of programming
Principles of programming
Rob Paok
 
Cmp2412 programming principles
Cmp2412 programming principles
NIKANOR THOMAS
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
The Little Wonders of C# 6
The Little Wonders of C# 6
BlackRabbitCoder
 
24 Resharper Tricks Every .Net Developer Should Know
24 Resharper Tricks Every .Net Developer Should Know
Lee Richardson
 
Developer workflow with docker
Developer workflow with docker
Lalatendu Mohanty
 
Windows Phone Application Development
Windows Phone Application Development
Jaliya Udagedara
 
Developing multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd edition
Steve Xu
 
Ad

Similar to C# coding standards, good programming principles & refactoring (20)

Clean code and code smells
Clean code and code smells
Md. Aftab Uddin Kajal
 
Naming Things (with notes)
Naming Things (with notes)
Pete Nicholls
 
What's in a name
What's in a name
Koby Fruchtnis
 
Coding Standards
Coding Standards
Jeevitesh Ms
 
Naming Standards, Clean Code
Naming Standards, Clean Code
CleanestCode
 
Clean Code
Clean Code
Chris Farrell
 
Clean Code - Writing code for human
Clean Code - Writing code for human
NETKO Solution
 
Lecture No 13.ppt
Lecture No 13.ppt
AhmadNaeem59
 
Clean code
Clean code
Simon Sönnby
 
Naming Things
Naming Things
Pete Nicholls
 
Perfect Code
Perfect Code
Artem Tabalin
 
Clean code
Clean code
Uday Pratap Singh
 
Variables
Variables
Maha Saad
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
Nick Pruehs
 
Software Design
Software Design
Ahmed Misbah
 
Clean code: meaningful Name
Clean code: meaningful Name
nahid035
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Naming guidelines for professional programmers
Naming guidelines for professional programmers
Peter Hilton
 
Programming style guildelines
Programming style guildelines
Rich Nguyen
 
Naming Conventions
Naming Conventions
Pubudu Bandara
 
Naming Things (with notes)
Naming Things (with notes)
Pete Nicholls
 
Naming Standards, Clean Code
Naming Standards, Clean Code
CleanestCode
 
Clean Code - Writing code for human
Clean Code - Writing code for human
NETKO Solution
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
Nick Pruehs
 
Clean code: meaningful Name
Clean code: meaningful Name
nahid035
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Naming guidelines for professional programmers
Naming guidelines for professional programmers
Peter Hilton
 
Programming style guildelines
Programming style guildelines
Rich Nguyen
 
Ad

Recently uploaded (20)

Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 

C# coding standards, good programming principles & refactoring

  • 1. C# CODING STANDARDS, GOOD PROGRAMMING PRINCIPLES & REFACTORING Eyob Lube 10/11/2013
  • 2. Topics 1. Coding Standards 2. The Total Cost of Owning a Mess 3. Principles of Good Programming 4. General Naming Conventions 5. Capitalization Conventions 6. Capitalization Rules for Identifiers 7. Methods (Functions) 8. Bad Smells in Code 9. Refactoring 10. Tools for better coding 11. References 2
  • 3. 1. Coding Standards Why do we need coding Standards ? • First, you may not agree with everything I say… that’s ok! • Creates a consistent look to the code, so that readers can focus on content, not layout. • Enables readers to understand the code more quickly by making assumptions based on previous experience. • Facilitates copying, changing, and maintaining the code. • Produces more stable, reliable code • Pick a standard for your project or company and stick to it! • Make the standard easily available to each programmer (print or online) • Enforce via code reviews, and pair programming. • If the standard is insufficient or is causing problems update it as needed, but it should not be “hacked” 3
  • 4. 2. The Total Cost of Owning a Mess If you have been a programmer for more than two or three years, you have probably been significantly slowed down by someone else’s messy code. If you have been a programmer for longer than two or three years, you have probably been slowed down by messy code. The degree of the slowdown can be significant. Over the span of a year or two, teams that were moving very fast at the beginning of a project can find themselves moving at a snail’s pace. Every change they make to the code breaks two or three other parts of the code. No change is trivial. Every addition or modification to the system requires that the tangles, twists, and knots be “understood” so that more tangles, twists, and knots can be added. Over time the mess becomes so big and so deep and so tall, they can not clean it up. There is no way at all. 4
  • 5. 2. The Total Cost of Owning a Mess… As the mess builds, the productivity of the team continues to decrease, asymptotically approaching zero. As productivity decreases, management does the only thing they can; they add more staff to the project in hopes of increasing productivity. But that new staff is not versed in the design of the system. They don’t know the difference between a change that matches the design intent and a change that thwarts the design intent. Furthermore, they, and everyone else on the team, are under horrific pressure to increase productivity. So they all make more and more messes, driving the productivity ever further toward zero.(See Figure below) 5 Productivity vs. time Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
  • 6. 6 3. Principles of Good Programming I. KISS Design Principle "Keep it simple, Stupid!". "keep it short and simple" or "keep it simple and straightforward". The KISS principle states that simplicity should be a key goal in design, and that unnecessary complexity should be avoided. II. SOLID Principles of Object Oriented Design a. The Single Responsibility Principle (SRP) b. The Open / Closed Principle (OCP) c. The Liskov Substitution Principle (LSP) d. The Interface Segregation Principle (ISP) e. The Dependency Inversion Principle (DIP)
  • 7. 7 a. The Single Responsibility Principle (SRP) There should never be more than one reason for a class to change. Basically, this means that your classes should exist for one purpose only.
  • 8. 8 b. The Open Closed Principle (OCP) The Open/Closed Principle states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Wikipedia At first, this seems to be contradictory: how can you make an object behave differently without modifying it? The answer: by using abstractions, or by placing behavior(responsibility) in derivative classes. In other words, by creating base classes with override-able functions, we are able to create new classes that do the same thing differently without changing the base functionality. c. The Liskov Substitution Principle (LSP) The Liskov Substitution Principle states that Subtypes must be substitutable for their base types. Agile Principles, patterns and Practices in C# Named for Barbara Liskov, who first described the principle in 1988.
  • 9. 9 d. The Interface Segregation Principle (ISP) The interface Segregation Principle states that Clients should not be forced to depend on methods they do not use. Agile Principles, patterns and Practices in C# Prefer small, cohesive interfaces to “fat” interfaces.
  • 10. 10 e. The Dependency Inversion Principle (DIP) High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions. Agile Principles, patterns and Practices in C#
  • 11. Word Choice Choose easily readable identifier names. For example, a property named HorizontalAlignment is more readable in English than AlignmentHorizontal. Favor readability over brevity. The property name CanScrollHorizontally is better than ScrollableX. Do not use underscores, hyphens, or any other nonalphanumeric characters. 4. General Naming Conventions 11
  • 12. Abbreviations and Acronyms • In general, you should not use abbreviations or acronyms. These make your names less readable. • Do not use abbreviations or contractions as parts of identifier names. • For example, use OnButtonClick rather than OnBtnClick. • Do not use any acronyms that are not widely accepted, and then only when necessary. General Naming Conventions continued… 12
  • 13. Meaningful Names Names are everywhere in software. We name our variables, functions, arguments, classes, packages, source files, directories…we name and name and name. Because we do so much of it, we’d better do it well. 13
  • 14. Meaningful Names…Continued Use Intention-Revealing Names • Choosing good names takes time but saves more than it takes. So take care with your names and change them when you find better ones. Everyone who reads your code (including you) will be happier if you do. • The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. • int d; // elapsed time in days – the name d reveals nothing. It does not evoke a sense of elapsed time, nor of days. We should choose a name that specifies what is being measured and the unit of that measurement. • int elapsedTimeInDays 14
  • 15. Meaningful Names…Continued Use Intention-Revealing Names… The varaible d could be renamed to one of the following: int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification; int fileAgeInDays; Choosing names that reveal intent can make it much easier to understand and change code. What is the purpose of this code? public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; } 15
  • 16. Meaningful Names…Continued Use Intention-Revealing Names… Why is it hard to tell what this code is doing? There are no complex expressions. Spacing and indentation are reasonable. There are only three variables and two constants mentioned. There aren’t even any fancy classes or polymorphic methods, just a list of arrays (or so it seems). The problem isn’t the simplicity of the code but the implicity of the code (to coin a phrase): the degree to which the context is not explicit in the code itself. The code implicitly requires that we know the answers to questions such as: 1. What kinds of things are in theList? 2. What is the significance of the zeroth subscript of an item in theList? 3. What is the significance of the value 4? 4. How would I use the list being returned? 16
  • 17. Meaningful Names…Continued Use Intention-Revealing Names… The answers to these questions are not present in the code sample,but they could have been. Say that we’re working in a mine sweeper game. We find that the board is a list of cells called theList. Let’s rename that to gameBoard. Each cell on the board is represented by a simple array. We further find that the zeroth subscript is the location of a status value and that a status value of 4 means “flagged.” Just by giving these concepts names we can improve the code considerably: public List<int[]> getFlaggedCells() { List<int[]> flaggedCells = new ArrayList<int[]>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; } 17
  • 18. Meaningful Names…Continued Use Intention-Revealing Names… Notice that the simplicity of the code has not changed. It still has exactly the same number of operators and constants, with exactly the same number of nesting levels. But the code has become much more explicit. We can go further and write a simple class for cells instead of using an array of ints. It can include an intention-revealing function (call it isFlagged) to hide the magic numbers. It results in a new version of the function: public List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) if (cell.isFlagged()) flaggedCells.add(cell); return flaggedCells; } With these simple name changes, it’s not difficult to understand what’s going on. This is the power of choosing good names. 18
  • 19. Meaningful Names…Continued Avoid Disinformation • Example: Do not refer to a grouping of accounts as an accountList unless it’s actually a List. The word list means something specific to programmers. If the container holding the accounts is not actually a List, it may lead to false conclusions. So accountGroup or bunchOfAccounts or just plain accounts would be better. (It’s also not good to include the type into the name) •A truly awful example of disinformative names would be the use of lower-case L or uppercase O as variable names, especially in combination. The problem, of course, is that they look almost entirely like the constants one and zero, respectively. int a = l; if ( O == l ) a = O1; else l = 01; 19
  • 20. Meaningful Names…Continued Make Meaningful Distinctions • It is not sufficient to add number series or noise words, even though the compiler is satisfied. If names must be different, then they should also mean something different. • Number-series naming (a1, a2, .. aN) is the opposite of intentional naming. Such names are not disinformative—they are noninformative; they provide no clue to the author’s intention. • Consider: • Public static void CopyChars(char a1[], char a2[]) • Public static void CopyChars(char source [], char destination []) • Noise word are another meaningless distinctions. Imagine that you have a Product class if you have another called ProductInfo or ProductData, you have made the names different without making them mean anything different. Info and Data are indistinct noise words like a, an, and the. • Noise words are redundant. The word variable should never appear in a variable name. The word table should never appear in a table name. How is NameString better than Name? Use Pronounceable Names private Date genymdhms; //generation date, year, month, day, hour, minute second vs private Date generationTimestamp 20
  • 21. Meaningful Names…Continued Compare class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ }; to class Customer { private Date generationTimestamp; private Date modificationTimestamp;; private final String recordId = "102"; /* ... */ }; Intelligent conversation is now possible: “Hey, Mikey, take a look at this record! The generation timestamp is set to tomorrow’s date! How can that be?” 21
  • 22. Meaningful Names…Continued Class Names • Classes should have noun or noun phrase names like Customer, WikePage, Account and AddressParser. Avoid words like Processor, Data, or Info in the name of a class. A class name should not be a verb. Method Names • Methods should have a verb or verb phrase names like PostPayment, DeletePage, or SaveAccessors. 22
  • 23. 5. Capitalization Conventions Casing Styles The following terms describe different ways to case identifiers. Pascal Casing The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example: BackColor Camel Casing The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example: backColor Uppercase All letters in the identifier are capitalized. For example: IO 23
  • 24. 6. Capitalization Rules for Identifiers Identifier Case Example Class Pascal AppDomain Enumeration type Pascal ErrorLevel Enumeration values Pascal FatalError Event Pascal ValueChanged Exception class Pascal WebException Read-only static field Pascal RedValue Interface Pascal IDisposable Method Pascal ToString Namespace Pascal System.Drawing Parameter Camel typeName Property Pascal BackColor 24
  • 25. 7. Methods (Functions) • Should be very small (20 – 30 lines max ,not more than 1 screen) • Do one thing • Use Descriptive Names • Ideal number of arguments for a function is zero. Next comes one, followed closely by two. Three arguments should be avoided where possible. • Prefer to pass by using a class variable instead of listing 5 or 10 function arguments. • Arguments are hard they take a lot of conceptual power. • Delete commented out dead code, if anyone really needs it, he should go back and check out a previous version. 25
  • 26. 8. Bad Smells in Code 1. Duplicated Code 2. Long Method 3. Large Class 4. Long Parameter List 26
  • 27. 9. Refactoring Refactoring is the process of improving your code after it has been written by changing the internal structure of the code without changing the external behavior of the code. Reasons for Refactoring Code 1. Consolidating and eliminating “Like” or “Similar” Code 2. Breaking out an extraordinary long function into more manageable bites 3. Make error trapping easier to handle 4. Make code more readable and maintainable 5. Removing nested IF or logic Loops 6. Make it easier to document 7. Create Reusable code 8. Better class and function cohesion. The benefits now are the following: 1. Similar code is now the same which is the way it was meant to be. 2. Since the code had the same purpose, it looks the same now and behaves the same. 3. Code is in one spot instead of 5 – makes it easier for a base change 4. Error trapping is much more controlled. 27
  • 28. 10. Tools for better coding 1. Visual Studio 2. Resharper 3. Code Analysis 4. PowerCommands 5. FxCop 28
  • 29. 11. References 1. C# Coding Conventions (C# Programming Guide) 2. All-In-One Code Framework Coding Standards 3. Importance of Code Refactoring 4. Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin 5. Refactoring: Improving the Design of Existing Code by Martin Fowler 6. .NET Coding Standards For The Real World (2012) by David McCarter on Jan 27, 2012 7. http://pluralsight.com/training 8. The S.O.L.I.D. Object Oriented Programming(OOP) Principles 9. Agile Priniciples, Patterns and Practices in C# By Robert C. Martin and Micah Martin 10. KISS principle 11. SingleResponsibilityPrinciple image 12. The Interface Segregation Principle (ISP) image 13. Dependency Inversion Principle (DIP) image 29
  • 30. Q & A THANK YOU! 30

Editor's Notes

  • #2: This template can be used as a starter file for presenting training materials in a group setting.SectionsRight-click on a slide to add sections. Sections can help to organize your slides or facilitate collaboration between multiple authors.NotesUse the Notes section for delivery notes or to provide additional details for the audience. View these notes in Presentation View during your presentation. Keep in mind the font size (important for accessibility, visibility, videotaping, and online production)Coordinated colors Pay particular attention to the graphs, charts, and text boxes.Consider that attendees will print in black and white or grayscale. Run a test print to make sure your colors work when printed in pure black and white and grayscale.Graphics, tables, and graphsKeep it simple: If possible, use consistent, non-distracting styles and colors.Label all graphs and tables.
  • #3: Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  • #4: Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  • #5: Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  • #6: Give a brief overview of the presentation. Describe the major focus of the presentation and why it is important.Introduce each of the major topics.To provide a road map for the audience, you can repeat this Overview slide throughout the presentation, highlighting the particular topic you will discuss next.
  • #7: This is another option for an Overview slides using transitions.