Clean Code


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Clean Code

  1. 1. Clean Code
  2. 2. Broken WindowsWTFs per minuteGood code mattersCode constitutes our inventoryBad code brings companies to their kneesWeve all seen itWeve all written it - but why?Clean it up later? Leblancs law: Later = Never
  3. 3. Cost of Bad CodeEver decreasing productivityBlame lies in us - not management, or customers, or marketingWe are deeply complicit in the planning of a projectand share a great deal of responsibility, especially if failureshave to do with bad codeIts our job to defend the code - as it is a mangers to defend thescheduleYou will not make the deadline by making a mess, rather youwill be slowed down instantly and miss the deadline
  4. 4. Clean Code Is An Artrecognizing bad code does not mean you can write clean coderequires a myriad of techniques applied with code-sensecode sense shows us a strategy for transforming bad code intoclean codea sequence of transformations applied against a set of unittests
  5. 5. Good vs. BadBad Code Good Code ● tempts the mess to grow ● elegant ● gets messier over time ● pleasing ● tries to do too much ● efficient ● speculative ● no duplication ● does not include unit tests ● minimal entities ● does not run unit tests ● unpolluted by surrounding details ● has duplication ● reads like well written prose ● is obscure ● matter-of-fact, decisive ● appears neglected ● easy for others ● difficult for others to read ● includes tests and runs them all ● mysterious words ● literate ● functions serve multiple purposes ● has been taken care of ● classes serve multiple purposes ● expresses design of system ● object.child.grandchild.greatgrandchild ● tiny abstractions ● has dead code ● no surprises, obvious, simple, ● relies on comments compelling
  6. 6. We Are Authorsratio of time spent reading code vs. writing is 10:1reading should be easy, even if that makes writing hardhowever, making it easy to read makes it easy to writefunctions are the verbs of a system, classes are the nounsprogramming is the art of language designmaster programmers think of systems as stories to be toldrather than programs to be written
  7. 7. Boy Scout RuleKeep it Cleanleave the campground cleaner than you found itif we all check in cleaner than we find it, it wont rotcan be something small: improve one variable name, break upone large function, eliminate one small bit of duplication, cleanup one composite if statementimagine working on a project where the code got better andbetter over time, easier and easier to readdont comment bad code - rewrite it
  8. 8. NamesTake care of your namesChange names when you find better onesreveal all intention in every namewhy it exists, what it does, how it is usedif a comment is needed, intention is not revealedavoid disinformation, obscure anagram style names, keywordsthat are not accurate (AccountList, for a container holdingaccounts that is not actually a list), slight variations,inconsistent spelling, deliberately wrong spelling
  9. 9. Namesnumber series names are bad (a1, a2, a3). come up withsomething meaningfulnoise words are redundant, e.g. ProductData, ProductInfo,NameString, ColorVariablereader should be able to distinguish the differencesnames should be pronounceable: var genymdhms:TimeStampnames should be searchablelength of name should correspond to size of its scope
  10. 10. Namesencoding type or scope into name adds extra burden ofdecipheringHungarian Notation makes it harder to change the name ortype of a variable, function or class and makes it harder to read.the encoding system could wind up misleading the readermember prefixing is unnecessary and winds up being ignoredUsing capital i I to prefix an interface is a distraction and toomuch information - if you have to encode 1 or the other, encodethe implementation - but, best not to encode at allprofessionals understand that clarity is king - dont try to becute
  11. 11. NamesClass names should be nouns or noun phrasesMethods should be verbs or verb phrasesAccessor methods should be named for their valueMethods should describe their arguments - change the namewhen the arguments changePick 1 word for an abstract concept and stick with itSame word for two different purposes is essentially a punUtilize a consistent lexicon
  12. 12. NamesOK to use Computer Science terms: algorithm names, patternnames, math terms, etcIf possible, avoid using names from the problem domain, ascomputer scientists unfamiliar with the problem domain will notknow what they meanNames are contextual, the method lives in a class which lives ina package - so name them appropriately to avoid encodingShorter is better, provided full clarity is provided - add no morecontext than is necessaryGood naming requires descriptive skills - which is a teachingissue, not a technical, business or management issue
  13. 13. Functionsshould do one thing, do it well, do it onlyshould be small - then smaller than thatshould hardly ever be 20 lines longaim for 2-4 lines of transparency and obviousnesstell a story, lead the read from method to method in acompelling orderblocks within if, if else, while, etc. should be 1 line - a functioncallthe indent level of a function should not be greater than 1 or 2should not be large enough to hold nested structures
  14. 14. Functionsshould only perform steps 1 level below the stated name of thefunctionshould not be able to extract another function from it with aname that is not merely a restatement of its implementationshould not be able to divide into sectionsshould not mix levels of abstractionthe step-down rule: code should read like a top down narrativeevery function should be followed by next level of abstractionwhere top is most abstract
  15. 15. Functionswriting functions that perform at a single level of abstraction ischallenging, but is very, very important - keeps them short andsingular of focuseach function should introduce the nextswitch statements can only be tolerated if they appear onlyonce, are used to create polymorphic objects, and are hiddenbehind an inheritance relationship where rest of system cantsee themthere should not be more than 1 reason for the function tochange and functions should not need to change when newtypes are added
  16. 16. Functionsthe smaller and focused a function is, the easier it is to namedont be afraid of long names, better a long descriptive namethan a descriptive commentdont be afraid of taking time to choose a name or of changingnames, in fact, try several namesbe consistent with names, use your module names in yourfunctionsthe ideal number of arguments is 0, next is 1, then 2. 3 shouldbe avoided
  17. 17. Functionsthe more arguments, the more difficult a function is to test, andthe harder it is to understandoutput arguments are confusing - objects passed in that getchanged in the function, but not returned - always return yourtransformed object - better yet, add the function the objectcommon reasons for a single argument: query the objectpassed in, or transform the object and return itflag arguments are a terrible practice: complicates signaturebecause it does more than one thingconvert dyads to monads whenever possible
  18. 18. Functionstriads increase the complexity of a function more than doublewhen you have more than two or three arguments, maybe theyneed to be wrapped in a classwith a monad, the function and argument should form a niceverb/noun pairingfunction names should have arguments encodedside effects are lies: a side effect is when your functionpromises to do one thing but also does other hidden thingstemporal coupling are confusing, especially when hidden as aside effect
  19. 19. Functionsshould either do something or answer something - not bothfunction should either change state of an object, or return infoabout that objectextract try/catch blocks out to functions of their owna try/catch block should be the only thing a function does,nothing before try, nothing after finallyexceptions are better than error codes
  20. 20. Commentsat best a necessary evilalways a failuregrimace every time and feel the failure of your ability to expressyourselfinaccurate comments are worse than no commentsrather than spend time explaining your mess - clean it upbest comment is the one you found a way not to write
  21. 21. Commentssometimes usefulprovide intent behind implementation decisionscan be helpful to explain meaning of an obscure arguments orreturn valuecan warn of consequencesamplify importance of something that seems trivialTODOs are ok, but not an excuse to leave bad code in thesystem - eliminate them regularlyif writing a public API - make JavaDocs, but make them good
  22. 22. Commentsreplace the temptation to create noise with the determination toclean your codebanners /////////////////// are noise, are clutter - should beeliminatedcommenting out code is odious - dont do it! theres no way foranyone to know what to do with it - just delete it, svn will store itfor youdefinitely do not add HTML to source code commentsdont offer system wide information in the context of a localcomment
  23. 23. Commentsdont use comments as a change log, or discussion boardcomments should refer to code they appear near and shouldmake sense in contexta well chosen method name is better than a header commentgenerating javadocs for classes and functions inside a systemis not generally useful - ok for public apis but not systeminternals