SlideShare a Scribd company logo
1 of 49
Writing Clean Code in C# and .NET
About.ME
• Senior Consultant @CodeValue
• Developing software (Professionally) since 2002
• Writing clean code since 2009
• Blogger: http://blog.drorhelper.com
Let’s talk about software bugs
Bugs cost around $312 Billion Per Year
And it’s all a developer’s fault
The cost of fixing bugs
1 2 10
20
50
150
RQUIRMENTS DESIGN CODE DEV T ACC T OPERATION
[B. Boehm - ICSE 2006 Keynote Address]
High quality code is:
• Easy to read and understand
• Impossible to hide bugs
• Easy to extend
• Easy to change
• Has unit tests
Be a proud of your code
Broken windows
The cost of owning a mess
0
10
20
30
40
50
60
70
80
90
100
Productivity
Productivity
[Robert Martin – “Clean Code”]
Quality == Agility
• Adapt to changes
• Don’t be held back by bugs
• Cannot be agile without high quality code
How a developer spends his time
60% - 80% time spent in understanding code
So make sure your code is readable
But what is a readable code?
“Always code as if the guy who ends up
maintaining your code will be a violent
psychopath who knows where you live”
Megamoth
Stands for MEGA MOnolithic meTHod.
Often contained inside a God Object, and
usually stretches over two screens in height.
Megamoths of greater size than 2k LOC have
been sighted. Beware of the MEGAMOTH!
http://blog.codinghorror.com/new-programming-jargon/
Write short methods – please!
• It’s easier to understand
• Performance won’t suffer
• Avoid mixing abstraction layers
• Enable re-use
• Also write small classes
How can we recognize bad code?
• You know it we you see it
• You feel it when you write it
• You get used to it after a while 
• known as Code Smells
Code Smells
• Duplicate code
• Long method
• Large class
• Too many parameters
• Feature envy
• Inappropriate intimacy
• Refused request
• Lazy class/Freeloader
• Contrived complexity
• Naming!
• Complex Conditionals
• And more…
http://en.wikipedia.org/wiki/Code_smell
Comments often are used as a deodorant
Refactoring, Martin Fowler
Comments are a dead giveaway
• If explains how things done means that the
developer felt bad about the code
• “Code title” – should be a method
• Commented Old code – SCM
Good comments exist in the wild – but rare
http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-
source-code-you-have-ever-encountered
/// <summary>
/// Gets or sets the name of the first.
/// </summary>
/// <value>The name of the first.</value>
public string FirstName
}
get { return _firstName; }
set { _firstName = value; }
{
/** Logger */
private Logger logger = Logger.getLogger();
/// <summary>
/// The possible outcomes of an update
operation (save or delete)
/// </summary>
public enum UpdateResult
}
/// <summary>
/// Updated successfully
/// </summary>
Success = 0,
/// <summary>
/// Updated successfully
/// </summary>
Failed = 1
{
//private instance variable for storing age
public static int age;
// Always returns true.
public bool isAvailable()
}
return false;
{
Regions == Comments
Naming is important
d, days  daysSinceLastPayment
customerPo  customerPurchaseOrder
productIdString  productId
genymdhms  generationTimeStamp
Dead Code
• Code which is never run
• But still has maintenance costs
• Solution - delete
Undead Code
Dead code that you’re afraid to delete
- “I might need this…”
geek-and-poke.com/
// UNUSED
// Separate into p_slidoor.c?
#if 0 // ABANDONED TO THE MISTS OF TIME!!!
//
// EV_SlidingDoor : slide a door horizontally
// (animate midtexture, then set noblocking line)
//
Avoid duplicate code (DRY)
“Every piece of knowledge must have a
single, unambiguous, authoritative
representation within a system”
The Pragmatic Programmer: Dave Thomas, Andy Hunt
public bool HasGroup(List<Token> tokenList){
for(Token token : tokemList){
if(token.get_group() != null) {
return true;
{
{
return false;
{
public Group GetValidGroup(List<Customer> customers){
for(Customer customer : customers){
Group group = customer.get_group();
if(group != null) {
return group;
{
{
return null;
{
Good code start with good design
Bad DesignGood design
RigidLoosely coupled
FragileHighly cohesive
ImmobileEasily composable
ViscousContext independent
It’s all about dependencies
• In .NET Reference == dependency
• Change in dependency  change in code
This is not OOP!!!
public class Record_Base
{
public DateTime RecordDateTime
{
get { return _recordDateTime; }
set
{
if (this.GetType().Name == "Record_PartRegister")
_recordDateTime = value;
else
throw new Exception("Cannot call set on RecordDateTime for table " + this.GetType().Name);
}
}
}
http://thedailywtf.com/Articles/Making-Off-With-Your-Inheritance.aspx
Design stamina hypothesis
http://martinfowler.com/bliki/DesignStaminaHypothesis.html
Principles of Object Oriented Design
Single responsibility
Open/closed
Liskov substitution
Interface segregation
Dependency inversion
www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
Single responsibility
A class should have one, and only one,
reason to change.
http://www.amazon.com/Wenger- 16999-ssiwS-efinK-
B/pd/tnaiG001 DZTJRQ/
Naming as code smell
Having difficulties naming your class/method?
You might be violating SRP
public interface ITimerService
{
IDisposable SetTimout(long durationMilliSeconds, Action callback);
Task Delay(TimeSpan delay, CancellationToken token);
void KillLastSetTimer();
}
public interface IDispacherTimerService : ITimerService
{
long GetMilisecondsFromLastStart();
}
public interface IElapsedTimerService : ITimerService
{
void SetTimout(long durationMilliSeconds, Action<TimeSpan> callback);
}
Open closed principle
software entities should be
open for extension,
but
closed for modification
Liskov subtitution
objects in a program should
be replaceable with instances of their
subtypes
without altering the correctness of that
program
LSP smell - look for type checking
void ArrangeBirdInPattern(IBird aBird)
}
var aPenguin = aBird as Pinguin;
if (aPenguin != null)
}
ArrangeBirdOnGround(aPenguin);
{
else
}
ArrangeBirdInSky(aBird);
{
// What about Emu?
{
Interface segregation
Many client specific interfaces are better than
one general purpose interface.
http://en.wikipedia.org/wiki/Cockpit
Dependency Inversion
Depend upon abstractions.
Do not depend upon concretions.
Your code will change!
• Requirements change
• Bugs are found
• New feature requests
 Your design will change
In the beginning…
Application was beautiful - then came change…
• Software Rot
– Duplication
– Excess coupling
– Quick fixes
– Hacks
public override void HandleActionRejected(User from, reason reason)
}
Logger.Info("HandleActionRejected - user:{0}", from.Id);
/*foreach (var user in UserRepository.GetAllUsers)
}
Client.SendInfo(user, from, reason);
{ */
//2.2
Events.Users.Value = new UserData
}
SessionId = CurrentSession.Id,
HaveIInitiated = true,
OtherUser = from,
StartCallStatus = Events.ConvertToCallStatus(answer)
{;
UserRepository.Remove(from, reason);
if(UserRepository.IsEmpty())
}
Exit();
{
{
Refactoring
Refactoring
“a disciplined technique for restructuring
an existing body of code, altering its
internal structure without changing its
external behavior”
- Martin Fowler
http://refactoring.com/catalog/
Refactoring with Visual Studio
Code reviews
Can catch up to 60% of defects
Effective code reviews are:
• Short – don’t waste time
• Constructive
• Avoid emotionally draining arguments
Everybody reviews and everybody is reviewed
No quality has very high cost
Never have time to do it,
but always have time to re-do it.
Explain why this feature takes so much time
“You rush a miracle man,
you get rotten miracles.”
Don’t expect your company to force you
Be a professional
Care about your code
Improve your code
• Start as soon as you can
• Don’t compromise
Schedule time for quality
–Improve existing code
–Make it work, then make it better
49
Writing clean code in C# and .NET

More Related Content

What's hot

Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
Clean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipClean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipTheo Jungeblut
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practicesTan Tran
 

What's hot (20)

Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Clean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipClean Code III - Software Craftsmanship
Clean Code III - Software Craftsmanship
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Clean code
Clean codeClean code
Clean code
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
 

Similar to Writing clean code in C# and .NET

How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Old code doesn't stink - Detroit
Old code doesn't stink - DetroitOld code doesn't stink - Detroit
Old code doesn't stink - DetroitMartin Gutenbrunner
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality codeHayden Bleasel
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Writing code for others
Writing code for othersWriting code for others
Writing code for othersAmol Pujari
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsLewis Ardern
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampTheo Jungeblut
 
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0Marcel Bruch
 
NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET Dmytro Mindra
 
Enhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code ContractsEnhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code ContractsEran Stiller
 
Rooted con 2020 - from the heaven to hell in the CI - CD
Rooted con 2020 - from the heaven to hell in the CI - CDRooted con 2020 - from the heaven to hell in the CI - CD
Rooted con 2020 - from the heaven to hell in the CI - CDDaniel Garcia (a.k.a cr0hn)
 
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkTaming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkJoseph Yoder
 
Finding Needles in Haystacks
Finding Needles in HaystacksFinding Needles in Haystacks
Finding Needles in Haystackssnyff
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsVitali Pekelis
 
API Design - developing for developers
API Design - developing for developersAPI Design - developing for developers
API Design - developing for developersJoy George
 
Sandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedSandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedMinded Security
 

Similar to Writing clean code in C# and .NET (20)

How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Old code doesn't stink - Detroit
Old code doesn't stink - DetroitOld code doesn't stink - Detroit
Old code doesn't stink - Detroit
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality code
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Writing code for others
Writing code for othersWriting code for others
Writing code for others
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript Applications
 
Old code doesn't stink
Old code doesn't stinkOld code doesn't stink
Old code doesn't stink
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp
 
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
 
NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
 
Enhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code ContractsEnhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code Contracts
 
Rooted con 2020 - from the heaven to hell in the CI - CD
Rooted con 2020 - from the heaven to hell in the CI - CDRooted con 2020 - from the heaven to hell in the CI - CD
Rooted con 2020 - from the heaven to hell in the CI - CD
 
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkTaming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
 
Finding Needles in Haystacks
Finding Needles in HaystacksFinding Needles in Haystacks
Finding Needles in Haystacks
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
API Design - developing for developers
API Design - developing for developersAPI Design - developing for developers
API Design - developing for developers
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Sandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedSandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession Learned
 

More from Dror Helper

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutDror Helper
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Dror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with awsDror Helper
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutDror Helper
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agileDror Helper
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreDror Helper
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET coreDror Helper
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot netDror Helper
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyDror Helper
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy codeDror Helper
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowDror Helper
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing toolsDror Helper
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developersDror Helper
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbgDror Helper
 

More from Dror Helper (20)

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with aws
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agile
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net core
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET core
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot net
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the ugly
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should know
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing tools
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developers
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
 

Recently uploaded

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Recently uploaded (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Writing clean code in C# and .NET

  • 1. Writing Clean Code in C# and .NET
  • 2. About.ME • Senior Consultant @CodeValue • Developing software (Professionally) since 2002 • Writing clean code since 2009 • Blogger: http://blog.drorhelper.com
  • 3. Let’s talk about software bugs
  • 4. Bugs cost around $312 Billion Per Year
  • 5. And it’s all a developer’s fault
  • 6. The cost of fixing bugs 1 2 10 20 50 150 RQUIRMENTS DESIGN CODE DEV T ACC T OPERATION [B. Boehm - ICSE 2006 Keynote Address]
  • 7. High quality code is: • Easy to read and understand • Impossible to hide bugs • Easy to extend • Easy to change • Has unit tests Be a proud of your code
  • 9. The cost of owning a mess 0 10 20 30 40 50 60 70 80 90 100 Productivity Productivity [Robert Martin – “Clean Code”]
  • 10. Quality == Agility • Adapt to changes • Don’t be held back by bugs • Cannot be agile without high quality code
  • 11. How a developer spends his time 60% - 80% time spent in understanding code So make sure your code is readable But what is a readable code?
  • 12. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live”
  • 13. Megamoth Stands for MEGA MOnolithic meTHod. Often contained inside a God Object, and usually stretches over two screens in height. Megamoths of greater size than 2k LOC have been sighted. Beware of the MEGAMOTH! http://blog.codinghorror.com/new-programming-jargon/
  • 14. Write short methods – please! • It’s easier to understand • Performance won’t suffer • Avoid mixing abstraction layers • Enable re-use • Also write small classes
  • 15. How can we recognize bad code? • You know it we you see it • You feel it when you write it • You get used to it after a while  • known as Code Smells
  • 16. Code Smells • Duplicate code • Long method • Large class • Too many parameters • Feature envy • Inappropriate intimacy • Refused request • Lazy class/Freeloader • Contrived complexity • Naming! • Complex Conditionals • And more… http://en.wikipedia.org/wiki/Code_smell
  • 17. Comments often are used as a deodorant Refactoring, Martin Fowler
  • 18. Comments are a dead giveaway • If explains how things done means that the developer felt bad about the code • “Code title” – should be a method • Commented Old code – SCM Good comments exist in the wild – but rare
  • 19. http://stackoverflow.com/questions/184618/what-is-the-best-comment-in- source-code-you-have-ever-encountered /// <summary> /// Gets or sets the name of the first. /// </summary> /// <value>The name of the first.</value> public string FirstName } get { return _firstName; } set { _firstName = value; } { /** Logger */ private Logger logger = Logger.getLogger(); /// <summary> /// The possible outcomes of an update operation (save or delete) /// </summary> public enum UpdateResult } /// <summary> /// Updated successfully /// </summary> Success = 0, /// <summary> /// Updated successfully /// </summary> Failed = 1 { //private instance variable for storing age public static int age; // Always returns true. public bool isAvailable() } return false; {
  • 21. Naming is important d, days  daysSinceLastPayment customerPo  customerPurchaseOrder productIdString  productId genymdhms  generationTimeStamp
  • 22. Dead Code • Code which is never run • But still has maintenance costs • Solution - delete
  • 23. Undead Code Dead code that you’re afraid to delete - “I might need this…” geek-and-poke.com/ // UNUSED // Separate into p_slidoor.c? #if 0 // ABANDONED TO THE MISTS OF TIME!!! // // EV_SlidingDoor : slide a door horizontally // (animate midtexture, then set noblocking line) //
  • 24. Avoid duplicate code (DRY) “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system” The Pragmatic Programmer: Dave Thomas, Andy Hunt
  • 25. public bool HasGroup(List<Token> tokenList){ for(Token token : tokemList){ if(token.get_group() != null) { return true; { { return false; { public Group GetValidGroup(List<Customer> customers){ for(Customer customer : customers){ Group group = customer.get_group(); if(group != null) { return group; { { return null; {
  • 26. Good code start with good design Bad DesignGood design RigidLoosely coupled FragileHighly cohesive ImmobileEasily composable ViscousContext independent It’s all about dependencies • In .NET Reference == dependency • Change in dependency  change in code
  • 27. This is not OOP!!! public class Record_Base { public DateTime RecordDateTime { get { return _recordDateTime; } set { if (this.GetType().Name == "Record_PartRegister") _recordDateTime = value; else throw new Exception("Cannot call set on RecordDateTime for table " + this.GetType().Name); } } } http://thedailywtf.com/Articles/Making-Off-With-Your-Inheritance.aspx
  • 29. Principles of Object Oriented Design Single responsibility Open/closed Liskov substitution Interface segregation Dependency inversion www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
  • 30. Single responsibility A class should have one, and only one, reason to change. http://www.amazon.com/Wenger- 16999-ssiwS-efinK- B/pd/tnaiG001 DZTJRQ/
  • 31. Naming as code smell Having difficulties naming your class/method? You might be violating SRP
  • 32. public interface ITimerService { IDisposable SetTimout(long durationMilliSeconds, Action callback); Task Delay(TimeSpan delay, CancellationToken token); void KillLastSetTimer(); } public interface IDispacherTimerService : ITimerService { long GetMilisecondsFromLastStart(); } public interface IElapsedTimerService : ITimerService { void SetTimout(long durationMilliSeconds, Action<TimeSpan> callback); }
  • 33. Open closed principle software entities should be open for extension, but closed for modification
  • 34.
  • 35. Liskov subtitution objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program
  • 36. LSP smell - look for type checking void ArrangeBirdInPattern(IBird aBird) } var aPenguin = aBird as Pinguin; if (aPenguin != null) } ArrangeBirdOnGround(aPenguin); { else } ArrangeBirdInSky(aBird); { // What about Emu? {
  • 37. Interface segregation Many client specific interfaces are better than one general purpose interface. http://en.wikipedia.org/wiki/Cockpit
  • 38. Dependency Inversion Depend upon abstractions. Do not depend upon concretions.
  • 39. Your code will change! • Requirements change • Bugs are found • New feature requests  Your design will change
  • 40. In the beginning… Application was beautiful - then came change… • Software Rot – Duplication – Excess coupling – Quick fixes – Hacks
  • 41. public override void HandleActionRejected(User from, reason reason) } Logger.Info("HandleActionRejected - user:{0}", from.Id); /*foreach (var user in UserRepository.GetAllUsers) } Client.SendInfo(user, from, reason); { */ //2.2 Events.Users.Value = new UserData } SessionId = CurrentSession.Id, HaveIInitiated = true, OtherUser = from, StartCallStatus = Events.ConvertToCallStatus(answer) {; UserRepository.Remove(from, reason); if(UserRepository.IsEmpty()) } Exit(); { {
  • 43. Refactoring “a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior” - Martin Fowler http://refactoring.com/catalog/
  • 45. Code reviews Can catch up to 60% of defects Effective code reviews are: • Short – don’t waste time • Constructive • Avoid emotionally draining arguments Everybody reviews and everybody is reviewed
  • 46. No quality has very high cost Never have time to do it, but always have time to re-do it. Explain why this feature takes so much time “You rush a miracle man, you get rotten miracles.”
  • 47. Don’t expect your company to force you Be a professional Care about your code
  • 48. Improve your code • Start as soon as you can • Don’t compromise Schedule time for quality –Improve existing code –Make it work, then make it better 49

Editor's Notes

  1. The developer Wrote the code - Was the first to see the feature Can validate requirments
  2. So why not have better testing? It’s hard to find all of the scenarios Cost of fixing increase
  3. Bad code attracts more bad code “It was like this when I got here”
  4. Show example of not readable code
  5. a.k.a spaghetti code
  6. Avoid duplicate code (DRY)