Beta

Slashdot: News for Nerds

×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Clean Code

samzenpus posted more than 5 years ago | from the read-all-about-it dept.

Programming 214

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.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.

cancel ×

214 comments

fp (-1, Troll)

Anonymous Coward | more than 5 years ago | (#25138673)

speaking of clean, you ladies need to shave your beavers.

I really want a copy of this... (5, Funny)

shellster_dude (1261444) | more than 5 years ago | (#25138711)

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

Re:I really want a copy of this... (5, Funny)

Horus107 (1316815) | more than 5 years ago | (#25138779)

"How to Write Unmaintainable Code".

Use Perl!

Re:I really want a copy of this... (2, Funny)

StarfishOne (756076) | more than 5 years ago | (#25139613)

A real programmer is lazy and uses a random character generator. ;p

Re:I really want a copy of this... (5, Funny)

Surt (22457) | more than 5 years ago | (#25139765)

Mod parent redundant, gp already said 'Use Perl!'

Re:I really want a copy of this... (2, Funny)

bb5ch39t (786551) | more than 5 years ago | (#25140199)

Pah! You want unmaintainable code? Use APL! Now that is a real programmer's language! A real sick programmer who likes Greek letters along with other make up symbols not in any other language on this planet.

Re:I really want a copy of this... (1)

MikeDirnt69 (1105185) | more than 5 years ago | (#25140609)

"How to Write Unmaintainable Code".

Use Perl!

Plus GOTOs

Re:I really want a copy of this... (3, Funny)

antifoidulus (807088) | more than 5 years ago | (#25138835)

You have Microsoft's Software Engineering methodologies printed out?

Re:I really want a copy of this... (0)

Anonymous Coward | more than 5 years ago | (#25138979)

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

Perhaps you also want a copy of The American Spelling Book [google.com] to sit next to the code books? Just helping out - so you don't get nitpicked next time you post.

Re:I really want a copy of this... (1, Insightful)

Anonymous Coward | more than 5 years ago | (#25139495)

Um, he used proper grammar. He is putting this book beside the other, therefore he is setting it next the other. Both books would be sitting on something.

Re:I really want a copy of this... (0)

Anonymous Coward | more than 5 years ago | (#25140519)

Thankyou! I'm glad you figured-out what he was complaining about, I'd thought that somehow "unmaintainable" was another one of those words spelt differently by Americans than the rest of the English speaking world. Yet I couldn't find it spelt any other way.

Um, he used proper grammar. He is putting this book beside the other, therefore he is setting it next the other. Both books would be sitting on something.

Re:I really want a copy of this... (4, Funny)

Eudial (590661) | more than 5 years ago | (#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.

God's code... (5, Funny)

turtleAJ (910000) | more than 5 years ago | (#25138813)

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

Good review (5, Interesting)

raddan (519638) | more than 5 years ago | (#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.

Re:Good review (5, Funny)

bennomatic (691188) | more than 5 years ago | (#25138935)

Good meta-review. I usually skip... Ok, you get the joke.

Re:Good review (1)

dubl-u (51156) | more than 5 years ago | (#25139311)

Good meta-meta... I... joke.

Re:Good review (0)

Anonymous Coward | more than 5 years ago | (#25139393)

Mod parent up, +1 Brevity.

Re:Good review (1)

Godji (957148) | more than 5 years ago | (#25141135)

What, you mean that was a META-Slashvertisement?! I think my head just exploded...

Re:Good review (5, Informative)

Anml4ixoye (264762) | more than 5 years ago | (#25139065)

Thanks. It was *not* a Slashvertisement - I try my best to actually make the Book Reviews I do meaningful. ;)

Re:Good review (-1, Redundant)

Jansingal (1098809) | more than 5 years ago | (#25139547)

Wow, a good comment. I usually skip over the comments, because I find that they're filled with inside jokes and wandering monologues, but in this case, the comment was well-written, thoughtful.

Run with more threads than processors (5, Insightful)

nwf (25607) | more than 5 years ago | (#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:Run with more threads than processors (3, Insightful)

Anonymous Coward | more than 5 years ago | (#25139085)

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

Re:Run with more threads than processors (0)

Anonymous Coward | more than 5 years ago | (#25140535)

He is talking about the case where you have 1024 processors and 750 threads.

Write your code backwards (1)

Colin Smith (2679) | more than 5 years ago | (#25139771)

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

 

Allow me to make a bold claim (1)

Griffon26 (709915) | more than 5 years ago | (#25139845)

Any code where the number of threads is not determined by the design is trivial parallel code.

Re:Run with more threads than processors (1, Funny)

Anonymous Coward | more than 5 years ago | (#25140185)

It's amazing how much code there is that doesn't run as expected when you run it with fewer threads than processors.

Especially on a single-processor machine.

Re:Run with more threads than processors (1)

warhammerkid (910986) | more than 5 years ago | (#25141067)

He's not saying that you should debug concurrency with more threads than processors. What he is saying is that you should first work out issues not related to concurrency in threaded code, and then fix the concurrency issues using whatever method you deem correct.

Bravo! (2, Interesting)

fferret (58662) | more than 5 years ago | (#25138863)

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!?

Re:Bravo! (-1, Troll)

Anonymous Coward | more than 5 years ago | (#25139001)

netadmins gobble cock

Re:Bravo! (1)

sakdoctor (1087155) | more than 5 years ago | (#25139271)

Is this really what passes for informative these days?

Re:Bravo! (1)

bugeaterr (836984) | more than 5 years ago | (#25139459)

huzzah!

OK, for which Renaissance Festival are you sys/netadmin'ing for and is it hard to type whilst wearing plate mail and hoisting a flagon of mead?

before any healing can begin, the bleeding must.. (-1, Offtopic)

Anonymous Coward | more than 5 years ago | (#25138877)

be stopped. all the bleeding is still taking place in the deserts (at an unmentionable cost?). taking your eye off the ball is the trick.

Re:before any healing can begin, the bleeding must (-1, Offtopic)

Anonymous Coward | more than 5 years ago | (#25139463)

I would much prefer that they take their balls off my eyes. I don't need to get teabagged to know that code is sloppy.

Is the problem one of craft or mentality? (5, Interesting)

The Clockwork Troll (655321) | more than 5 years ago | (#25138893)

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

Re:Is the problem one of craft or mentality? (1)

Krishnoid (984597) | more than 5 years ago | (#25139301)

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.

Re:Is the problem one of craft or mentality? (5, Insightful)

dubl-u (51156) | more than 5 years ago | (#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.

Re:Is the problem one of craft or mentality? (1)

Soko (17987) | more than 5 years ago | (#25139951)

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 to not only learn the methods in coding, but how to properly speak to the geek and have them communicate.

Even then, don't expect them to always fit in a team or be able to communicate exactly what they're thinking. The latter is usually due to bandwidth limitations - hard to explain 500 ideas all at the same time without frustrating the person they're communication with.

yay! (5, Funny)

thhamm (764787) | more than 5 years ago | (#25138921)

high WTF/minute count

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

Re:yay! (4, Funny)

jbeaupre (752124) | more than 5 years ago | (#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:yay! (3, Funny)

Vizzoor (777022) | more than 5 years ago | (#25139623)

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! (4, Funny)

Nerdfest (867930) | more than 5 years ago | (#25139445)

Reference diagram:

wtfs-per-minute [think-box.co.uk]

Re:yay! (4, Interesting)

myvirtualid (851756) | more than 5 years ago | (#25139499)

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.

Re:yay! (1)

dubl-u (51156) | more than 5 years ago | (#25139611)

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! (4, Insightful)

Surt (22457) | more than 5 years ago | (#25139867)

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! (1)

MikkoApo (854304) | more than 5 years ago | (#25140191)

I think the original metric is based on the sign of the WTFs. Positive WTFs are rare and usually the metric goes below zero, sometimes way below ;-)

Kidding aside, I'm just reading the book (chapter 2 - Meaningful Names) and from what I've read so far, the book seems really good and useful. In the beginning the author states that some of the guidelines might not work for everyone but at least the author gives a lot of food for thought.

Re:yay! (1)

sootman (158191) | more than 5 years ago | (#25140073)

SI units always use seconds. :-)

This should come naturally but... (1)

prayag (1252246) | more than 5 years ago | (#25138987)

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.

Re:This should come naturally but... (0)

Ethanol-fueled (1125189) | more than 5 years ago | (#25139265)

"Clean" in the newbie/classroom sense is subjective. Do you mean clean as in compact, or clean as in readable? What's good for the student is often not what's good to a style-nazi instructor. For example:

public static List getShortestPathTo(Vertex target) {
List path=new ArrayList();
for(Vertex vertex=target; vertex!=null; vertex=vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}

Vs.

public static List getShortestPathTo(Vertex target)
{
List path = new ArrayList();

for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);

Collections.reverse(path);
return path;
}

I know, looks like crap because of /.'s gimpy text parser.

Re:This should come naturally but... (1)

halsver (885120) | more than 5 years ago | (#25139419)

If your TA (who is the one most likely to grade your code) ever talks to you, I would hope he or she mentions how readable your code is.

That said, I have met some very anti-social CS TAs, but they would express their dislike for unreadable code with low marks.

Re:This should come naturally but... (1)

PainKilleR-CE (597083) | more than 5 years ago | (#25140405)

It should be noted, though, that many students have been through classes in which their code was not reviewed if it compiled and passed the tests required by the assignment.

This is especially true of larger projects done for class, as even the TA has something better to do than review the poorly-written code of 60 CS students in a first-year class.

baby names (0, Flamebait)

Eternal Annoyance (815010) | more than 5 years ago | (#25138993)

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.

Does the book mention Linux desktops? (0)

Anonymous Coward | more than 5 years ago | (#25138995)

...because there is no cleaner code than code for Linux desktops.

Bob's your uncle? (2, Funny)

192939495969798999 (58312) | more than 5 years ago | (#25139005)

"Bob Martin (Uncle Bob)'s"

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

Sys admin? (-1, Troll)

Anonymous Coward | more than 5 years ago | (#25139033)

Come on, these chimps are there to fix jammed printers, load back-up media, and create the odd user account. Most "admins" can barely cope with BASH scripting, let alone real code, or they're point-n-click drones with their MSCE butt-wipe paper.

good start (-1, Troll)

larry bagina (561269) | more than 5 years ago | (#25139067)

when you're done cleaning your code, maybe you can clean yourself? Take a shower daily. Use soap. Wipe your ass. Wear clean clothes. Trim or shace facial hair.

Depends on function (2, Interesting)

BountyX (1227176) | more than 5 years ago | (#25139083)

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:Depends on function (3, Insightful)

Louis Kleiman (1371245) | more than 5 years ago | (#25139347)

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.

Re:Depends on function (4, Insightful)

dubl-u (51156) | more than 5 years ago | (#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:Depends on function (2, Insightful)

leenks (906881) | more than 5 years ago | (#25139415)

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 know when to do that and document appropriately (both inside the code and out - the last thing you want when planning a large change is to not know what is involved until you get neck deep in code).

Re:Depends on function (1)

PainKilleR-CE (597083) | more than 5 years ago | (#25140981)

Besides, you don't need as many comments if your code is easy to read. Reserve comments for making your intentions clear (so people can make sure the code works as intended), and explaining hacks and work-arounds when things don't work the way they should. Even my first year CS teacher told us not to use the alphabet as the source of our variable names, and most of us still had to learn the hard way.

Re:Depends on function (4, Insightful)

Nerdfest (867930) | more than 5 years ago | (#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:Depends on function (4, Interesting)

Zet (178940) | more than 5 years ago | (#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:Depends on function (2, Insightful)

Frequency Domain (601421) | more than 5 years ago | (#25139857)

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.

Re:Depends on function (5, Insightful)

Anonymous Coward | more than 5 years ago | (#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:Depends on function (3, Insightful)

Anonymous Coward | more than 5 years ago | (#25140119)

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 don't bother with those simple and basic principles... Sad.

Re:Depends on function (1)

BountyX (1227176) | more than 5 years ago | (#25140611)

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 preformance related code makes use of multiple calls in a single function to ensure that the scope usage is as short as possible. I wouldn't call 20 functions in one line of code readable. How do most people make it readable? Separate function return values into variables causing the variable to live in the entirety of its parentâ(TM)s scope. So you end up with less memory optimization. I guess when I think of performance related code, I think more of code optimizations (i.e. const int &var) that end up making a single line of code more complex and hence, less readable. I wanted to imply that many code optimizations result in less readable code due to the low-level nature and extra modifiers required to optimize code.

Re:Depends on function (3, Insightful)

jgrahn (181062) | more than 5 years ago | (#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.

Of course... (5, Funny)

viljun (1267170) | more than 5 years ago | (#25139105)

... we all write clean code. Let's buy this book to our fellow workers.

Clean code? (3, Insightful)

Mycroft_514 (701676) | more than 5 years ago | (#25139113)

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

Re:Clean code? (0)

Anonymous Coward | more than 5 years ago | (#25139321)

Just write the code so that it is ONLY you that can debug it at 4am.

Fixed that for you. And yes...I'm a consultant. :-)

Re:Clean code? (1)

neuromanc3r (1119631) | more than 5 years ago | (#25140693)

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? (3, Insightful)

Mycroft_514 (701676) | more than 5 years ago | (#25141313)

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.

The Elements of Programming Style (5, Informative)

steveha (103154) | more than 5 years ago | (#25139119)

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

So Dijkstra is no longer the go-to guy on this? (3, Funny)

ivandavidoff (969036) | more than 5 years ago | (#25139123)

But seriously: I've always thought that coding Can be poetry

Answer: definetely no! (1)

ThiagoHP (910442) | more than 5 years ago | (#25139313)

So Dijkstra is no longer the go-to guy on this

Dijkstra would never ever be the goto guy because Goto Considered Harmful [acm.org] .

Re:Answer: definetely no! (1)

ivandavidoff (969036) | more than 5 years ago | (#25139769)

Dude, I know. That's why it's funny to call him the "go-to guy".
*sigh*

Re:Answer: definetely no! (1)

ThiagoHP (910442) | more than 5 years ago | (#25140011)

The subtler the humor, the better. Kudos to you. :)

If you think THAT's clean code (5, Funny)

bugeaterr (836984) | more than 5 years ago | (#25139213)

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

Clean Code (4, Insightful)

codepunk (167897) | more than 5 years ago | (#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.

Re:Clean Code (1)

dubl-u (51156) | more than 5 years ago | (#25139501)

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.

Re:Clean Code (1)

codepunk (167897) | more than 5 years ago | (#25139763)

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...

Is it professional to cheat your boss? (2, Informative)

Corporate Gadfly (227676) | more than 5 years ago | (#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).

Re:Is it professional to cheat your boss? (4, Interesting)

dubl-u (51156) | more than 5 years ago | (#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.

You had me right up to "Agile." (3, Insightful)

mellon (7048) | more than 5 years ago | (#25139325)

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?

Re:You had me right up to "Agile." (1)

mustafap (452510) | more than 5 years ago | (#25139955)

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

Re:You had me right up to "Agile." (2, Insightful)

Tassach (137772) | more than 5 years ago | (#25140111)

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 types love to believe that a swarm of code monkeys can produce on the same level as a brilliant top-tier programmer. They can't.

Re:You had me right up to "Agile." (0)

Anonymous Coward | more than 5 years ago | (#25140317)

What is "Buzzword du jure": a catchphrase used by a judge?

I think you meant 'Buzzword du jour'

Re:You had me right up to "Agile." (3, Insightful)

Enter the Shoggoth (1362079) | more than 5 years ago | (#25140387)

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?

Superflous (2, Informative)

jDeepbeep (913892) | more than 5 years ago | (#25140081)

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.

ARG!!! Looks like COBOL (1)

bb5ch39t (786551) | more than 5 years ago | (#25140169)

Variable names like MAX_STUDENTS_PER_CLASS??? That looks like COBOL! My head! oh, my head! What ever happened to that Microsoft notation?

Re:ARG!!! Looks like COBOL (0)

Anonymous Coward | more than 5 years ago | (#25140325)

Variable names like MAX_STUDENTS_PER_CLASS???

It should be MAXIMUM_STUDENTS_PER_CLASS. That way, there is NO doubt as to what value it is intended to contain. :]

whitespace (3, Funny)

doti (966971) | more than 5 years ago | (#25140259)

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

The 10 Line Perl Script that Cost Us $1000 per Day (1)

c0d3r (156687) | more than 5 years ago | (#25140349)

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!

Re:The 10 Line Perl Script that Cost Us $1000 per (1)

stubob (204064) | more than 5 years ago | (#25140547)

Sounds like a problem with cron, not with the script. Integration, not unit test.

Re:The 10 Line Perl Script that Cost Us $1000 per (1)

sergstesh (929586) | more than 5 years ago | (#25140733)

And what does it have to do with Perl ?

Quite Useful I think (1)

Thyamine (531612) | more than 5 years ago | (#25140561)

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).

Code Complete (1, Informative)

Anonymous Coward | more than 5 years ago | (#25140575)

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.

The best resource for clean code... (0)

Anonymous Coward | more than 5 years ago | (#25140685)

can be found here [cs.ru.nl]

A one / two page version of this book? (1)

jelling (412920) | more than 5 years ago | (#25141531)

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.

Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Create a Slashdot Account

Loading...