Clean Code
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.
to set right next to my "How to Write Unmaintainable Code".
According to xkcd
http://xkcd.com/224/
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.
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.
I don't know, but it works for me.
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!?
We're through being cool! Eliminate the ninnies and the twits! -Devo
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
There are no karma whores, only moderation johns
high WTF/minute count
/.
hot damn. a new and useful [SI] unit. thanks
Its a pity us computer science / programming students are not taught writing clean code in classrooms. Clean is simple and intuitive. Its just what generic programming books illustrate and teachers condone. I really hate it when teachers do not take care of a students code quality/ cleanliness / and design as long as it works and has plenty of comments.
By the time we graduate writing unclean code becomes a habit. Something which could be checked at the very starting becomes a huge enough problem to require professional books.
They provide a really good source of variable names. After that you could use town names... you're bound not to run out of variable names that way.
...because there is no cleaner code than code for Linux desktops.
"Bob Martin (Uncle Bob)'s"
No wonder he's so good at making clean code... Bob actually is this guy's uncle!
stuff |
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.
Trying to install linux on my microwave, but keep getting a kernel panic...
... we all write clean code. Let's buy this book to our fellow workers.
Ville / Varuste.net
Just write the code like it is YOU that has to debug it at 4am. Nothing to see here, move along, move along.
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
steveha
lf(1): it's like ls(1) but sorts filenames by extension, tersely
But seriously: I've always thought that coding Can be poetry
You should see the SOAP request I wrote last year!
[rim shot]
Good night! Don't forget to tip your waiters!
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.
Got Code?
Here's an interview with Robert Martin (part of a panel) where he talks about cheating the boss (by writing good code without permission to use the time).
Corporate Gadfly
Jonathan Archer: the most beaten up Enterprise captain in Star Trek history
Dijkstra would never ever be the goto guy because Goto Considered Harmful.
a perfect example of unclean code? http://thepiratebay.org/torrent/3497574/Windows_2000_source_code
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?
It's much easier to write parallel code that way.
Deleted
Any code where the number of threads is not determined by the design is trivial parallel code.
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.
Reply to That ||
Variable names like MAX_STUDENTS_PER_CLASS??? That looks like COBOL! My head! oh, my head! What ever happened to that Microsoft notation?
you can't get cleaner than that!
factor 966971: 966971
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!
Sounds like a problem with cron, not with the script. Integration, not unit test.
Planning to be moderated ± 1: Bad Pun.
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).
I will shred my adversaries. Pull their eyes out just enough to turn them towards their mewing, mutilated faces. Illyria
Another excellent book is the book Code Complete published by Microsoft Press. Lots of really good advice for who to write good code and maintainable code.
New hires at WinTellect have to read it. Mandatory.
can be found here
And what does it have to do with Perl ?
Does anyone know of one or two page summary of this book / general style recommendations? I manage a software development team, and while I'd like to have everyone read this, I think it may be more reasonable to give them a "cheat sheet" of sort.
At the very least, some would take to it immediately and they could always use it as a reference for enforcing things later.
Opinions were like kittens / I was giving them away
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, 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.
Screw the FSM - Real geeks believe in the Invisible Pink Unicorn
Well, if it would have been written in LISP, it would only have taken 4 lines.
She made the willows dance
The book's cover is the Sombrero Galaxy.
ceci n'est pas un sig
The mentioned diagram is the original source of the whole joke.
At a coffee shop near you!
"The ability to delude yourself may be an important survival tool" - Jane Wagner -
Sounds to me like the problem was with the idiot who signed a SLA allowing for that much downtime and to the owners of pagers for turning them off without investigating. IT worked as it should have.
It's simple: I demand prosecution for torture.
By including files multiple times, but with different macro definitions each time. One include sets up the actual function bodies, another sets up an import table, properly prototyped to be typesafe, another generates little assembler stubs that need decorated names to work okay, another... and so on. This involved writing preprocessor macros that inserted comma's between, but not before or after, a list of whitespace delimited arguments. That the comma has a special meaning to the preprocessor didn't help, but it works now. Not clean, perhaps, but this way I can keep related definitions in different places consistent automatically, eliminating a lot of potential human error and forgetfulness.
that's it. said it all in the subject. continue scrolling down.
Eclipse PDE and Me
"you ladies" - new here?
It is probably a wonderful book. But the very concept of "clean code" is, to me, a pre-occupation with the wrong things. It is as if the designers of the Large Hadron Collider were most concerned with the neatness of the machining of parts. What about design? What about patterns? Code is a means to an end, not an end in itself.
How the hell can you review a book that is not even available for the public to buy?
Smells like Slashdot Pepsi.
... you might want to add "numerical recipes" to your wishlist:
http://www.nrbook.com/nr3/
"Violence is the last refuge of the competent, and, generally, the first refuge of the incompetent" - Thing_1
When mailing lists where still massively used, a new feature in mailboxes upped emails an order of magnitude overnight. The feature is still among us: "auto-reply when absent" and caused mailing lists to send out new digests every time it got an out of office reply. Registered users got a new mail every minute or so, each time growing in size as the old message was included.
"Violence is the last refuge of the competent, and, generally, the first refuge of the incompetent" - Thing_1
Behind every WTF moment is something that seemed like a perfectly reasonable idea at the time.
Every programmer has his own little set of tips'n'tricks when coding, ranging from indenting in source code, to using brackets & keep code organized. Some examples can be found here (http://www.mattiasgeniar.be/programming/little-coding-habits/), and it's what makes it challenging for us to work on group-projects, where everyone uses his own methods and ways to organize his/her code.
It's all in the eye of the beholder... What you think is clean code doesn't mean someone else thinks the same about it.. Everybody has his/her own favorite way of doing stuff, and for them it's clean, but for others it isn't.. I have seen it so many times now.. someone who tell's you there is a rule to cleancode it lying, those are his rules... as I said, cleancode is something in the eye of the beholder...
Found this a while ago, tend to agree with most of it ;)
http://gwaredd.blogspot.com/2005/08/good-code.html
Some of them have to be seen to be believed.
Patrick Doyle
I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
Alaso known as the entire aSmallWorld codebase.
I'm in the middle of the book, and so far, I haven't seen much that I haven't seen before. In other places I think the author misses things, or I just plain disagree
Example Miss:
I the section on comments, he misses one of the most import reasons to comment/type of comment - the explaination of WHY you used a particular algorythm. I have a real life example - In one of my projects, there is a vendor API call AAA that seems to do exactly what we want, but it has 2 HUGE problems, the first being that despite the vendors docs claiming the API is thread safe, it isn't (this has been confirmed by the vendor), and if you use the call one item at a time, the 80ms each call takes kills us on our large data sets (the data set we use is something like 15x the size of the average customer). So, we developed a hybrid method that uses 2 different API calls, which ARE slower for 1st call (about 115ms), but then we can do the rest of the work locally. The comment documents WHY we are doing this, points to a longer document in the SCS that explains the details
Example disagree:
He uses the example of a gas tank and an interface. The "Bad" interface gives you CapacityInGallons and GallonsRemaining, while the "Good" interface gives you "PercentageOfFuelRemaining". Frankly, in most situations, I'd want to know what the first interface gives me - If I hook a 5 gallon hydrogen tank to the the space shuttle, I can have 100% of the fuel remaining, but I'm NOT going very far. Percentage of fuel remaining is useless unless you know what size the tank IS
-- 73 de KG2V For the Children - RKBA! "You are what you do when it counts" - the Masso