58

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?

2
  • In all my attempts to write "clean" code according to well-established principles, I never really found it to be so easy to maintain past a certain scale based on such premise alone. Far more relevant was the reliability of it and how well-tested it was and how well-suited it was for its purpose (which can relate just as much to implementation as design). All the cleanliness in the world cannot make up for a lack of any of these, and sometimes the most reliable code I continue to use isn't the cleanest, while my cleanest wasn't always the most reliable.
    – user204677
    Jan 30, 2018 at 0:41
  • So above all things -- above readability, beauty, SOLID, anything else -- I've found it useful to prioritize reliability and "stability" (the quality of being unchanging in my book, and further, lacking the need or desire to change further). Reliable and stable things are the things that have lasted the test of time for me, and sometimes they aren't very clean at all by many people's books (some of my most reused code is C code dating back to the late 80s and early 90s which applies things like bit-fiddling hacks that barely anyone understands anymore -- still works so reliably).
    – user204677
    Jan 30, 2018 at 0:45

22 Answers 22

61

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 f*****g 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 writes 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, and 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'.

19
  • 50
    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, 2010 at 19:19
  • 3
    @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.
    – spong
    Dec 23, 2010 at 13:48
  • 44
    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, 2010 at 2:02
  • 7
    Another illusion is to think you'll have time to clean it later. That won't happen. You'll have other things to ship. You shouldn't deliver messy code. And by the way, you should be working on deadlines too, you're the tech guy who knows how much time it'll take to write clean code. That doesn't mean over cleaning and tinkering for an insane amount of time, that means the time to refactor before you ship the code should be taken in account. Oct 6, 2016 at 13:57
  • 4
    "Go back and refactor it later" - something which never happens. So I would say, at least make an attempt to write clean code in the first run. You never get time to refactor old code once it goes to production. That's the reality. Sep 4, 2018 at 7:42
39

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 that they ensured that the correct white spaces between members were respected.

It's too much.

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

10
  • 15
    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. Dec 22, 2010 at 15:59
  • 15
    Elegant code is inherently more maintainable, and easier to read I think.
    – Craige
    Dec 22, 2010 at 16:06
  • 6
    +1, I've seen some perfectly styled SPAGHETTI CODE in the past.
    – Jas
    Dec 22, 2010 at 16:25
  • 26
    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. Dec 22, 2010 at 17:09
  • 4
    @sunpech: Write it clean, and it's a lot easier to keep it clean. Dec 22, 2010 at 17:35
27

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

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

3
  • 6
    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, 2012 at 14:41
  • This also depends on what corner of software development you work in. I used to work for a Digital Marketing agency that were more than happy to pass charges onto their client if the next phase were to take longer due to code base issues. Our push for more time during dev to fix existing issues were shot down in favour of extended dev time equalling more money for the business. Mar 30, 2013 at 0:25
  • 2
    I agree with that, You should deliver code, but if you can't fix / update / upgrade, what you delivered was not code, but a money hole. I find that people that fight that idea are use to working in bad environments and argue a system that they have never experienced. I have maintained both clean and not clean code, and will tell you that clean code is far cheaper and quicker to maintain and develop.
    – Jdahern
    Mar 30, 2016 at 17:13
22

Would any of us buy a car if we know that under the hood it is 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.!

1
  • I would disagree - software doesn't rust (as Joel puts it), unlike the insides of a car. You might argue that when an OS is upgraded, the software must upgrade, too, but that is something different. Also, I do write clean code, but I don't think that it's the most important characteristic of my contributions.
    – K.Steff
    May 13, 2012 at 17:12
20

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. Don't look at clean code as vanity; look at it as an investment in saving future effort and time.

15

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 oversight: I do the best I can, but I write so much code it's extremely difficult to write the clean perfect code that everyone else claims they write.

I try to 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, and 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 Visual Basic 6.0 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.

5
  • Agreed. Most people aren't going to write clean code to ship/release the first time. There's duct tape involved to get the job done.
    – spong
    Dec 22, 2010 at 17:31
  • 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, 2010 at 2:04
  • 6
    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. Oct 20, 2011 at 20:16
  • 1
    @peter: And in two decades, I've never seen a place where every piece of code was clean. I've rarely even seen a place where half was. Where do you work? NASA? Oct 21, 2011 at 0:15
  • 3
    @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. Oct 21, 2011 at 3:31
8

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

6

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.

5

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.

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.

4

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

3

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.

1
  • 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, 2010 at 15:59
3

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.

2

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.

2

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

2

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 too many software gets shipped with too 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.

1

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.

1
  • Like wing or (worse) box comments, say? Dec 23, 2010 at 19:08
1

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.

1

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.

1

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

0

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.

0

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.

4
  • 12
    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)
    – riwalk
    Dec 22, 2010 at 16:26
  • 1
    @stargazer712: I hate php's functions because of the lack of defined namespaces. Inevitably, reading someone elses code, they have one "include" at the top, which itself includes 5 other things, which each include 4 more, and then I have to do a search on the entire code base to find the function definition. Very frustrating. Dec 22, 2010 at 16:31
  • Often this is code that does not warrant a function declaration. eg. no possibility for reuse, calculation/setting of related local-scoped variables, etc
    – Craige
    Dec 22, 2010 at 16:33
  • on the other hand, code with no possibility of reuse is rare. If you find yourself writing a lot of code that cannot be reused, there's a good possibility that it could be improved...greatly.
    – riwalk
    Dec 23, 2010 at 0:19
-3

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

5
  • 2
    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.
    – riwalk
    Dec 22, 2010 at 16:28
  • @Stargazer712 which is exactly why I don't bother much beyond following company standards
    – Muad'Dib
    Dec 22, 2010 at 17:44
  • @Maud'Dib, the problem then is that the result is only as good as the beautifier. While the horizontal whitespace is entirely about scope (and therefore cleans very well), vertical whitespace is commonly about intent (grouping what is related), and cleans very poorly. Bottom line--have mercy on your fellow developers.
    – riwalk
    Dec 23, 2010 at 0:22
  • @Stargazer712 Problem is, except for "company standards" everything else is entirely a matter of taste, which is subjective. for example, I like to put spaces in places where my coworker positively hates them. I make it look nice to me, and that is as far as I go.
    – Muad'Dib
    Dec 23, 2010 at 4:51
  • 1
    Be careful with "beautifiers", as they can mess up merging commits big time (I've got first hand experience :) ). Oct 25, 2012 at 10:23

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