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 summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With JestBen McCormick
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Clean architecture
Clean architectureClean architecture
Clean architectureandbed
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practicesmh_azad
 
Kata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and AdaptersKata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and Adaptersholsky
 
임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013devCAT Studio, NEXON
 
Android Modularization
Android ModularizationAndroid Modularization
Android ModularizationYoung-Hyuk Yoo
 
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들Chris Ohk
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)Tom Kocjan
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 

What's hot (20)

Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean code
Clean code Clean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Kata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and AdaptersKata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and Adapters
 
임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013
 
Clean Code
Clean CodeClean Code
Clean Code
 
Android Modularization
Android ModularizationAndroid Modularization
Android Modularization
 
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Event storming
Event storming Event storming
Event storming
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 

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

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 

Recently uploaded (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

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)