Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Writing Clean Code in C# and .NET
About.ME
• Senior Consultant @CodeValue
• Developing software (Professionally) since 2002
• Writing clean code since 2009
...
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 Addres...
High quality code is:
• Easy to read and understand
• Impossible to hide bugs
• Easy to extend
• Easy to change
• Has unit...
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 ...
“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...
Write short methods – please!
• It’s easier to understand
• Performance won’t suffer
• Avoid mixing abstraction layers
• E...
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 wh...
Code Smells
• Duplicate code
• Long method
• Large class
• Too many parameters
• Feature envy
• Inappropriate intimacy
• R...
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”...
http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-
source-code-you-have-ever-encountered
/// <summary>...
Regions == Comments
Naming is important
d, days  daysSinceLastPayment
customerPo  customerPurchaseOrder
productIdString  productId
genymdhm...
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_...
Avoid duplicate code (DRY)
“Every piece of knowledge must have a
single, unambiguous, authoritative
representation within ...
public bool HasGroup(List<Token> tokenList){
for(Token token : tokemList){
if(token.get_group() != null) {
return true;
{
...
Good code start with good design
Bad DesignGood design
RigidLoosely coupled
FragileHighly cohesive
ImmobileEasily composab...
This is not OOP!!!
public class Record_Base
{
public DateTime RecordDateTime
{
get { return _recordDateTime; }
set
{
if (t...
Design stamina hypothesis
http://martinfowler.com/bliki/DesignStaminaHypothesis.html
Principles of Object Oriented Design
Single responsibility
Open/closed
Liskov substitution
Interface segregation
Dependenc...
Single responsibility
A class should have one, and only one,
reason to change.
http://www.amazon.com/Wenger- 16999-ssiwS-e...
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 de...
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 correc...
LSP smell - look for type checking
void ArrangeBirdInPattern(IBird aBird)
}
var aPenguin = aBird as Pinguin;
if (aPenguin ...
Interface segregation
Many client specific interfaces are better than
one general purpose interface.
http://en.wikipedia.o...
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 fix...
public override void HandleActionRejected(User from, reason reason)
}
Logger.Info("HandleActionRejected - user:{0}", from....
Refactoring
Refactoring
“a disciplined technique for restructuring
an existing body of code, altering its
internal structure without c...
Refactoring with Visual Studio
Code reviews
Can catch up to 60% of defects
Effective code reviews are:
• Short – don’t waste time
• Constructive
• Avoid ...
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 s...
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 ...
Writing clean code in C# and .NET
Writing clean code in C# and .NET
Upcoming SlideShare
Loading in …5
×

Writing clean code in C# and .NET

11,409 views

Published on

Maintaining the product is one (if not the most) expensive area of the overall product costs. Writing clean code can significantly lower these costs, making it more efficient during the initial development and results in more stable code. In this session participants will learn how to apply C# techniques in order to improve the efficiency, readability, testability and extensibility of code.

Published in: Software, Technology
  • Be the first to comment

Writing clean code in C# and .NET

  1. 1. Writing Clean Code in C# and .NET
  2. 2. About.ME • Senior Consultant @CodeValue • Developing software (Professionally) since 2002 • Writing clean code since 2009 • Blogger: http://blog.drorhelper.com
  3. 3. Let’s talk about software bugs
  4. 4. Bugs cost around $312 Billion Per Year
  5. 5. And it’s all a developer’s fault
  6. 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. 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
  8. 8. Broken windows
  9. 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. 10. Quality == Agility • Adapt to changes • Don’t be held back by bugs • Cannot be agile without high quality code
  11. 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. 12. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live”
  13. 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. 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. 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. 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. 17. Comments often are used as a deodorant Refactoring, Martin Fowler
  18. 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. 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; {
  20. 20. Regions == Comments
  21. 21. Naming is important d, days  daysSinceLastPayment customerPo  customerPurchaseOrder productIdString  productId genymdhms  generationTimeStamp
  22. 22. Dead Code • Code which is never run • But still has maintenance costs • Solution - delete
  23. 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. 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. 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. 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. 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
  28. 28. Design stamina hypothesis http://martinfowler.com/bliki/DesignStaminaHypothesis.html
  29. 29. Principles of Object Oriented Design Single responsibility Open/closed Liskov substitution Interface segregation Dependency inversion www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
  30. 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. 31. Naming as code smell Having difficulties naming your class/method? You might be violating SRP
  32. 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. 33. Open closed principle software entities should be open for extension, but closed for modification
  34. 34. Liskov subtitution objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program
  35. 35. 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? {
  36. 36. Interface segregation Many client specific interfaces are better than one general purpose interface. http://en.wikipedia.org/wiki/Cockpit
  37. 37. Dependency Inversion Depend upon abstractions. Do not depend upon concretions.
  38. 38. Your code will change! • Requirements change • Bugs are found • New feature requests  Your design will change
  39. 39. In the beginning… Application was beautiful - then came change… • Software Rot – Duplication – Excess coupling – Quick fixes – Hacks
  40. 40. 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(); { {
  41. 41. Refactoring
  42. 42. 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/
  43. 43. Refactoring with Visual Studio
  44. 44. 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
  45. 45. 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.”
  46. 46. Don’t expect your company to force you Be a professional Care about your code
  47. 47. 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

×