Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

share|improve this question

closed as not constructive by Thomas Owens Mar 26 '13 at 11:59

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

14  
Hmm.. How about "clean" code? –  Robert Harvey Dec 22 '10 at 15:53
45  
Still not buying that 'girl-code' is a term that actually gets used, or should be used. –  Doug Dec 22 '10 at 15:56
8  
First time I hear that term, and I can guarantee you that I'll never use it. ;) Clean code will do. –  MetalMikester Dec 22 '10 at 15:57
12  
@Doug, I agree. 'girl-code' is a sexist statement (unlike, say, code cowboy) similar to other statements which are generally used to deride a male for having handwriting "like a girl." While humorous, it isn't appropriate. –  Stephen Furlani Dec 22 '10 at 16:04
8  
Yes. I go screen by screen (scrolling) while holding an alcohol wipe to the monitor. My code is freaking sterile !!! –  Tim Post Dec 22 '10 at 16:11

23 Answers 23

up vote 26 down vote accepted

I would argue that many of us do not write clean code. And generally, that's not our job. Our job as software developers is to deliver a product that works, on time.

I am reminded of Joel Spolsky's blog post: The Duct Tape Programmer.

He quotes from Coders at Work:

At the end of the day, ship the fucking thing! It’s great to rewrite your code and make it cleaner and by the third time it’ll actually be pretty. But that’s not the point—you’re not here to write code; you’re here to ship products. - Jamie Zawinsky

I am also reminded of Robert Martin's blog response:

So. Be smart. Be clean. Be simple. Ship! And keep a small roll of duct tape at the ready, and don’t be afraid to use it. - Uncle Bob

If the code a developer write happens to be clean AND work (is deliverable), so be it, good for everyone. But if a developer is tinkering around trying to make clean and readable code at the expense of being able to deliver it timely, then that's bad. Make it work, use duct tape, ship it. You can refactor it later and make it super gorgeous and efficient.

Yes, it's good practice to write clean code, but never at the expense of being able to deliver. The benefit of delivering a duct-taped product on time, far outweighs the benefits of clean code that was never finished and delivered.

A good chunk of code I've come across isn't clean. Some are downright ugly. But they were all released and used in production. Some may say that it's unprofessional to write messy code. I disagree. The professional thing is to deliver code that works, whether it's clean or messy. The developer must do the best he/she can, given whatever time that was allocated before delivery. Then, go back to clean up-- that's professional. Hopefully the code delivered isn't pure duct tape, and is 'clean-enough'.

share|improve this answer
21  
As long as your technical debt ( en.wikipedia.org/wiki/Technical_debt ) doesnt lead you to "technical bankrupt" (Unable to deliver new features, fixing one part breaks another, etc...), and that you keep an eye on it, I agree. –  Matthieu Dec 22 '10 at 19:19
1  
@HeathLilley Agreed. I just don't believe developers that say only clean code should be written. That's bogus. Messy code happens. The idea that developers should only write clean and correct code from the start is an illusion. I promote the idea that we always revisit and refactor once our understanding of the domain improves. –  sunpech Dec 23 '10 at 13:48
2  
@sunpech: I don't believe developers that say only X. Real life is more complicated than that. –  David Thornley Dec 23 '10 at 19:06
13  
The problem with "just ship the fucking thing now" is that management will not buy your reasons for refactoring later, but if you invisibly do it NOW, it will be all good. –  Job Dec 24 '10 at 2:02

You must ensure that your code is very readable, clean and maintainable. That's what all programmers must do.

But you are talking about over styling (like that term better that girl-code) which serves nothing but the ego of its author.

I've seen many developers in the past so proud of their creation (you know, like in the restrooms ;)), they spent hours cleaning and polishing their code. Some of them were so meticulous than they ensured that the correct white spaces between members were respected.

It's too much.

I fight that kind of behavior counterproductive. In a professional context, you must be professional. You can get your satisfaction by writing clean, very readable and maintainable code and talking with happy users or colleagues.

share|improve this answer
7  
Well, I polish until the code is clearly readable by me. If I come back two weeks later and I have to figure out what I did, it's probably not clear enough for others to easily understand. –  Robert Harvey Dec 22 '10 at 15:59
7  
Elegant code is inherently more maintainable, and easier to read I think. –  Craige Dec 22 '10 at 16:06
2  
+1, I've seen some perfectly styled SPAGHETTI CODE in the past. –  Jas Dec 22 '10 at 16:25
8  
I agree with the sentiment, but I do write my code with the correct number of spaces between members, and am irritated by people who don't. It's an easy thing to do (made even easier by automated tools like StyleCop), and the consistency it affords is worth the small amount of effort required. –  Robert Harvey Dec 22 '10 at 17:09
2  
@sunpech: Write it clean, and it's a lot easier to keep it clean. –  David Thornley Dec 22 '10 at 17:35

Honestly it depends. I like how everyone spouts the party line about how "anything less than clean well documented code is a sheer travesty!" but I work in a business with ridiculous deployment cycles and zero oversite: I do the best I can, but I write so much code its extremely difficult to write the clean perfect code that everyone else claims they write.

What I try to do is write code that can be easily maintained by someone who has roughly my ability. I comment the tricky parts, I name the programs, variables, and classes friendly names, I deploy, I move on. I don't have time to do anything else.

Sometimes I feel a bit guilty about it, but not very. You should see some of the horrors I deal with on a daily basis. Decades of custom code in obscure languages with zero documentation. One of my coworkers develops exclusively in VB6 and deploys cryptically named binaries all over the place. The woman I replaced programmed exclusively in RPG.

It's just extremely difficult for me to believe, as much horrible crap as I've seen in my years as a programmer, that everyone only generates clean code.

share|improve this answer
2  
Enough with the duct tape! Spolsky ain't god. He puts his pants on one leg at the time just like we do! –  Job Dec 24 '10 at 2:04
4  
Part of the reason you write clean code is that it is faster to write clean code than dirty code on any but the shortest timeline (say a few hours). If thinking for a few seconds about variable and method names is going to make you miss a deadline, then so will the precious time you loose when you and/or your coworkers become confused by your code. You make code sound almost disposable, like you will write it, it will be used for a while without maintenance, and then retired. Maybe in your peculiar situation code is disposable. I have never seen that happen in a decade of practical experience. –  PeterAllenWebb Oct 20 '11 at 20:16
1  
@Satanicpuppy I have seen a lot of dirty code in my time, and I've written my share, but almost all of it was wasting my time or someone else's. I stand by the claim that clean code can actually be written FASTER than dirty code on any time scale longer than a few hours. –  PeterAllenWebb Oct 21 '11 at 3:31

Would any of us buy a car if we know that under the hood it all messy and hard to troubleshoot,maintain or fix and it takes more resources to run than it should?

Why should it be any different for a piece of software?

Just because the end users cannot look under the hood does not mean they will never know it. Sooner or latter it will show up.

answering the question "Do you actually write 'clean-code'?" -- Oh, Yeah.!

share|improve this answer

If by 'clean code' you mean do I go out of my way to make sure the code is as clear as possible?

Heck yes.

The cleaner, clearer the code, the easier it is to maintain, and thus saves you time in the long run. Dont look at clean code as vanity, look at it as an investment in saving future effort and time.

share|improve this answer

I would disagree with the accepted answer on this question.

Your responsibility is obviously to ship, but usually you also have a responsibility to ship something that is maintainable as cost effectively as possible by yourself and future developers.

I've spent periods as that poor maintenence programmer or consultant on site who has to understand and debug some huge undocumented system, and I can tell you that poor designs and messy confusing code can lead to hours or even days of wasted effort. I can think of lots of situations where an extra N hours of effort by the initial developer could have lead to a 5N cost saving in terms of my time.

I know there is a statistic floating around about this, but in my experience across multiple projects, each line of code that is written is read 5-20 times during extension and maintenence.

So I would say to clean up code to within an inch of it's life. It takes time but it's likely a net cost saving over the life of the project

share|improve this answer
1  
No, you clean up your code when and if there's time, and budget, AND the risk of doing so is smaller than the risk of not doing so. In production environments, that means quite often you're not going to polish existing code to make it prettier, it's just not cost effective but does cause risk of introducing new bugs. –  jwenting Oct 10 '12 at 14:41

I don't think I like the term "girl code" but clean code = maintainable code. Anything less is unprofessional.

As a general rule, I consider then next developer that has to look at my mess.

A lot of the time it is me...several months later...when I don't remember how it works...and I have even less time to make a change.

share|improve this answer

I try to write "clean code" in the Bob Martin sense (e.g. OO design). There is great value in writing clean code. It is much more maintainable.

Then I let ReSharper make it "pretty code" for me. (e.g. alignment, line breaks, etc) There is good value in writing pretty code. But there are diminishing returns. Some prettification makes it a bit more maintainable due to ease of reading.

If you feel that neatly lining up huge blocks of code is necessary to make it readable, then the problem is your freakin huge block of code! It's too big. I see many examples of people taking great pains to prettify some very poorly designed code. It's like putting sprinkles on a dog turd.

If I didn't have ReSharper, I would still have clean code, but it wouldn't be quite as pretty.

I don't think I should spend more than ~5% of my coding time in prettifying. Which means the more powerful my editor and the more proficient I am with it, the more prettification I can do.

share|improve this answer

I think "clean code" should be as clean or cleaner than how you used to write on your physics/engineering/math exams. If it's too messy, the grader won't understand your work and will probably mark it wrong even if it's right.

share|improve this answer

I am not sure "looking good" and being "elegant, perfectly understandable and maintainable" is equivalent.

I try to write code, that is "elegant, perfectly understandable and maintainable". I do refactor my own code to better match those criteria.

I don't see any drawbacks, except the resulting cost in time.

For code to "look good", there are plenty of automated tools, that will properly indent and space everything as you wish.

share|improve this answer
2  
That causes me to be annoyed even more when I see code badly formatted. The person writing it could have just used one of those tools to do it for them. It also occurs most often when mixing tabs and spaces together to create an unholy mess. –  jsternberg Dec 22 '10 at 15:59

Just avoid "vanity code". There are plenty of developers out there that do things purely out of vanity (or due to an OCD) and nothing else. My panties really get twisted with those people.

share|improve this answer

Too much of anything is never any good.

However, an important thing to bear in mind with "unclean" code is that it can easily lead to "broken windows". If the code is very poorly formatted I think many people new to the code base might feel less inclined to do a good job with maintenance and evolution causing a downward spiral that might eventually affect the working condition of the software.

Therefore maintaining a certain level of cleanliness in the code is beneficial to more than just your fellow developers. Don't spend too much time on it (~5 % has been mentioned). Learn to use the tools of your craft to automate manual tasks (code formatting in this case). Take responsibility for what you do and always do what you feel is most beneficial to your company/customers/users.

share|improve this answer

I do go to great length to clean code. I think it greatly helps the bugs stand out.

I don't agree with the "ship the fucking thing now" concept, because clean code is an investment to the future. Also to many software gets shipped with to many bugs. Resolving one bug in my opinion is better than implementing one new feature.

Also if you look at estimates of programmer productivity, I don't think I score very bad. Writing clean code is a habit, and the more experience as a programmer, the more efficient one becomes at it. If one never tries it, obviously, one will never get experience with it.

Another point to take into account, is that most developer time goes to reading code, so readable code greatly reduces the times spent reading. Understanding undocumented algorithms for example can be costly and invite new bugs.

One thing I definitely do miss and would like to have one day is an automatic code formatter that I could adapt to my style, that would really save me some time, especially when reading other people's code.

Clean coding does have a link to perfectionism, which does have a risk of never materializing, but I think that is mainly a problem when you start out, because you invest in later and when reusing your own elegant pieces of code, combined with your experience, growing older you will be very productive and a lot less haunted by bugs than the messy coders.

This is a piece of code demonstrating my coding style.

share|improve this answer

Seems no one raises the point of what's in your company's best interest?

Often, if not always, programmers are just employees, and while the management decisions might frustrate us, we often do not have all of the data they do.
For example, say the company is contracted with a clause that if the software isn't ready in time, you won't get paid (it just happened to us, though I think we got the payment after all). Yeah, clean code is important, but more important is to have the code working by the payment day!

Another example - the company is in bad financial position and needs to raise some money. Guess who cares about quality? You can fix it later, if you have to, just ship it!

An argument might be "Why should I sell out and write crappy code?". Well, why should your company pay you a nice check each month? Choices, my friend. If you are after idealism, try the Free Software Foundation, I hear they're doing some pretty cool stuff (I mean this one and I respect FSF & OSS).

On the other side of things, if you work on a project where an explosive growth in usage is expected (although such projections are almost never accurate), you better lay some solid foundation with the best code quality required, since it's almost certain maintenance will be the bigger cost for the project.

Programmers love 'clean' code, whatever that means. We can't even agree on what's clean, but we love it. However sometimes it just doesn't matter that much as usability and correctness do. These might seem synonymous, but they aren't - if you've seen code written by a true Perl hacker in 4 hours with the intent to be used twice and thrown away, you would acknowledge it's not clean, but it works.

So sometimes, ego aside, we should just get it working. Note that I don't recommend writing bad code as a habit, I'm just pointing that it might be necessary. Perfection takes time your company might not have. So if your employer doesn't mind, craft software, but if you need to, just write working code, never mind the 'cleanliness'. It's just not a 'One size fits all' answer - you should prioritize.

share|improve this answer

I admit to doing that; and the benefit is not getting annoyed every time I see it. I guess it's also easier to read, and therefore bugs become more obvious; but the real reason is that I can't stand ugly code.

share|improve this answer

I would say I make an effort to write cleaner code, but that can change because of time constraints or if I'm working on something difficult. It tends to get messy when focusing on making it work. Then I'll go back and clean up as I review it. If you return to code and have to spend too much time refreshing your memory, you didn't comment it enough.

Clean code is good but like everything else, it just needs to be clean enough. Indenting 5 lines of code 4 spaces and one line 5 spaces doesn't increase the reading difficulty.

share|improve this answer

I think it is dependent on what you are doing. If I'm writing a proof-of-concept application then I'm basically cowboy-coding my ass off and not looking back. If I'm working on an application that I'm actually going to be working on for a while, then I make sure I code it well enough as well as making it understandable a month from now.

I think that styling your code is a bit iffy. As some above have said, your job is to make a product, not formatted code but I would say at the very least one should stick with a defined style of commenting and coding things. I would hate to see half of the variables camel cased and the other half Hungarian.

But also, it depends on what you mean by 'clean-code'.

share|improve this answer

I like code to be readable, but the most important thing is consistency. For me that means consistency with naming conventions and spacing between functions, parenthesis on the same line or the next line of the if statement, etc.

Of course, there are times when someone programs something with a consistent code style and it still drives me insane. Especially code that doesn't "breath". For example:

void function1(){
    //whatever code
}
int fooBar(){
    //whatever else
}
Foo* someOtherFooBar(int value){
    if(value){
        //do something
    }
    return ...;
}

Well... It looks worse with Objective-C methods, and with lots and lots of nested if statements, and lines much longer than 80 characters. But it still annoys me :)

share|improve this answer

This is a quote from Clean Code, by Bob Martin:

To drive this point home, what if you were a doctor and had a patient who demanded that you stop all the silly hand-washing in preparation for surgery because it was taking too much time? Clearly the patient is the boss; and yet the doctor should absolutely refuse to comply. Why? Because the doctor knows more than the patient about the risks of disease and infection. It would be unprofessional (never mind criminal) for the doctor to comply with the patient.

So too it is unprofessional for programmers to bend to the will of managers who don’t understand the risks of making messes.

share|improve this answer

Refactoring your code to make it elegant makes it easier to read, and easier to maintain. Even minor things such as aligning your variable assignments:

int foo    = 1;
int bar    = 2;
int foobar = 3;

is easier to read than

int foo = 1;
int bar = 2;
int foobar = 3;

which means it's easier to skim over when you're debugging later.

Also, in PHP you're allowed any number of random code blocks. I use these to group logical tasks:

// do x
{
    // ...
}

// do y
{
    // ...
}

This adds clear definition to relevant code.

Edit: As an added bonus, it's easy to preceed one of those logical code blocks with an if (false) if you want to skip over it temporarily.

share|improve this answer
9  
I think they already invented something that does that--its called a function. Any time you find yourself creating one of those blocks, you should create a function instead. From there, if you don't want to run it, comment out the function call (rather than putting in a backhanded comment) –  Stargazer712 Dec 22 '10 at 16:26

I write code that attempts to solve the given problem in the most efficient and theorertically 'elegant' way. In that sense only it is clean. If it happens to be 'pretty' when I am done, so be it.

What I have found in my limited experiences is that when people complain about 'clean-code', the ugliness is usually a result of a terrible solution rather than coding convention.

share|improve this answer

I write clean code and put comments that make others understand it. Simple.

share|improve this answer

I just write my code, following the company standards. If I want it "prettied up," I can run it through a code beautifier.

share|improve this answer
1  
Except what generally happens is someone else ends up running it through a beautifier trying to clean up what you didn't get around to cleaning. –  Stargazer712 Dec 22 '10 at 16:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.