Forgot your password?
typodupeerror
Programming

Clean Code 214

Posted by samzenpus
from the read-all-about-it dept.
Cory Foy writes "As developers, system admins, and a variety of other roles in IT, we have to deal with code on a daily basis. Sometimes it's just one-off scripts we never have to see again. Sometimes we stare at something that, for the life of us, we can't understand how it came out of a human mind (or, as the book puts it, has a high WTF/minute count). But there is a time when you find code that is a joy to use, to read and to understand. Clean Code sets out to help developers write that third kind of code through a series of essay-type chapters on a variety of topics. But does it really help?" Read below to find out.
Clean Code - A Handbook of Agile Software Craftsmanship
author Robert C. Martin
pages 431
publisher Prentice Hall
rating 10
reviewer Cory Foy
ISBN 978-0-13-235088-4
summary A great book for anyone wanting to really improve how they write code
I had the pleasure of attending Bob Martin (Uncle Bob)'s sessions at several agile software conferences over the past several years. In them, Bob has a unique way of showing us the value of clean code. This book is no different. There is a warning in the introduction that this is going to be hard work — this isn't a "feel good" kind of book, but one where we slog through crappy code to understand how to make it better. The authors also point out that this is their view of what clean code is all about — and fully acknowledge that readers may "violently disagree" with some of the concepts.

The book wastes no time diving in covering "Meaningful Names", "Functions" and "Comments" right in the first several chapters. While I could sum up the chapters by saying, "Use them", "Keep them small" and "Comments don't make up for bad code" it wouldn't do the wisdom in the book justice. For example, in the meaningful names chapter, he talks about making pronounceable and searchable names — staying away from things like "genymdhms" (Generation date, year, month, day, hour, minute and second) and preferring things like MAX_STUDENTS_PER_CLASS.

After touching on formatting rules (including some very interesting graphs on the file and function length distributions in some common open source projects) he dives back into some more controversial topics — "Objects and Data Structures", and "Error Handling". The Objects chapter does a great job of drawing a line in the sand between Objects and Data Structures and why it really is both important, and clearer, to keep your privates in your private classes.

The Error Handling chapter is important because of the application of earlier chapters — the Do One Thing rule. Your functions should do one thing — either handle business logic, or exception handling, but not both. It's the difference between this:

try { s = new Socket(4000); s.OpenSocket(); string data = s.ReadFromSocket(); if(data == "32") data = "42"; printer.print(data); } catch(Exception ex) { if(ex == NetworkInterruptException) { //do something } if(ex == PrinterOnFireException) { //do something } logException(ex); }

And this

try { tryToPrintDataFromSocket(); } catch(Exception ex) { logException(ex); }

We then move on to "Boundaries" and "Unit Tests" — the critical points where we tend to really let code go. If we work hard, usually we can keep our own code clean. It's when we have to begin interacting with other systems that things start to go astray. In these chapters, Bob and James Grenning show us how to keep our code at the boundaries clean — and how to keep our code working, period. The authors are proponents of Test-Driven Development, and the chapter on unit tests is a fresh reminder that those tests are just as much code, and need to be kept just as clean as any other code we write.

We then begin to move at a higher level, starting with "Classes" and "Systems". The classes section should be familiar to most any OO programmer — keep the classes small, with a single responsibility, and low coupling. He also talks about Organizing for Change which is a great section on how to structure classes in a way that keeps them open to change. The Systems section continues along the path with the great reminder to "Separate Constructing a System from Using It". Here they go into Dependency Injection and Aspect-Oriented Programming, which I'll address in a bit.

Moving even higher up the chain, the book then tackles "Emergent Design". The key is to keep the design simple, which according to Kent Beck, means:
  • Runs all the tests
  • Contains no duplication
  • Expresses the intent of the programmer
  • Minimizes the number of classes and methods

With the above list given in order of importance. Really this breaks out to "Runs all the Tests" and "Refactoring" or making the code better. Simple design is perhaps one of the harder things out there, and yet the most important. When you look at systems that highly scale, it's because they are made up of simply designed components which work very well together.

After the Emergent Design chapter there is suddenly a chapter on Concurrency. This was not something I expected to see, but was very glad to. Too many times books about patterns and design don't address problems like scaling and concurrency. But this chapter does a great job of introducing the necessary steps that need to be taken to deal with concurrency — while still keeping your code clean. The book also provides an appendix which goes even deeper into the concurrency topic which I found to be quite good. Both this chapter and the appendix provide some very valuable rules that I personally have used when writing concurrent systems — like "Get your nonthreaded code working first" and "Run with more threads than processors" to flush out problems.

Chapters 14-16 cover the cleaning up of three different sections of code — an argument processor, JUnit and SerialDate, which is part of the org.jfree package. These chapters really hold true to the warning in the introduction that we'd be going through some code. However, the refinements work very well, and I think that each of them show the value of how much cleaning up the code can improve the readability of even code that works well and seems clean.

The last chapter is a "Smells and Heuristics" chapter which I'm finding to be a handy reference guide for code smells I see. When something is bothering me with code I'm reading, I flip to this section first to see if they have it listed. And with things like "Replace Magic Numbers with Named Constants" you can be sure that all of the advice that should have been beaten into your head long ago is still there, and relevant.

All in all I think this is a very valuable book for any developer wanting to improve how they write code. For senior level people, some things may seem trivial, but if you really take the time to look at the structural changes being made and apply them, you will write better code. For functional developers — the authors believe in OO, but there are still valuable nuggets that are applicable outside of that (like "Use Copies of Data" in the concurrency section). And for any developer, the insights are really good, and you'll find yourself writing down little snippets to hang on the wall.

The challenges with the book are first that it is just as they said — hard work. This is not a flip-through-with-your-mind-shut-off type book. If you want the most out of it, you have to be willing to really work at it. The other challenges are that at times it gets way too Java-centric. All of the code examples being in Java is fine, but some of the chapters (most notably the Systems chapter) really go heavy into Java tools and the Java way which, to me, weren't always applicable across languages.

All in all, I'd highly recommend this book to anyone wanting to improve how they write code. You likely will find yourself violently disagreeing with parts, but the total sum more than makes up for it.

You can purchase Clean Code - A Handbook of Agile Software Craftsmanship from amazon.com. Slashdot welcomes readers' book reviews — to see your own review here, read the book review guidelines, then visit the submission page.

This discussion has been archived. No new comments can be posted.

Clean Code

Comments Filter:
  • by shellster_dude (1261444) on Wednesday September 24, 2008 @01:19PM (#25138711)
    to set right next to my "How to Write Unmaintainable Code".
    • by Horus107 (1316815) <Florian@Lindner.xgm@de> on Wednesday September 24, 2008 @01:23PM (#25138779)

      "How to Write Unmaintainable Code".

      Use Perl!

    • Re: (Score:3, Funny)

      by antifoidulus (807088)
      You have Microsoft's Software Engineering methodologies printed out?
    • by Eudial (590661) on Wednesday September 24, 2008 @03:19PM (#25140811)

      to set right next to my "How to Write Unmaintainable Code".

      It's an artform, some people make it look so easy, but to write truly horrible code takes lot of practice. The key is gotos and ifs (preferably nested deeply). Consider the first "clean" sum generator:


      int sum(int n) {
          if(!n) return 0;
          return sum(n-1) + n;
      }

      We'll see about that:


      int sum() { int n,ro,r; ro=-1; n=r=0;
      f: if(n<10) {
          ro=r;
          r=r+n++;
          }
          if(!(ro^r)==0) goto f2;
          if(n>=10) goto f2;
          goto f;
      f2:
          return r;
      }

      It's important to note just how unmaintainable this function is. It's hard coded (the limit is stored in two different places), so that it only calculates the sum of 1...10, (so, in fact, the entire function could be replaced by a a constant integer). It also has a redundant check, to make sure that the two are the same (so that it doesn't get too large), but it might get too small. Naturally, goto is cruise control for cool.

      • by tjwhaynes (114792) on Wednesday September 24, 2008 @04:06PM (#25141663)

        Consider the first "clean" sum generator:

        int sum(int n) { if(!n) return 0; return sum(n-1) + n; }

        It's interesting you chose this one. I write a lot of Perl (tens of thousands of lines a year) and you might have done this in perl:

        sub sum {
        my $input = shift;
        if ($input =< 0) return 0;
        return sum($input - 1) + $input;
        }

        at which point you would tried it out on some large number and cried about the performance. Now the code is clean (albeit somewhat lacking in type checking) and it would be a shame to lose that cleanliness in the search for performance. This function is deterministic, so if we can cache the result, we can get the performance we want at the expense of memory usage. So we add the following to our code:

        use Memoize;
        memoize('sum');

        and magically, we get caching on the sum subroutine. And our code remains clean and understandable.

        Just because anyone can write unreadable, unmaintainable Perl doesn't mean you have to...

        Cheers,
        Toby Haynes

        • by Eudial (590661) on Wednesday September 24, 2008 @04:52PM (#25142513)

          There are naturally various considerations: Value caching as you mention, whether the programming language optimizes tail recursion, and so forth.

          But the real shenanigans in the function is that you can use mathematics and find that the sum of the series 1...n is n*(n+1)/2 straight away, so making such a function is a moot exercise altogether.

          On the other hand, keeping that sort of mathematics arcane and shrouded in mystery creates thousands of extra programming jobs all across the world.

          • by greg1104 (461138) <gsmith@gregsmith.com> on Wednesday September 24, 2008 @09:59PM (#25146185) Homepage

            If you're operating in integers with a fixed range, computing n*(n+1)/2 might overflow in situations where computing the sum via a series of additions will not. You need to consider which of (n,n+1) is even, divide only that one by two, then multiply by the other odd term to get something that is both a fast computation and utilizes the full range of the integer size you're working with.

            While the above might seem simply pedantic, consider the case where a program built using a naive sum approach that needed the full range was broken by replacing it with the multiplication-based approach. That sort of issue, where clever code is more fragile than the simple implementation, is one reason some programmers shy away from being too clever.

        • by Samah (729132)
          A better example of recursive programming would be factorials or the fibonacci sequence. They're the two most common examples shown in textbooks (in my experience, at least). It's something similar to this:

          int fib(int n) {
          if(n<=1)
          return 1;
          return fib(n-1)+fib(n-2);
          }
          int fact(int n) {
          if(n<=1)
          return 1;
          return n * fact(n-1);
          }

      • Re: (Score:3, Insightful)

        by ChatHuant (801522)

        int sum(int n) {
        if(!n) return 0;
        return sum(n-1) + n;
        }

        Ouch... Your function fails miserably if n is negative. Check if n greater than 0, not !0

      • by Thiez (1281866)

        > int sum(int n) {
        > if(!n) return 0;
        > return sum(n-1) + n;
        > }

        Why do people insist on using recursion in stupid places?!

        Do something like:

        int sum(int n) {
        int result = 0;
        while(n > 0)
        result += n--;
        return result;
        }

        It's way faster since it doesn't have to go crazy with the stack. Also, it isn't harder to understand.

        Somewhat related, one of my peeves is using recursion to calculate factorials. Grrrrr.

        • Re: (Score:2, Informative)

          by Follis (702842)
          The function is tail recursive (or could be if your language requires the sum+n to be n+sum). Hence most interpreters/languages will convert it to a jump. Recursion more closely embodies the Series representation of the sum.
          • by Morty (32057)

            Y'all do realize that sum(n)==(n^2+n)/2, right? A solution that contains either recursion or a loop is inherently bad, with or without memoization. This is a O(1) problem. In Perl:

            sub sum() {
                my $n=shift;
                return 0 if $n=0;
                return ($n**2+$n)/2;
            }

            • Re: (Score:3, Informative)

              by Morty (32057)

              Er. /. killed my less-than. That should say:

              sub sum() {
                  my $n=shift;
                  return 0 if $n<=0;
                  return ($n**2+$n)/2;
              }

            • by Thiez (1281866)

              Once again someone proves that a little maths knowledge can have huge advantages.

              Yay for making me feel stupid though :(

  • by turtleAJ (910000) on Wednesday September 24, 2008 @01:24PM (#25138813)

    According to xkcd
    http://xkcd.com/224/ [xkcd.com]

  • Good review (Score:5, Interesting)

    by raddan (519638) on Wednesday September 24, 2008 @01:25PM (#25138829)
    Wow, good review. I usually skip over the reviews, because I find that they're filled with inside jokes and wandering monologues, but in this case, the review was well-written, thoughtful, and the book seems interesting. I'll probably pick it up. If this was a Slashvertisement, well, it worked.
  • by nwf (25607) on Wednesday September 24, 2008 @01:26PM (#25138849)

    Run with more threads than processors

    Funny, I've found more problems by running with fewer threads than processors. Otherwise, you aren't necessarily getting true concurrency. Running ten threads on a single processor isn't going to help you find some of the pesky concurrency issues that arise from true parallel execution. Of course, one should run with more threads than processors to test that as well.

    Either way, writing non-trivial parallel code isn't easy.

    • Re: (Score:3, Insightful)

      by Anonymous Coward

      So you're saying that you generally find more concurrency issues by running less than one thread on a single processor?

      • Re: (Score:3, Informative)

        by Skrapion (955066)

        +1 Insightful? More like -1 Poor Reading Comprehension.

        If you have a quad-core machine and you run your app with three threads, then you're almost guaranteed that all of your threads will be running at once. On the other hand, if you're running with five threads, and thread #5 conflicts with thread #3, you may never notice that, because thread #5 could be sleeping the whole time.

        And as the GP said, it's a good idea to test your code with more and less treads than the optimal number.

    • It's much easier to write parallel code that way.

       

    • by BitZtream (692029)

      The solution is to make sure your parallel code is trivial, so it can be dealt with in a sane matter. When you start firing off threads that handle complex tasks and interact with other complex tasks often, it becomes VERY hard to keep things sane.

      Break complex tasks down into smaller, trivial ones that can be controlled easier and reduce the concurrancy/contention issues to very small easy to manage chunks.

  • Bravo! (Score:2, Interesting)

    by fferret (58662)
    Even if I was still coding, (moved on to sys/netadmin several years ago,) this book would deserve a huzzah! OK, now we've made it readable, when can we make it efficient, and get rid of all the bells&whistles that have turned software into bloatware!?
  • by The Clockwork Troll (655321) on Wednesday September 24, 2008 @01:29PM (#25138893) Journal

    I don't know that this is the right book for the general problem.

    In my career, the engineers who have been the most effective and most pleasant to work with usually do what they can to be better teammates. This includes but is not limited to: writing good code (or improving/refactoring existing code), and managing their personal interactions with teammates toward rational consensus and general embetterment (a perfectly cromulent word).

    In my experience, the guys who consistently write the worst code also tend to have "lone wolf" mentalities. These are the guys who say, "if it was hard to write, it should be hard to read", and not half-jokingly. I honestly get the impression that growing up they might not have had the sorts of personal interactions that lead a person to be mindful of "playing nice with others". Coding serves a much more selfish end. This doesn't mean they are not "productive" in the absolute sense, but they are solo silo stars and it's hard to pair or team them.

    Put another way, the kind of engineer that would actually benefit from a book like this, has probably already read a book like this.

    The needed book I think is for the manager: psychology of the antisocial geek

    • by Krishnoid (984597) *

      but they are solo silo stars and it's hard to pair or team them.

      Not that hard [yahoo.com], depending on how you do it [communityarts.net]. You really find out who can work well with a partner if you do it right.

    • by dubl-u (51156) * <2523987012.pota@to> on Wednesday September 24, 2008 @01:58PM (#25139421)

      Put another way, the kind of engineer that would actually benefit from a book like this, has probably already read a book like this.

      I think you've created a false dichotomy.

      I haven't read this book yet (although Bob Martin's other stuff is great), but back at the dawn of time, I was working with a team that was all relatively young. When McConnell's "Code Complete" came out, we all went through it pretty excitedly.

      Although we had the right spirit, and we each could have named some of the things in the book, none of us could have articulated all of them. And there were a lot of subtleties that we had never thought of.

      So I'd agree that jerks won't read this and nice graybeards don't need to, there are plenty of people who are perfectly nice that haven't perfected their craft yet. They can use this book.

    • by Soko (17987)

      The needed book I think is for the manager: psychology of the antisocial geek

      For the love of $DEITY, do not listen to ESR. [catb.org]

      That being said, most geeks aren't truly anti-social - they just work differently. Being cut from a different cloth means that you can't always tailor them to your needs - you may have to modify your pattern a tad.

      I've seen where giving an uber-hacker an inexperienced but - and this is key - very bright geek to teach brought them out of their shell a bit. Mostly because he n00b was able

  • yay! (Score:5, Funny)

    by thhamm (764787) on Wednesday September 24, 2008 @01:30PM (#25138921)
    high WTF/minute count

    hot damn. a new and useful [SI] unit. thanks /.
    • Re:yay! (Score:5, Funny)

      by jbeaupre (752124) on Wednesday September 24, 2008 @01:50PM (#25139257)
      Minutes are well defined by a standard, but we still need to think of an easily measurable and reproducible WTF. For instance, waking up some place you don't recognize after drinking 10 shots of tequila the night before. Nope, still too much potential variability. How about pouring 1 liter of water at 0C onto a sleeping person's face? Hmmm. There's got to be something better.
      • Re: (Score:3, Funny)

        by Vizzoor (777022)
        Why not take advantage of all that the internet has given us? 1 WTF = the mental pain proportional to a man spreading his anus a certain distance.
      • Re:yay! (Score:4, Funny)

        by AmberBlackCat (829689) on Thursday September 25, 2008 @12:12AM (#25147165)
        I'm sure the ISO can come up with a standard WTF. It's just that the definition will be so vague that every time we try to implement it, we'll say WTF? And then we'll have our implementation. Pure genius.
    • Re:yay! (Score:5, Funny)

      by Nerdfest (867930) on Wednesday September 24, 2008 @01:59PM (#25139445)
      Reference diagram:

      wtfs-per-minute [think-box.co.uk]
    • Re:yay! (Score:5, Interesting)

      by myvirtualid (851756) <pwwnow.gmail@com> on Wednesday September 24, 2008 @02:02PM (#25139499) Journal

      high WTF/minute count

      hot damn. a new and useful [SI] unit. thanks

      All kidding aside, WTF/minute is a deceptive metric.

      I remember poring over about 30 lines of C for about two plus days with a WTF/minute ratio in the hundreds or thousands. And I knew what the code was supposed to do! It wasn't that I didn't understand it, I didn't understand why the guy who wrote it, a brilliant, brilliant hacker, wrote it the way he did.

      Over two days of following the nested ifs, the gotos (no STL, no exception handling, the gotos made perfect sense), the logic, then BAM!

      "Wow, that's fast!"

      It was the most difficult-to-read code I'd ever read - and it was brilliantly brilliantly fast. (It was a network proxy involving PKI-related messages embedded in LDAP, all based on ASN.1 - all speed improvements were important, his were amazing.)

      Most of the time, high WTF/minute is a good indication that the coder should never, ever have been allowed near a keyboard. Live an awful lot of Java.

      But every now and again, high WTF/minute is a sign of absolute genius. Like a lot of really cool Haskell code. Or wicked perl.

      Hmm, perhaps it's not WTF/minute that we need to consider, but its first order derivative. WTF/minute that peaks then declines to zero suggests genius. WTF/minute that remains constant suggests a bad day or a lot of PHB pressure. WTF/minute that increases without bound suggests brain-damage and a potential career in sales.

      • by dubl-u (51156) *

        But every now and again, high WTF/minute is a sign of absolute genius. Like a lot of really cool Haskell code. Or wicked perl.

        I think that depends on why you're coding. If you're writing code in the spirit that people write poetry, that's fab. Or if you're dealing with a performance-critical section that can't work any other way, then sure, that's fine.

        But for most code (and more and more all the time), maintenance cost vastly overwhelms other factors. Real geniuses get the job done in a way that will last over the long haul.

      • Re:yay! (Score:5, Insightful)

        by Surt (22457) on Wednesday September 24, 2008 @02:23PM (#25139867) Homepage Journal

        And if he had documented his code, explaining the performance advantages, you'd have read it in an hour and reached the same goal, and he wouldn't have dozens of WTFs to his credit.

      • Re:yay! (Score:4, Insightful)

        by Spy der Mann (805235) <spydermann@slashdot.gmail@com> on Wednesday September 24, 2008 @05:18PM (#25143051) Homepage Journal

        Over two days of following the nested ifs, the gotos (no STL, no exception handling, the gotos made perfect sense), the logic, then BAM!

        "Wow, that's fast!"

        And your understanding could've been faster if the author had bothered to include a comment block before the series of ifs/gotos.

        Example:
        /** The following series of if's/gotos are a hardwired implementation of
          * a finite state machine, as documented in the book "Efficient State Machine
          * examples for data processing (ISBN blablablabla, p.15).
          * The machine is as follows:
          *
          * A -> (condition 1) -> B
          * A -> (condition 2) -> C
          * ...
          *
          * The if at point 1 is node A
          * The if at point 2 is node B... etc
          */

        // Point A of the FSM
            if(...) {
                goto B;
            }

        True, comments aren't an excuse for bad code, and WTF/min aren't necessarily accurate. But difficult to understand code without proper in-code documentation is a potential disaster. In fact, I'd call your example a mega-WTF for its lack of comments.

      • Re:yay! (Score:5, Funny)

        by camperdave (969942) on Wednesday September 24, 2008 @05:50PM (#25143571) Journal
        I remember pouring over a few uncommented lines of WANG BASIC trying to figure out what was going on. The guy was doing something like 31.13-18.81 and using that to validate a date. It did not make sense to me. 31.13-18.81=12.32, yet this guy was using the third to sixth digit after the decimal point in his validation. I poured over the code on paper for days. Finally, I got access to the computer and typed in PRINT 31.13-18.81 and pressed enter. The result: 12.319999
    • by sootman (158191)

      SI units always use seconds. :-)

  • by 192939495969798999 (58312) <info AT devinmoore DOT com> on Wednesday September 24, 2008 @01:35PM (#25139005) Homepage Journal

    "Bob Martin (Uncle Bob)'s"

    No wonder he's so good at making clean code... Bob actually is this guy's uncle!

  • Depends on function (Score:2, Interesting)

    by BountyX (1227176)
    Preformance related code and highly efficent code is the opposite of clean code. Clean code is often high level in nature, while efficient and robust code is low level and not pretty. Comments are for readabilty, not the code. Always go for efficiency.
    • Re: (Score:3, Insightful)

      So, you can't write code that is both pretty and efficient? Don't saddle the rest of us with your problems. "Clean code" and "Preformance related code" [sic] are NOT opposites. In fact, I have seen a huge number of situations where I sped something up by cleaning out the code.
      • by dubl-u (51156) * <2523987012.pota@to> on Wednesday September 24, 2008 @02:12PM (#25139681)

        related code" [sic] are NOT opposites. In fact, I have seen a huge number of situations where I sped something up by cleaning out the code.

        I know what you mean, but the guy has a point. I have also often sped things up by removing "performance improvements" that some dolt had added because he thought he was being clever.

        My view, which I guess you'd agree with, is that it's best to start with clean, simple code. Usually, that's plenty fast. If performance tests prove that you have a problem, and a profiler shows you the source of the problem, only then should you sacrifice clarity for speed. And you should only do just enough to meet your performance goals.

    • Re: (Score:3, Insightful)

      by leenks (906881)

      It depends on the situation.

      Efficiency isn't always the desirable outcome as most code doesn't need to be exceptionally efficient - a good developer's time is expensive, and often anything that makes it easier to maintain is a good thing.

      It also means developers can spend more time developing extra functionality rather than coding uber efficient code that usually isn't needed - and then rewrite poorly performing code.

      That said, sometimes you really do want to go for the efficiency - a good developer will kn

    • by Nerdfest (867930) on Wednesday September 24, 2008 @02:04PM (#25139539)
      It's taken me a long time to get myself out of this mindset. I used to always go for the absolute fastest implementation I could come up with. I now generally go with 'fast enough' rather than 'as fast as possible' if the latter is more maintainable. Sometimes the bar for 'fast enough' lowers, but not often.
      • Re: (Score:3, Funny)

        by Nerdfest (867930)
        My apologies ... looking back at my post, I think a little refactoring is in order.
    • by Zet (178940) on Wednesday September 24, 2008 @02:18PM (#25139801)

      This is dead wrong. It's true that sometimes
      purity is sacrificed for performance. But in
      general, good clean code matches a good clean
      design, which emerges when a problem is
      well-understood. Even code that has been
      tweaked to exploit certain compiler anomalies
      can remain clean.

    • Re: (Score:3, Insightful)

      Comments are for readabilty, not the code. Always go for efficiency.

      I endorse the saying "when debugging, ignore the comments - they can be very misleading." Hence I want the code itself to be readable more than I want it to be maximally efficient.

    • by Anonymous Coward on Wednesday September 24, 2008 @02:33PM (#25140049)

      Bzzt, fail, please go buy the book.

      http://en.wikipedia.org/wiki/Optimization_(computer_science)#Quotes

      Clean code is efficient and performs well because you can easily see where the issues are and optimise there appropriately.

    • Re: (Score:3, Insightful)

      by Anonymous Coward

      You're joking I hope.

      Clean is NOT the opposite of efficient.

      >Comments are for readabilty, not the code

      No. NO. NO!

      There is no excuse for writing unreadable code. The code itself must be readable. Then comments are necessary to supplement the code, to help understanding the tricky parts, explain the reasons that lead to choose this or that method to solve a problem or -the most important- explain the INTENT of the code. How many projects (FLOSS and closed source) have I seen that were a mess because they d

    • by BountyX (1227176)
      To all who disagree: please note my title. I agree with all of you that it DEPENDS on the implementation (hence my title). A good developer knows how to balance it out.
      Clean code can be high performing, but most of the time, high performing code is not clean. Look at encryption algorithms. Look at Qt's premoc compiler. The nature of performance in code is inherently low-level. Want to maximize a function in C++ to its fullest extent? Great, take it too far and you end up with parts using inline ASM. Most p
    • by jgrahn (181062) on Wednesday September 24, 2008 @03:06PM (#25140623)

      Preformance related code and highly efficent code is the opposite of clean code. Clean code is often high level in nature, while efficient and robust code is low level and not pretty.

      Clean code is the enemy of robust code? I've never heard anyone state that before.

      Comments are for readabilty, not the code. Always go for efficiency.

      Even when I don't need it? You don't make sense.

  • by viljun (1267170) on Wednesday September 24, 2008 @01:41PM (#25139105) Homepage
    ... we all write clean code. Let's buy this book to our fellow workers.
  • Clean code? (Score:4, Insightful)

    by Mycroft_514 (701676) on Wednesday September 24, 2008 @01:42PM (#25139113) Journal

    Just write the code like it is YOU that has to debug it at 4am. Nothing to see here, move along, move along.

    • Bad idea. If I know that I will have to debug it, I can use whatever variable names I want. Which is not necessarily what makes sense to other people.
      • Re:Clean code? (Score:4, Insightful)

        by Mycroft_514 (701676) on Wednesday September 24, 2008 @03:46PM (#25141313) Journal

        LIKE it has to be you - not that it will. If I write code like that, then my buddy can debug it at 4am and not have to call me to fix it. And if his code is like that, I can figure out what is wrong easily and not have to spend hours fixing it.

      • by tirerim (1108567)
        Yeah, that's not going to help when I'm debugging it two years later and have no clue what I was thinking when I wrote it. I have seriously gone in to look for a bug, said to myself, "What idiot wrote this incomprehensible garbage?", and looked at the cvs log only to discover that the idiot was me.
    • Re: (Score:3, Insightful)

      by fyoder (857358) *

      Just write the code like it is YOU that has to debug it at 4am.

      It's likely it will be me who has to debug it at 4 am. Writing clear code with helpful comments where necessary makes me appreciate my past self, since if the code is more than a few weeks old, I've already forgotten a whole lot. If it's more than a year old, it might as well have been written by someone else. This is, in fact, how I learned the value of clear coding. It wasn't for others, but for myself. The early shit I wrote in perl looks like something that might originally have been scrawled in fe

    • As Damian Conway writes in Perl Best Practices (much like this book, it seems),

      Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

  • by steveha (103154) on Wednesday September 24, 2008 @01:42PM (#25139119) Homepage

    I will seek out Clean Code and take a look at it. But I'd like to take this opportunity to plug a classic favorite of mine.

    The Elements of Programming Style by Kernighan and Plauger is an old book... so old that all its examples are in either Fortran or PL/I. It doesn't matter. They take examples of code, ruthlessly dissect each one, then rewrite each one; and in every case, their rewritten version is hugely improved. Then they present a rule that encapsulates what they did to improve the example. Their writing is clear, insightful, and entertaining. This is a book that I pull out again and again and re-read.

    http://www.amazon.com/Elements-Programming-Style-Brian-Kernighan/dp/0070342075/ref=sr_1_2?ie=UTF8&s=books&qid=1222277636&sr=1-2 [amazon.com]

    steveha

  • by ivandavidoff (969036) on Wednesday September 24, 2008 @01:43PM (#25139123)
    But seriously: I've always thought that coding Can be poetry
  • by bugeaterr (836984) on Wednesday September 24, 2008 @01:48PM (#25139213)

    You should see the SOAP request I wrote last year!
    [rim shot]
    Good night! Don't forget to tip your waiters!

  • Clean Code (Score:5, Insightful)

    by codepunk (167897) on Wednesday September 24, 2008 @01:49PM (#25139243)

    I recently ran across a situation where I looked a piece of code someone else wrote and thought to myself that
    is really ugly. I set out to write a clean version but gave up when I figured out that no matter what I did
    this was still going to be ugly. Not so much because of a poor job coding it but because of what the code had
    to actually perform.....I guess it is just not possible to always put lipstick on the pig.

    • by dubl-u (51156) *

      I think a better way to look at this is that at the time you couldn't think of a better way. Often I've come back to a problem later and found some better abstraction. Or asked a colleague who has a nice trick to sort things out.

      On some days, I think the the main job of a programmer is to hide the ugliness as well as possible. The code bases that really scare me are the ones where people have admitted defeat and let the ugliness seep everywhere.

      • by codepunk (167897)

        Actually there are off the shelf products that could handle the situation easily, cleaner and much more robust. However
        we where told to not spend any time on it since it is getting replaced. We all know how that story goes, that same line has been
        used for the last 6-8 years and there is still no replacement in site....the ugliness lives on...

      • by mdf356 (774923)

        Last week I rewrote some code that had been annoying me since early 2003. I knew intuitively it could be done better at the time but I didn't have time (or, I think, skills at the time) to dig into it. After 5+ years of the code working okay but bugging me every time I came across it again, having hacks added on top, and constant improvement of the stuff around it (including a lot of deleting) I finally had my a-ha moment.

        32 modified files and thousands of lines of code later, it was done, and my team rej

    • by Moochman (54872)

      This may be the case, but what you *can* do is make sure that all of the publicly exposed methods are at least easy to use.

      Thing is, every class written is in a way an API unto itself. So even if it's ugly inside, make sure it's easy to use outside.

  • by Corporate Gadfly (227676) on Wednesday September 24, 2008 @01:50PM (#25139269)

    Here's an interview [blog.jaoo.dk] with Robert Martin (part of a panel) where he talks about cheating the boss (by writing good code without permission to use the time).

    • by dubl-u (51156) * <2523987012.pota@to> on Wednesday September 24, 2008 @02:23PM (#25139875)

      I totally agree with Bob Martin here.

      Suppose I go into the doctor and say, "I'm tired and not getting enough done. Please give me a bucket of amphetamines." The doctor will say no, as that would be likely to cause harm, followed by death. Instead, they'll try to figure out what's really going on, and help me appropriately. That's what professionals do.

      If a boss comes to me and tells me that for the new banking software they'd like me to skip testing, exception handling, and error logging, I'll say no. Instead, I'll ask them what their real goal is, and suggest ways they can achieve that.

      Over and over I see developers offering to write unmaintainable garbage, only to get in hot water in a year's time because productivity is in the toilet. It's not even fun the first time, but people keep on doing it. They should stop.

  • who wants (Score:4, Funny)

    by nawcom (941663) on Wednesday September 24, 2008 @01:54PM (#25139323) Homepage
    a perfect example of unclean code? http://thepiratebay.org/torrent/3497574/Windows_2000_source_code [thepiratebay.org]
  • by mellon (7048) on Wednesday September 24, 2008 @01:54PM (#25139325) Homepage

    For some reason, whenever I see that word in reference to programming, I want to run screaming in the opposite direction. Does that make me a bad person?

    • by mustafap (452510)

      If it does, there are a lot of us bad people around.

    • Re: (Score:3, Insightful)

      by Tassach (137772)
      No, it's natural to fear the (mis)application of the buzzword du jure. Agile has some good ideas, but like any other development methodology, too many people just blindly follow the formula without really understanding WHY it works or realizing that software development isn't a cookie-cutter process. Any methodology like Agile, or CMM, or whatever, is just a way of keeping the code monkeys in their cages grinding out code. There's only one way to write great code: hire great programmers. Management ty
    • Re: (Score:3, Insightful)

      Abso-freakin-lutely! Agile isn't such a bad idea in principle but you tend to find that people who rave-on about it seem to think it somehow relieves you of the burden of creating project plans, software specifications and the like.

      For some reason, whenever I see that word in reference to programming, I want to run screaming in the opposite direction. Does that make me a bad person?

    • I had the pleasure of recording a graduate-level CS class taught by Chris Gilmore at Portland State University on agile methodologies. A lot of what he said actually made a lot of sense. You should give agile an honest chance.
  • Superflous (Score:2, Informative)

    by jDeepbeep (913892)
    I don't see who the audience is going to be, aside from n00bs. No senior dev is going to buy this unless it's for a hint hint type of gift to a less-experienced colleague.

    If you're in the field, you either know this stuff already and use it (won't be purchasing the book), know this stuff and don't use it (won't be purchasing the book), know this stuff and don't care (you wouldn't be pained to go purchase a book about it).

    Bob's really chosen a microscopic target reading audience imo.
  • whitespace (Score:4, Funny)

    by doti (966971) on Wednesday September 24, 2008 @02:43PM (#25140259) Homepage

    you can't get cleaner than that [wikipedia.org]!

  • Some idiot in IT for a startup I worked for wrote some perl script that checks to see if our web page was up, and if it was down, it emails to 6 pages. Our ISP had a problem, and there were some other network issues and everyone just turned off their pagers and the script was constantly sending e-pages to all 6 pages, for a total for $1000/day. I guess the idiot didn't space out the times between checking the web site and paging, as it just constants sent e-pages. WTF!

  • I like these types of books because as the lone developer for a consulting company, I don't have much of a chance to interact with other devs. We mostly focus on everything else, with me left to do any and all the software work that comes up. I've been out of school for almost 10 years now, and it's nice to find something that helps remind me of different ways to do things, or things that will help me later (or someone that may come behind me).
  • Just follow one coding standard and stick to it, preferably a aerospace and/or military related one (as those are the ones that happen to be the best worked-out I've seen).

    Personally, I prefer 2RDU00001 [jsf.mil], because not only it has the rules, but explains why every single specific rule makes sense, thus making it easier to enforce in a team.

Whenever people agree with me, I always think I must be wrong. - Oscar Wilde

Working...