SlideShare a Scribd company logo
Software CraftsmanshipMeeting #2http://www.flickr.com/photos/renfield/17375998/in/set-388814/
AgendaBad Code / Good CodeCode SmellsToolsHands OnCode DojoIdentifying Smells *
WTF    publicstaticbooleanisValidNumber(Integer number) {methodName = "isValidNumber";        Logger logger = LoggingHelper.getLogger(LOGGER);logger.entering (CLASS, methodName);        // parse this number. If you get an NFE, then its         // not valid, return falsetry {Integer.parseInt(number.toString());        } catch(Exception ex) {logger.fine(methodName + " returns false");logger.fine("Number Format Exception when parsing");            return false;         }logger.fine(methodName + " returns true");logger.exiting(CLASS, methodName);         return true;          }Logging EntryWTF?Logging Exit
WTFwhile(true){if(mainType == 7)    {subType = 4;break;    }if(mainType == 9)    {subType = 6;break;    }if(mainType == 11)    {subType = 9;break;    }break;}/*=============checkSizeMake sure the image is a power of 2.=============*/intcheckSize(int x) {if (x == 2 || x == 4 || x == 8 || x == 16 || x == 32 || x == 64 || x == 128 || x == 256 || x == 512)return 1;elsereturn 0;}WTF?WTF?
WTFDirectoryInfo dir = new DirectoryInfo(pathToDelete);// subDirsDirectoryInfo[] subDirs = dir.GetDirectories();foreach(DirectoryInfosubDirinsubDirs){  // subSubDirsDirectoryInfo[] subSubDirs = subDir.GetDirectories();foreach(DirectoryInfosubSubDir in subSubDirs)  {    // subSubSubDirsDirectoryInfo[] subSubSubDirs = subSubDir.GetDirectories();foreach(DirectoryInfosubSubSubDirinsubSubSubDirs)    {      // subSubSubSubDirsDirectoryInfo[] subSubSubSubDirs = subSubSubDir.GetDirectories();foreach(DirectoryInfosubSubSubSubDirinsubSubSubSubDirs)      {        // ********************************************        // should be enough; if not, I can add more here        // ********************************************WTF?WTF?
Code Smellhttp://www.flickr.com/photos/brian-fitzgerald/3334353375/http://www.flickr.com/photos/yomi955/1192827822/Code Smell - In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problemhttp://en.wikipedia.org/wiki/Code_smell
Code SmellsDuplicated CodeSame code structure in more than one place:Same expression in two methods of the same classSame expression in two sibling subclassesSame expression in two unrelated classes
Code Smells
DemoClone Detector
Code SmellsLong MethodA good technique is to look for comments. They often signal a semantic distance between the intension of the code and the implementation of the codeThe net effect is that you should be much more aggressive about decomposing methodsThe desired length should be 5-8 lines
Code Smells
DemoComments, please!
Code SmellsLarge ClassMany instance variables indicates that a class tries to do too muchMany instance variables can indicate a duplicate codeToo much code is prime breeding ground for duplicated code, chaos, and death
Code Smells
DemoHow Many Lines?
Code SmellsLong Parameter ListIn the past we passed in as parameters everything needed by a routine. With objects it’s not required; instead enough parameters passed in to the method in order to allow it to get everything rest it needsLong parameter lists are hard to understandLong parameter lists inconsistent and difficult to useLong parameter lists are forever changed as more data is required
Code Smells
Code SmellsLong Parameter ListAvoid output parameters (ref, out)Avoid boolean argumentsAvoid more than 3 arguments2 is preferable1 is better0 is the bestIntroduce Parameter ObjectRefactoring StepSeparate Query From ModifierRefactoring StepOne return value.
DemoTo Query or To Modify?
Code SmellsSwitch StatementsThe problem with switch statements is essentially that of duplication i.e. the same switch statement scattered about a program in different placesMost times you see a switch statement you should consider polymorphism
Code Smells
DemoHow to Process Request
Code SmellsSpeculative GeneralityA class that exists to support some future and imaginary feature.“We might need this one day …”If you really do need it later, you can add it easily using Refactoring.It doesn’t mean you don’t need to anticipate requirements and features.
Code SmellsCommentsWhen you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous
Code SmellsFeature EnvoyA method that seems more interested in a class other than the one it actually is inData and the behavior that references that data usually change together, but there are exceptions:VisitorStrategy
Code Smells
Code SmellsMessage ChainsA client asks one object for another object, which the client then asks for yet another object, which the client then asks for yet another another object, and so onCan be seen as a long line of GetThis() methods, or as a sequence of tempsAny change to the intermediate relationships causes the client to have to changeAccount.Owner.OwnerDetails.Address.Zip
Hands OnDojoCode Smellshttp://www.flickr.com/photos/renfield/351556388/in/photostream/
Roman Numbers: ToString()0NullaNumerals
Roman Numbers: ToString()IThe values of each roman letter can be additiveIIThe larger numerals must be placed to the left of the smaller numeralsIIIAt the fourth iteration, a subtractive principle may beemployed, with the base placed before the higher base:IIII or IV The subtracted digit must be at least one tenth of thevalue of the larger numeral. Therefore: 99 isn’t IC butrather XCIX
2nd Meeting of the Software Craftsmanship Grouphttp://www.flickr.com/photos/psd/2086641/

More Related Content

What's hot (20)

PDF
JavaScript: Core Part
維佋 唐
 
PPTX
Clonedigger-Python
Sangharsh agarwal
 
PDF
Clone detection in Python
Valerio Maggio
 
PPTX
Python language data types
Hoang Nguyen
 
PDF
Amusing C#
PVS-Studio
 
PDF
Python cheat-sheet
srinivasanr281952
 
PPTX
The Sincerest Form of Flattery
José Paumard
 
PPTX
Python Session - 4
AnirudhaGaikwad4
 
PDF
Advanced perl finer points ,pack&unpack,eval,files
Shankar D
 
PPTX
Introduction To Programming with Python-3
Syed Farjad Zia Zaidi
 
PPT
Antlr V3
guest5024494
 
PPTX
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 3)
Binary Studio
 
PDF
Get Functional on the CLR: Intro to Functional Programming with F#
David Alpert
 
PPSX
Programming with Python
Rasan Samarasinghe
 
PDF
Unsupervised Machine Learning for clone detection
Valerio Maggio
 
PPTX
Introduction to Structure Programming with C++
Mohamed Essam
 
PPT
The JavaScript Programming Language
Raghavan Mohan
 
PPT
The Java Script Programming Language
zone
 
PPT
Phyton Learning extracts
Pavan Babu .G
 
PPTX
Python Programming Basics for begginners
Abishek Purushothaman
 
JavaScript: Core Part
維佋 唐
 
Clonedigger-Python
Sangharsh agarwal
 
Clone detection in Python
Valerio Maggio
 
Python language data types
Hoang Nguyen
 
Amusing C#
PVS-Studio
 
Python cheat-sheet
srinivasanr281952
 
The Sincerest Form of Flattery
José Paumard
 
Python Session - 4
AnirudhaGaikwad4
 
Advanced perl finer points ,pack&unpack,eval,files
Shankar D
 
Introduction To Programming with Python-3
Syed Farjad Zia Zaidi
 
Antlr V3
guest5024494
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 3)
Binary Studio
 
Get Functional on the CLR: Intro to Functional Programming with F#
David Alpert
 
Programming with Python
Rasan Samarasinghe
 
Unsupervised Machine Learning for clone detection
Valerio Maggio
 
Introduction to Structure Programming with C++
Mohamed Essam
 
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
zone
 
Phyton Learning extracts
Pavan Babu .G
 
Python Programming Basics for begginners
Abishek Purushothaman
 

Viewers also liked (8)

PPTX
Software craftsmanship - 4
Uri Lavi
 
PPTX
Web Performance 101
Uri Lavi
 
PPTX
JavaScript TDD
Uri Lavi
 
PPTX
Software Craftsmanship - 3
Uri Lavi
 
PPTX
Intro to Mahout
Uri Lavi
 
PPT
Cloud Aware Architecture
Uri Lavi
 
KEY
API Best Practices
Uri Lavi
 
PPTX
Effective Code Review
Uri Lavi
 
Software craftsmanship - 4
Uri Lavi
 
Web Performance 101
Uri Lavi
 
JavaScript TDD
Uri Lavi
 
Software Craftsmanship - 3
Uri Lavi
 
Intro to Mahout
Uri Lavi
 
Cloud Aware Architecture
Uri Lavi
 
API Best Practices
Uri Lavi
 
Effective Code Review
Uri Lavi
 
Ad

Similar to Software Craftsmanship - 2 (20)

PPTX
Code smells quality of code
Hasan Al Mamun
 
PPTX
Code smell overview
Pham Manh Lan
 
PDF
Code Smells and Its type (With Example)
Anshul Vinayak
 
PDF
Code smells
Mina Tafreshi
 
PPTX
Baroda code smell and refactoring
Mamata Gelanee
 
PDF
Msr17a.ppt
Ptidej Team
 
PDF
Msr17a.ppt
Yann-Gaël Guéhéneuc
 
PDF
Refactoring In Tdd The Missing Part
Gabriele Lana
 
PPTX
Code smells and Other Malodorous Software Odors
Clint Edmonson
 
PPTX
Code Smells
Mrinal Bhattacaharya
 
PDF
Webcast: Identify and Correct Common Code Smells
Serge Baranovsky
 
PDF
Bad Code Smells
kim.mens
 
PDF
Bad Smell In Codes 1
A Walk in the World
 
PPTX
Writing clean code in C# and .NET
Dror Helper
 
PPTX
Code smells and remedies
Md.Mojibul Hoque
 
PDF
Bade Smells in Code
Will Shen
 
PDF
Code Smell
Alex Punnen
 
PPTX
Develop your sense of code smell
Mike Clement
 
PPTX
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Cefalo
 
DOCX
A Study on Code Smell Detection with Refactoring Tools in Object Oriented Lan...
ijcnes
 
Code smells quality of code
Hasan Al Mamun
 
Code smell overview
Pham Manh Lan
 
Code Smells and Its type (With Example)
Anshul Vinayak
 
Code smells
Mina Tafreshi
 
Baroda code smell and refactoring
Mamata Gelanee
 
Msr17a.ppt
Ptidej Team
 
Refactoring In Tdd The Missing Part
Gabriele Lana
 
Code smells and Other Malodorous Software Odors
Clint Edmonson
 
Webcast: Identify and Correct Common Code Smells
Serge Baranovsky
 
Bad Code Smells
kim.mens
 
Bad Smell In Codes 1
A Walk in the World
 
Writing clean code in C# and .NET
Dror Helper
 
Code smells and remedies
Md.Mojibul Hoque
 
Bade Smells in Code
Will Shen
 
Code Smell
Alex Punnen
 
Develop your sense of code smell
Mike Clement
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Cefalo
 
A Study on Code Smell Detection with Refactoring Tools in Object Oriented Lan...
ijcnes
 
Ad

Recently uploaded (20)

PPTX
Simplifying End-to-End Apache CloudStack Deployment with a Web-Based Automati...
ShapeBlue
 
PDF
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
PPTX
UI5Con 2025 - Get to Know Your UI5 Tooling
Wouter Lemaire
 
PDF
Bitcoin+ Escalando sin concesiones - Parte 1
Fernando Paredes García
 
PDF
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
PDF
CIFDAQ Market Insight for 14th July 2025
CIFDAQ
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PPTX
Earn Agentblazer Status with Slack Community Patna.pptx
SanjeetMishra29
 
PDF
Productivity Management Software | Workstatus
Lovely Baghel
 
PDF
Trading Volume Explained by CIFDAQ- Secret Of Market Trends
CIFDAQ
 
PDF
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
PDF
Julia Furst Morgado The Lazy Guide to Kubernetes with EKS Auto Mode + Karpenter
AWS Chicago
 
PPTX
UI5Con 2025 - Beyond UI5 Controls with the Rise of Web Components
Wouter Lemaire
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
PDF
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
Simplifying End-to-End Apache CloudStack Deployment with a Web-Based Automati...
ShapeBlue
 
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
UI5Con 2025 - Get to Know Your UI5 Tooling
Wouter Lemaire
 
Bitcoin+ Escalando sin concesiones - Parte 1
Fernando Paredes García
 
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
CIFDAQ Market Insight for 14th July 2025
CIFDAQ
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Earn Agentblazer Status with Slack Community Patna.pptx
SanjeetMishra29
 
Productivity Management Software | Workstatus
Lovely Baghel
 
Trading Volume Explained by CIFDAQ- Secret Of Market Trends
CIFDAQ
 
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
Julia Furst Morgado The Lazy Guide to Kubernetes with EKS Auto Mode + Karpenter
AWS Chicago
 
UI5Con 2025 - Beyond UI5 Controls with the Rise of Web Components
Wouter Lemaire
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 

Software Craftsmanship - 2

  • 2. AgendaBad Code / Good CodeCode SmellsToolsHands OnCode DojoIdentifying Smells *
  • 3. WTF publicstaticbooleanisValidNumber(Integer number) {methodName = "isValidNumber"; Logger logger = LoggingHelper.getLogger(LOGGER);logger.entering (CLASS, methodName); // parse this number. If you get an NFE, then its // not valid, return falsetry {Integer.parseInt(number.toString()); } catch(Exception ex) {logger.fine(methodName + " returns false");logger.fine("Number Format Exception when parsing"); return false; }logger.fine(methodName + " returns true");logger.exiting(CLASS, methodName); return true; }Logging EntryWTF?Logging Exit
  • 4. WTFwhile(true){if(mainType == 7) {subType = 4;break; }if(mainType == 9) {subType = 6;break; }if(mainType == 11) {subType = 9;break; }break;}/*=============checkSizeMake sure the image is a power of 2.=============*/intcheckSize(int x) {if (x == 2 || x == 4 || x == 8 || x == 16 || x == 32 || x == 64 || x == 128 || x == 256 || x == 512)return 1;elsereturn 0;}WTF?WTF?
  • 5. WTFDirectoryInfo dir = new DirectoryInfo(pathToDelete);// subDirsDirectoryInfo[] subDirs = dir.GetDirectories();foreach(DirectoryInfosubDirinsubDirs){ // subSubDirsDirectoryInfo[] subSubDirs = subDir.GetDirectories();foreach(DirectoryInfosubSubDir in subSubDirs) { // subSubSubDirsDirectoryInfo[] subSubSubDirs = subSubDir.GetDirectories();foreach(DirectoryInfosubSubSubDirinsubSubSubDirs) { // subSubSubSubDirsDirectoryInfo[] subSubSubSubDirs = subSubSubDir.GetDirectories();foreach(DirectoryInfosubSubSubSubDirinsubSubSubSubDirs) { // ******************************************** // should be enough; if not, I can add more here // ********************************************WTF?WTF?
  • 6. Code Smellhttp://www.flickr.com/photos/brian-fitzgerald/3334353375/http://www.flickr.com/photos/yomi955/1192827822/Code Smell - In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problemhttp://en.wikipedia.org/wiki/Code_smell
  • 7. Code SmellsDuplicated CodeSame code structure in more than one place:Same expression in two methods of the same classSame expression in two sibling subclassesSame expression in two unrelated classes
  • 10. Code SmellsLong MethodA good technique is to look for comments. They often signal a semantic distance between the intension of the code and the implementation of the codeThe net effect is that you should be much more aggressive about decomposing methodsThe desired length should be 5-8 lines
  • 13. Code SmellsLarge ClassMany instance variables indicates that a class tries to do too muchMany instance variables can indicate a duplicate codeToo much code is prime breeding ground for duplicated code, chaos, and death
  • 16. Code SmellsLong Parameter ListIn the past we passed in as parameters everything needed by a routine. With objects it’s not required; instead enough parameters passed in to the method in order to allow it to get everything rest it needsLong parameter lists are hard to understandLong parameter lists inconsistent and difficult to useLong parameter lists are forever changed as more data is required
  • 18. Code SmellsLong Parameter ListAvoid output parameters (ref, out)Avoid boolean argumentsAvoid more than 3 arguments2 is preferable1 is better0 is the bestIntroduce Parameter ObjectRefactoring StepSeparate Query From ModifierRefactoring StepOne return value.
  • 19. DemoTo Query or To Modify?
  • 20. Code SmellsSwitch StatementsThe problem with switch statements is essentially that of duplication i.e. the same switch statement scattered about a program in different placesMost times you see a switch statement you should consider polymorphism
  • 23. Code SmellsSpeculative GeneralityA class that exists to support some future and imaginary feature.“We might need this one day …”If you really do need it later, you can add it easily using Refactoring.It doesn’t mean you don’t need to anticipate requirements and features.
  • 24. Code SmellsCommentsWhen you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous
  • 25. Code SmellsFeature EnvoyA method that seems more interested in a class other than the one it actually is inData and the behavior that references that data usually change together, but there are exceptions:VisitorStrategy
  • 27. Code SmellsMessage ChainsA client asks one object for another object, which the client then asks for yet another object, which the client then asks for yet another another object, and so onCan be seen as a long line of GetThis() methods, or as a sequence of tempsAny change to the intermediate relationships causes the client to have to changeAccount.Owner.OwnerDetails.Address.Zip
  • 30. Roman Numbers: ToString()IThe values of each roman letter can be additiveIIThe larger numerals must be placed to the left of the smaller numeralsIIIAt the fourth iteration, a subtractive principle may beemployed, with the base placed before the higher base:IIII or IV The subtracted digit must be at least one tenth of thevalue of the larger numeral. Therefore: 99 isn’t IC butrather XCIX
  • 31. 2nd Meeting of the Software Craftsmanship Grouphttp://www.flickr.com/photos/psd/2086641/

Editor's Notes

  • #4: CMMI 5Complicated? Smart Ass?
  • #5: WHY?
  • #8: Duplicated Logic on a “Page” or “Code Behind”
  • #10: Examples:Execute similarities (CloneDetector) on the BlogEngine:DbRoleProvider, DbBlogProvider, DbMembershipProvider – Initialize method – 99% is duplicated. Also, Category and Post are duplicated on Title and Description, although they inherit from BusinessBase.Tools:http://www.getatomiq.com/overview/http://www.redhillconsulting.com.au/products/simian/http://clonedigger.sourceforge.net/
  • #11: Decomposition (valid reasons to create a method):Reduce ComplexityIndirectionRemove Duplicate CodeSupport SubclassingHide SequencesSimplify Complicated Boolean Tests
  • #13: Examples:BlogEngine.Core.Providers.XmlProvider. XMLBlogProvider.Posts.SelectPost – a huge methods with a lot of responsibilities.CardGame.BlackJackGame.DealNewGame – proves the newspaper paradigm
  • #16: Examples:BlogEngine.Core.Providers.BlogProvider – violates SR Principle and also defines a lot of different methods, has more than 200 lines.BlogEngine.Core.SyndicationGenerator – has more than 900 lines.BlogEngine.Core.API.MetaWeblog.MetaWeblogHandler – has more than 700 lines, most of the functions are private.
  • #20: Examples:- Method receiving booleanarg: CardGame.Card. The constructor Card takes a boolean argument, specifying whether the card is up or not. This is hard to read!!!- BlogEngine.Core.API.MetaWeblog.MetaWeBlogHandler.LookupCategoryGuidByName: Does 2 things: Returns whether found and returns the Category
  • #22: Refactor the MovieRent’s Rent and Movie classes to use State Pattern
  • #23: Examples:- BlogEngine.Core.API.MetaWebBlogHandler.ProcessRequest : A huge switch case.