• Home
  • RSS Feed
  • Log in

Clean Code vs. Implementation Patterns
Posted by Vincent Partington in the late evening: January 26th, 2009

I've just read Robert C. Martin's Clean Code and Kent Beck's Implementation Patterns back to back. I actually picked up Clean Code first because my colleagues were raving about it. But then Robert Martin's book quotes from Kent Beck's book on the third page of the first chapter already, and disagrees with the quote, so I decided it'd be fun to read Implementation Patterns too. :-)

Well, it turns out that the books don't really disagree that much. The difference is that Robert Martin is very convinced that he is describing a good way to do things for all of us, while Kent Beck's tone is more neutral, humbly presenting the patterns that have allowed him personally to become a better programmer. I guess it's a matter of taste, but I actually preferred Clean Code's boldness. Another big difference is that Clean Code contains a lot more actual code (the subject of both books after all) than Implementation Patterns. The bit in Clean Code's introduction about not skipping the case studies with that code lest the book be just another "feel good" book on programming is very true. I'm not sure, but it seems to me as if that line was directed towards Kent Beck's effort. ;-)

Besides those differences, the nice thing both books share is the refreshing new focus on the small things that make us better programmers. After we all read GoF's Design Patterns, a lot of books were talking about design patterns and then about architecture patterns. And after that our attention shifted towards process (XP, Agile). It is good to remember that the "mundane" task of writing code is something we still can and must improve.

Something else these books share is one very important value to keep in mind when writing code. And that is Communication (as Kent Beck summarizes it in one word). The code you write will be read more times than it was written and by more people. So to minimize the cost of maintenance, your code should be clear to those people (or yourself) reading it a later date. It should be nice to read, it should clearly communicate its design, and it should not be overly complex.

This comes forward in such heuristics (as they are called in Clean Code) or patterns (as Implementation Patterns refers to them) as:

  • Choose Descriptive Names (CC) / Intention-Revealing Name (IP) - Think about the names you give your classes, methods, etc. Instead of just starting with get or set and slapping on a word or two, actually describe what is going on. If you can't do that succinctly then maybe you need a better abstraction.
  • Functions Should Descend Only One Level of Abstraction (CC) / Composed Method (IP) - Split up large methods so that they deal just one level of abstraction, delegating work to other methods for work on a lower level of abstractions. Not only does this make the code easier to understand, you may also discover reusable bits of code this way. Doing this is easy to do with the support modern IDE's have for refactoring operations such as "Extract Method".
  • Use Explanatory Variables (CC) / Role-Suggesting Name (IP) - Split up complex calculations by using local variables with descriptive names. Like the previous pattern, this helps the reader of your code to understand what is going on. Modern IDE's have the "Extract Local Variable" refactoring operation to do this.

One nice advantage of following these patterns or heuristics is that it allows you to do away with a lot of comments. Comments that are sometimes redundant, that are bound to become obsolete, and that may even misguide the reader if not properly maintained. Having learned to program in the late eighties (when writing comments was what a good programmer was supposed to do), this felt a bit strange at first. But now, when I feel the need to explain a block of code by starting a comment, I know that I need to extract that block into a separate method. :-)

While both books inspired me a lot, there were a few thing I did not like.

To start with Clean Code: while Robert Martin's prose is very enticing, the chapters contributed by other people were not up to the same level. The chapter on Emergence did not offer any new insights, and the chapters on Concurrency seem simplistic. At least to someone that has read Brian Goetz' excellent Java Concurrency in Practice. Also, the coding style where fields are preferred over method arguments (as exemplified by the Args example in chapter 14) seems to be asking for concurrency problems to me. It looks like the Hidden Temporal Couplings smell mentioned in the same book.

As for Implementation Patterns; as I mentioned before, I would have liked the book to include more code. Also, some of the patterns are not really patterns but rather descriptions of a programming concept ("Class", "Initialization", "Parameter", etc.). So while the back cover of the book promises 77 patterns, you are actually getting less. ;-) And there is one pattern that I think is very dangerous; I've seen people misinterpreting the eager initialization pattern so many times, that I would have loved to see a move-the-declaration-to-the-initialization-instead-of-the-initialization-to-the-declaration pattern. And finally, while the last chapter describes some nice patterns to use when writing a framework, these patterns are not applied to the timer framework in appendix A that immediately follows.

One thing I dearly miss in both books is how to deal with existing frameworks. Most code we write does not exist in a vacuum but uses a lot of frameworks such as EJB3, Spring, Wicket or whatever. While modern frameworks are less invasive when compared to older frameworks such as EJB2, they still have an impact on your architecture as I recently discovered when using JPA on a new project (but more that in a later blog :-) ).

To conclude, I think these books are a valuable read for anyone who wants to become a better programmer. As they are easy to read (Implementation Patterns is only about 150 pages!) there really is no excuse to write bad code anymore!

  • Share/Bookmark

Filed under Architecture, Hibernate, Java, Testing | 11 Comments »



11 Responses to “Clean Code vs. Implementation Patterns”



    John K. Patrick Says:
    Posted at: January 26, 2009 at 11:45 pm

    Nice article mate! Patterns should be used carefully though, and not artificially bloat the whole architecture.



    dennis sellinger Says:
    Posted at: January 27, 2009 at 9:04 pm

    I have read IP twice and am having trouble slogging through CC (but then, I have the paper version of IP and only the online version of CC).

    I think IP changed the way I code simply because at one point Beck talks about code symmetry.

    For me, this was the first time I have seen code symmetry articulated, but I think when we look at asymmetric code we notice that “something is wrong”, even if we don’t know what it is.

    For me this was the “big new thing” of the book and I am encouraging my co-workers to read the book, just to have the concept explained (in hopes that we start to write more symmetric code).

    cheers.



    Alex Says:
    Posted at: January 27, 2009 at 9:58 pm

    Really enjoyed this article. In fact I just ordered both books; I should be able to get a real interesting and informative presentation for our professional circle from them.



    Caligula Says:
    Posted at: January 27, 2009 at 10:42 pm

    @John K Patrick: the “patterns” referred to here are not “design patterns”.



    dennis sellinger Says:
    Posted at: January 28, 2009 at 12:54 pm

    One more point. The more we try to write clean code (i.e. short methods that do exactly one thing), the more our code files can become a big mess of methods (in my IDE I don’t even have a way to know that a method is never called (even a private one!).

    IDEs generally provide “extract method” tools, but mine (Visual Studio) does not offer any tools to reorganize the code. Result, the code file is a stream of consciousness mess of short methods.

    So, I think tool providers have to start looking at doing method extraction with code reorganization in mind if we are ever to truely exploit the techniques of CC and IP.

    In addition, as we start “sorting” methods, we will also have problems with source code systems that will be continually finding change conflicts. So SCM tools have to start having method granularity rather than just code file granulatiry.

    So I think if we are to adopt some of these techniques, the tool providers have to start inventing new tools that will help us structure code files more easily.



    Henry Ho Says:
    Posted at: January 28, 2009 at 11:12 pm

    I just read Clean Code: A Handbook of Agile Software Craftsmanship, and I must say, Chapter 17. Smells and Heuristics is the most awesome chapter I have ever read!

    Thank you for introducing me to such a good book.



    fritz freiheit.com » Link dump Says:
    Posted at: January 30, 2009 at 9:57 pm

    [...] Clean Code vs. Implementation Patterns | Xebia Blog (Code,Refactoring,Book,Comparison,SoftwareDevelo… [...]



    Craig Jones Says:
    Posted at: March 26, 2009 at 12:32 am

    Thanks for comparison. I’m mostly through CC. Haven’t read IP yet, and I’m wondering if I need to bother. Based on the 3 examples you gave — “Choose Descriptive Names” (CC) vs. “Intention-Revealing Name” (IP), “Functions Should Descend Only One Level of Abstraction” (CC) vs. “Composed Method” (IP), and “Use Explanatory Variables” (CC) vs. “Role-Suggesting Name” (IP) — it seems like Martin’s CC book is more plain-spoken and therefore easier to grok. If I don’t have any questions after reading CC, will reading IP add anything? (Hmm, perhaps even if not, I should read IP anyway, just so I can communicate with other programmers who have read IP but not CC.)



    Code Quality - Learn: OOPs, Desing Patterns, Clean Code and Refactoring « Jai’s Weblog - Tech, Security & Fun… Says:
    Posted at: April 12, 2009 at 9:01 am

    [...] For review please feel free to have a look at this Book Review and also very interesting comparison Clean Code vs. Implementation Pattern. And certainly few more enthusiastic who even say  Get it. Read it. Learn it. Then live [...]



    Christian Horsdal Says:
    Posted at: July 3, 2009 at 6:57 am

    Thanks for an interesting comparison.

    About the two books not covering how to deal with exiting code: You might find Michael Feathers Working Effectively with Legacy Code interesting. I think it’s very, very good.



    Vincent Partington Says:
    Posted at: July 5, 2009 at 1:44 pm

    @Christian: Thanks for the tip. I’ve heard more people mention that Michael Feathers’ book is an interesting one. I’ll put it on my to-read list!



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    XML Semantic Web Closures Introduction to Agile IntelliJ qcon Functional Programming Poppendieck Groovy Agile Awareness Workshop Hibernate Ajax JavaOne Architecture Seam SOA fitnesse Scrum esb Java Agile Performance product owner Lean Grails Maven Spring Testing Scala Xebia
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs