Forgot your password?
typodupeerror

Refactoring: Improving the Design of Existing Code 184

Posted by samzenpus
from the read-all-about-it dept.
kabz writes "Refactoring (as I'll refer to the book from here on in) is a heavy and beautifully produced 418 page hardback book. The author is a UK-based independent consultant who has worked on many large systems and has written several other books including UML-Distilled. Refactoring is a self-help book in the tradition of Code Complete by Steve McConnell. It defines its audience clearly as working programmers and provides a set of problems, a practical and easily followed set of remedies and a rationale for applying those techniques." Read below for the rest of Johnathan's review.
Refactoring: Improving the Design of Existing Code
author Martin Fowler with Kent Beck, John Brant, William Opdyke and Don Roberts.
pages 431
publisher Addison-Wesley
rating 9/10
reviewer Jonathan Watmough
ISBN 0201485672
summary expands and formalizes the idea of applying explicit refactorings
Code refactoring is the process of restructuring code in a controlled way to improve the structure and clarity of code, whilst maintaining the meaning of the code being restructured. Many maintenance problems stem from poorly written code that has become overly complex, where objects are overly familiar with each other, and where solutions implemented expeditiously contribute to the software being hard to understand and hard to add features to.

Typically refactorings are applied over a testable or local scope, with existing behavior being preserved. Refactoring as defined in this book is not about fixing bad designs, but instead should be applied at lower levels.

Testing a la Extreme Programming is emphasized as a control for ensuring that program meaning is not changed by refactoring. It is not over emphasized, and this is not a book about testing, but it is often mentioned and stays in the background through the book.

The refactorings presented in the book are not intended as a comprehensive solution for all problems, but they do offer a means to regain control of software that has been implemented poorly, or where maintenance has been shown to simply replace old bugs with newer ones.

The book is divided into two main sections, introductory material that introduces and discusses refactorings, and a lengthy taxonomy of refactorings that includes both examples and further discussion. The introductory material consists of a long worked example through simple Java code that implements printing a statement for a video store. Despite the simplicity of the code, Fowler shows in clear detail where improvements can be made, and how those improvements make the code both impressively easy to understand, and easy to maintain and add features.

Several key refactorings are demonstrated in the opening chapter including Extract Method, Move Method and Replace Conditional with Polymorphism. This is a book about programming in the object oriented paradigm, so as you might expect, the first two refactorings refer to extracting and moving object methods either into new methods, or between objects. The third example provides a means to replace special cased behavior in a single object type by deriving a sub type of the object and moving type specific code to the sub types. This is a fundamental technique in object oriented programming, and is discussed here in practical terms.

Now that several actual refactorings have been introduced, Fowler provides a solid and well thought-out discussion of the why's, when's and when not's of refactoring. For example, code can decay as features are added, and programmers special-case, or bodge additional functionality into existing objects. Fowler argues that the bitrot and decay makes software more unreliable, leads to bugs and can accelerate as the problem gets worse. Faced with these problems, refactoring should be used to improve local design and clean up and improve code, leading to better software, that is easier to maintain, easier to debug, and easier to improve with new features as requirements change.

However, there is a caveat, in that since software functionality should remain unchanged during refactoring, the process of refactoring consumes resources, but provides no easily measurable value. Fowler confronts this issue in a section that discusses how to communicate with managers, that you are performing refactoring work. He denies being subversive, but his conclusion is that refactoring should essentially be folded in with normal work as it improves the overall result.

This is a bit like goofing off on the basis that you'll think better after 20 minutes of fooseball. I'd definitely subscribe to that theory, but many others may not.

Kent Beck guests in Chapter Three for a review of the issues in typical software that suggest a refactoring may be needed. This chapter is entitled Bad Smells in Code, and most of the smells presented will be familiar to any reasonably experienced programmer, and they will be a great learning experience for less experienced programmers. I got the same feeling reading this chapter as I did when I first read Code Complete. Here was someone writing down names and describing problems that I had a vague unease about, but was too inexperienced to really articulate or do something about. Typically the refactorings address the same kind of issues that a code review with a skilled experienced programmer would address. Long parameter lists, too long methods, objects delving about in each others private variables, case statements, related code spread across different objects etc. None of these problems are debilitating in themselves, but added up, they lead to software that can be prone to error and difficult to maintain.

Most of the remaining substance of the book, 209 pages, is given over to a taxonomy of refactorings. These 72 refactorings are covered in detail with comprehensive simple examples presented in Java. Each refactorings is given a clear name, a number and a line or two of descriptive text. The motivation for the refactoring is then discussed, often including caveats and cautions. The mechanics of implementing the refactoring are then listed, with 1 or more (and often more) examples of implementing the refactoring. Refactorings range from the very simple to more complex examples such as Convert Procedural Design to Objects.

Due to the difficulties of reproducing large and complex sections of code, Fowler sticks with relatively simple examples. These seem to grate on him more than the reader, and he can come across as somewhat embarrassed when we look at the employee, programmer, manager pay example for the tenth time. I certainly didn't have a problem with it though.

This is a very well written and fun to read book. I personally feel that much of the material is implied by from Code Complete, but Fowler does a fantastic job of expanding and formalizing the idea of applying explicit refactorings. Much like Code Complete gave a motivation for keeping code well commented and laid out, this book presents the case for care and feeding of how to structure software. To fight bitrot and technical debt, poorly structured and unclear code should be targeted and refactored to improve structure and clarity. This gives a very real payback in terms of less required maintenance, and ease in adding features later on down the line.

Despite the fact that all the examples are in Java, the ideas are easily transferable to C++ or any procedural object oriented language. I highly recommend this book.

You can purchase Refactoring: Improving the Design of Existing Code from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
This discussion has been archived. No new comments can be posted.

Refactoring: Improving the Design of Existing Code

Comments Filter:
  • Awful description (Score:5, Insightful)

    by Anonymous Coward on Wednesday January 09, 2008 @01:35PM (#21970802)

    This is a bit like goofing off on the basis that you'll think better after 20 minutes of fooseball. I'd definitely subscribe to that theory, but many others may not.

    It's not at all like that. If you really need an analogy to understand this very simple concept, it's like seeing that your desk is overflowing with paperwork and spending some time filing everything properly. A little time invested can make it a lot quicker to find what you are looking for and help you deal with one thing at a time.

    • by dubl-u (51156) * <2523987012@poDEBIANta.to minus distro> on Wednesday January 09, 2008 @03:52PM (#21973092)
      I agree that this is a terrible analogy:

      This is a bit like goofing off on the basis that you'll think better after 20 minutes of fooseball. I'd definitely subscribe to that theory, but many others may not.

      The analogy I usually draw is to cooking.

      Everybody's thrown a big dinner party and then left the dishes for a few days. Or even worse, had a roommate who did. Turns out this sucks, because if you just want to make yourself a little breakfast, then it's harder to cook. You have to scrape out a pan and chip off a plate just to get started. And cooking is twice as much work because you have to shift the mess around just to get at the counter, and then shift it again to get at the stove.

      Then when you're done, you sure aren't going to wash up properly; the sink's filled with dishes already. So you just toss your dishes on the top of the pile, saying you'll get to it "later". Of course, that ever-growing mound of fuzzy dishes is the real-world analogy of half the code bases I've seen. And the giant rewrites that inevitably follow are like tearing down your kitchen and building a new one because that's the cheapest way out of the mess.

      Instead, good chefs work clean. They clean as they go. Always. Not because they're uptight freaks, but because if they don't, the mess slows them down and makes them sloppier, eventually resulting in a giant clusterfuck, with all their colleagues yelling at them.

      Refactoring is just a way for programmers to clean as they go. I picked up the habit years ago, and now would never go back, as it's the fastest way I've found to get good work done.
  • Old news. (Score:5, Informative)

    by Kaz Kylheku (1484) on Wednesday January 09, 2008 @01:39PM (#21970862) Homepage
    Reviewed back in 1999 on Slashdot.

    http://books.slashdot.org/article.pl?sid=99/09/16/1333202 [slashdot.org]
    • by corby (56462)
      That is ridiculously insensitive. Everybody knows that samzenpus is unfrozen from the year 1999 [wikipedia.org], and is struggling to regain his relevance as a critic.

      Don't listen to Kaz, I'm behind you all the way, samzenpus. Hey, man, can you give us a sneak preview of that movie American Beauty? I hear it's a real sleeper!
    • Looks like the assigned score hasn't been refactored since then. I suppose that's a good sign the book is actually good and doesn't focus on specific technologies.
    • by Blakey Rat (99501)
      Also, it's spelled "Foozball." Since we're being critical and all.
      • by JerkBoB (7130)
        Also, it's spelled "Foozball."

        Fooseball. From Fußball, which is a shortening of Tischfußball.

        Fuß == foot. ball == ball. Football (soccer, for us yanks).

        Nyah.
    • Yes, this book has been out for a number of years now and is concept is not new. It is (or should) be taught in any decent software engineering curriculum.

      What gets me is that this book was published back in 1999, yet there hasn't been that much progress in terms of automated refactoring tools since then. Most IDE's have a handful of the simple ones available, but nothing complicated such as extract class (which I use frequently and is prone to errors).
    • by LizardKing (5245)

      Kaz Kylheku? Late of comp.lang.c? My god it's a small world.

  • by StandardDeviant (122674) on Wednesday January 09, 2008 @01:40PM (#21970880) Homepage Journal
    I don't mean to be a wet blanket, but the book has been out for quite some time -- checking Amazon, July of 1999. It is pretty great, and I would recommend it to those who somehow managed to miss it up to this point, but a review almost nine years later? Slow news day much?

    On the other hand, maybe periodically prodding towards the direction of higher internal quality (to be distinguished from external quality, that which is perceived in a black-box fashion by your customers, the relationship between these two qualities is of course a matter of much friction and debate between the managing and laboring classes) isn't a bad call. Lord knows any extra ammo to convince people that this is worthwhile is appreciated. As much as we like to think of ourselves as poets, I sometimes think the traditional profession most software development resembles is "butcher" or "janitor", just one messy hack-job and sweep under the rug after another after four or five decades of which you can retire and grumble on the beach about putting cyanide in the guacamole, fondly reminiscing about your red swingline or asr-33 or what have you.
    • Re: (Score:3, Insightful)

      by gbjbaanb (229885)
      I've just been reading a nice blog about how the modern world is chucking more and more stuff at us (yes, I'm looking at you Microsoft C#/.NET teams) so we barely have time to learn something before its obsoleted; cannot learn enough about all of the new features that are being pushed at us; stress out that we think we need to learn in order to keep up-to-date with modern development practices; etc.

      This review comes as a pleasant reminder that you don't have to chuck your old code away and rewrite it all in
    • I don't mean to be a wet blanket, but the book has been out for quite some time -- checking Amazon, July of 1999. It is pretty great, and I would recommend it to those who somehow managed to miss it up to this point, but a review almost nine years later? Slow news day much?

      I see where you're coming from but I think this book is so fundamental that the article will be worth it if one new person reads the book and takes its advice to heart.

      The book is 9 years old and its concepts are still relevant and practical today. That says a lot about a tech book

  • by iBod (534920)
    How this can be compared to McConnell's epic(s) I don't know.
    • by stg (43177)
      I've read both - while Code Complete is pretty good too, I think Refactoring is a bit better, in a practical sense.
      • by iBod (534920)
        How is it better?

        It seems to me like doing a quick makeover as opposed to getting it right the first time around.

        In my experience, and I don't thing I'm a coding God or anything, most code is generated by idiots (or to be kind, people who just don't understand the task at hand).

        If the design of an application is fubared from the start, you can't refine the mistakes out of the result.

        You need to understand the application requirement and code correctly through the entire process. There's no going back.
        • Re: (Score:2, Funny)

          by chromatic (9471)

          If the design of an application is fubared from the start, you can't refine the mistakes out of the result.

          There's an interesting book you should read. I forget the name, but it's about how to improve the design of existing code.

        • Re:MakeWork (Score:4, Informative)

          by stg (43177) on Wednesday January 09, 2008 @03:08PM (#21972196) Homepage
          First - you do realize the 2nd edition of Code Complete has a whole chapter on Refactoring, right? AND it recommends the other book for more details?

          Have you actually read the book or are you just going from the review? Most of the methods are designed to work in a very small scale.

          Examples - have you...
          - Moved some code in the middle of a method to a separate method to make your code clear or re-usable?
          - Renamed a variable with an unclear name?
          - Added an intermediate variable for a complex calculation?
          - Moved a complex boolean expression into a well-named boolean function?
          - Added/removed a parameter to/from an existing method?

          These are all refactorings, although some of the simplest. You might say that is just common sense, but that is kind of the point of it, and the particular steps are designed so that you won't screw up the code with common mistakes. Many refactoring tools exist too, and they are quite useful - for example, when adding a parameter to a method, one of my refactoring tools show me where that was used and I can edit any with a click (and also note if they all need it, or if I should give it a default value). If I change the name of a method, it can replace everywhere it is used (a search and replace can do the same, except if another object has a method with the same name it will screw things up - so you have to watch each replace carefully).

          You might also note that many refactorings match other concepts in Code Complete.

          None of these are supposed to "fix" a broken design by itself. They are meant to slowly improve the code so that it is easier to keep working on it.
        • Re: (Score:2, Insightful)

          by MetalPhalanx (1044938)
          What if you're not the one who does it "The first time around"? You mention that most code is generated by idiots... Don't you think that there's a good chance that many programmers might find themselves in a new position, being asked to implement new features into an old system that your predecessor (one of the idiots you mention) managed to somehow bludgeon together?

          Another scenario (this time it's personal experience): A co-worker and I were asked if we could design an in house resource management system
  • by RandoX (828285) on Wednesday January 09, 2008 @01:42PM (#21970916)
    Does your book cover that?
  • by Maxo-Texas (864189) on Wednesday January 09, 2008 @01:47PM (#21970994)
    "new" code is a capital investment and gets very high tax benefits.
    "refactored" code is a pure cost.

    I do a lot of refactoring but i always have to sneak it in under the cover of a "new" project instead of a "bug fix" project.
    • Re: (Score:3, Interesting)

      by Surt (22457)
      Refactored code is new code to do an existing job. Does Microsoft not get to write down its investment in each new version of windows because it does the same job?
      • Re: (Score:3, Interesting)

        by Maxo-Texas (864189)
        Refactored code is existing code maintained. It is not legally new code. Microsoft has big lawyers but they probably have to track their software the same way every company I've ever worked for in the last 25 years has. New code is like buying a new truck. Refactored code, bug fixed code, etc. is like fixing the truck or spending extra time tuning it up. You do not get the tax benefits.

        I'm not sure where "reusable" code falls in this mix. Here you reuse existing code for a new project.

        • by Surt (22457)
          That's pretty interesting ... none of the companies i've worked for in the last 20 years (6) have done what you're suggesting, none of my friends at Microsoft have mentioned this, and I've never heard of this before. Maybe this is something unique to your state.
          There's basically no way the company I currently work for even could track this, not without major infrastructure changes, and we refactor code all the time.

    • The primary problem is not legal, but your management.

      Improving your software is always a benefit, whether that benefit is visible to the customer or not is an exercise for your management to handle. By improving your code, you make it easier to maintain which in turn allows more NEW features to be added to it with less headaches.

      • Re: (Score:3, Interesting)

        by Maxo-Texas (864189)
        I do not think any of you guys got my point so I'll clarify.

        From here:
        http://www.pkftexas.com/pkf/NewsBot.asp?MODE=VIEW&ID=15&SnID=2 [pkftexas.com]
        The entrepreneurial owner of a growing business would like to expand into other cities and states, but is hesitant. He does not believe his current accounting software will be able to handle the increased transaction load and produce the type of management reports he needs to make effective decisions, and the cost of the next tier software has always been a little out o
    • by cbcanb (237883) on Wednesday January 09, 2008 @02:55PM (#21971984)
      Not true. not true.

      Refactoring code is like paying off debt. When you add new code without thinking about the design, the internal quality goes down. This makes the code harder (read "more expensive", "slower", etc) to work with in the future. And since most of the cost of software is in maintenance rather than the initial development, that's a bigger issue than you think.

      Carrying a little bit of technical debt is inevitable, and a good thing. But if you allow too much to build up (by not refactoring debt-heavy areas of code), the interest payments can become crippling. Your code sucks, you can't understand it, and making changes takes far more work than they should. That directly impacts the bottom line.
      • Re: (Score:3, Interesting)

        by dubl-u (51156) *
        Refactoring code is like paying off debt.

        Agreed! And that's the best way to explain it to execs.

        On a new project, you refactor to keep debt low. On a legacy project, you refactor to keep "interest" costs low. The interest on technical debt comes out as less reliable systems, buggier code, increased maintenance cost, and higher costs for new features. All of those cost cash money, which in my experience is a lot more money than you'd pay to do things right.
  • by lyapunov (241045) on Wednesday January 09, 2008 @01:48PM (#21971008)
    THe Pragmatics Programmer: From Journeyman to Master" was published as well in 1999 and is written by Andrew Hunt and David Thomas. I just got it for Christmas and have been enthralled with it. They spend some time dealing with the refactoring of code as well as wonderul insight into a wealth of other areas.

    This is yet another book that I wish I had read years ago. Working a few years in industry really makes you realize how much you can learn from other people. But alas, the problem of youth is that you always think you're the exception.
    • "The Mythical Man Month" by Fred Brooks was first published in 1975, and republished in 2000 as a 25th anniversary edition.

      And it's still one of the most insightful books about commercial software development out there.

      The Pragmatic chaps aren't bad either, but I'm not convinced they'll get republished in 2024 ;)
  • by w3woody (44457) on Wednesday January 09, 2008 @01:51PM (#21971052) Homepage
    At several places where I worked management was always happy to allow cycles to be spent on the process of 'refactoring' the code.

    Unfortunately, in my experience, the process of 'refactoring' involved making code more complex by adding to it. In one case, I saw the product of the 'refactoring' process wrap two pieces of functionality into two separate EJBs (with a whole 'dto-pojo' conversion scheme for data "isolation"). In another, I saw some functionality wrapped into a collection of beans--which was later wrapped in another layer of beans, and so forth, until 20 lines of code which set up a call into the javax.xml.translate package (for performing an XSLT transformation) into something like 8 bean layers. The 20 lines of code was at the heart of an 8-layer onion, each layer added by someone else's "refactoring" operation.

    In Java, because modern IDEs allow you to write code without thinking, the problem with code is not that there isn't enough code (to prevent incestuous classes from being overly familiar with each other), but that there is too much code as programmers unfamiliar with the problem decided to add beans and interprocess communication and multiple threads without properly sizing the problem. (Right now I'm looking at an internal system which may need to process 1 transaction a second, tops, built in an inter-cooperating network of 8 EJBs, which someone thought would help improve transactional performance. Eight? A second system essentially replicates an in-memory SQL system rolled in-house: the system has been buggy because the reverse index processing had a race condition. Um, why wasn't that built in a dozen classes on top of MySQL instead of built with a couple of hundred classes that reinvent the wheel poorly?)

    While I'm glad someone wrote a book on refactoring methodology, in my experience what we need is a book which describes how to write "simple" code: code that is just as complicated as it needs to be, and no more. And a book which also describes how to simplify overly-complicated code, how to pick simpler techniques, and how to manage programmers who have an "itch" so they go scratch it somewhere else--I think that would be a much more useful book.

    It's easy to add complexity. It's hard to simplify.
    • While I'm glad someone wrote a book on refactoring methodology, in my experience what we need is a book which describes how to write "simple" code: code that is just as complicated as it needs to be, and no more. And a book which also describes how to simplify overly-complicated code, how to pick simpler techniques, and how to manage programmers who have an "itch" so they go scratch it somewhere else--I think that would be a much more useful book. It's easy to add complexity. It's hard to simplify.

      If you read the book, you'll find that Mr. Fowler agrees with you.

      Read the TDD book by Beck. In it, he describes that TDD methodology in terms of making the code simple in terms of doing only what it should and no more.

    • by Bob9113 (14996)
      While I'm glad someone wrote a book on refactoring methodology, in my experience what we need is a book which describes how to write "simple" code: code that is just as complicated as it needs to be, and no more.

      Your point has much merit. Bear in mind, though, that refactoring is intended to facilitate the redesign of active code. While the book you mention would have value, it doesn't mean refactoring is somehow less valuable. Refactoring teaches a good designer how to steer poorly designed code, it would
    • ...and not with refactoring. Whenever I come across java code it always seems needlessly complex, with endless layers upon layers, unneeded abstractions, and patterns applied far beyond what would make for useful architecture.

      Before you start flaming, I'd like to state that this is probably more a problem with java *programmers* than with the language itself, although its design has certainly caused too many people to follow down that path. So the language is probably ok, but the surrounding libraries and t
    • by computational super (740265) on Wednesday January 09, 2008 @03:50PM (#21973038)

      Amen. I'm getting to the point these days where I'm slowly becoming wary of anything that appears, to me, to be a good idea. In the mid-90's or so, I came across this new paradigm called "Object Oriented Programming". At the time, I was maintaining monolithic Cobol systems, and the appeal of OO was intuitive. I saw right away how it could be used to simplify code reuse, or even make reusable code that had not previously been reusable.

      These days, OO means every function is encapsulated in a class, and every class has an ISomething interface, a SomethingImpl implementation (which has no data members) and an AbstractSomething base class (that's not extended by anything else), and a SomethingFactory that creates instances of SomethingImpl's and hands back a pointer to an ISomething... and if you ever float the concept of implementing ISomething again (you know, taking advantage of all that framework?), you'll be scolded for violating the purity of the OO design.

      XP was another thing that, when I first saw it, looked like a great idea. It seemed to me that XP was essentially a description of what productive programmers were already doing while they were pretending that Gantt charts were meaningful and that project managers were useful.

      Now XP is called "Agile" and companies hire "Agile Mentors" to show us how to do precisely the meaningless project management exercises that XP was meant to replace... When I see how much paperwork I have to fill out to be "agile", I long for the days of Gantt charts and Microsoft project.

      Refactoring, too. When I first saw Fowler's book, it was like a lightning bolt. The intro talks about how he spent a few days at a client site "cleaning up" a bit of code to simplify his next task. I had had that same experience too many times to count - I had been tasked with, say, implementing lot tracking in an inventory system. It was obvious (to me) that if I first made some modifications to the existing system, I could insert the desired feature without disturbing everything else - but I could never seem to explain that to a nonprogramming manager (in the end, I always ended up doing it and pretending I hadn't because I didn't want to be responsible for breaking the entire thing). And here was a book dedicated to the technique!

      Yet, nowadays, refactoring seems to mean going through working code and wrapping every function in a SomethingImpl class, giving it an ISomething interface, letting it extend an AbstractSomething base, and creating a SomethingFactory to create SomethingImpls...

      • Re: (Score:2, Informative)

        by Cederic (9623)

        XP is an Agile methodology, but there are many others. Not all methodologies work for all organisations, so someone that knows agile principles can help a company adopt an appropriate methodology without forcing them to follow any specific one. The principles behind them all are much the same. And if someone is requiring reams of documentation/paperwork as part of an agile methodology then either their methods are not agile, or the customer is demanding the documentation (in which case they should hire tech
    • by dubl-u (51156) *
      It's easy to add complexity. It's hard to simplify.

      Something where Refactoring's author, Martin Fowler, agrees strongly with you [martinfowler.com].

      A lot of what you described isn't refactoring, which is defined as making design improvements that don't change behavior. Instead, those guys were just doing developer goldplating.

      I think if you read the book, you'll see how a lot of the techniques in Refactoring are intended to be used in the service of simplification.
    • ...It's easy to add complexity. It's hard to simplify.
      I have always believed refactoring was simplifying. I looked at it in the same way editors look at books--omit needless words. If the work isn't smaller after refactoring, then it wasn't refactored.

  • Refactoring sucks (Score:4, Insightful)

    by Hal_Porter (817932) on Wednesday January 09, 2008 @01:56PM (#21971108)
    I've worked at a load of places where there's insufficient resources to do things that customers actually want, but an endless program to refactor away the ugliness of code. And the thing is, it's bullshit. Customers don't care how ugly the code is, so long as it works. And good programmers can deal with ugly code [msdn.com] - it's just the sort of people who are obsessed with refactoring that can't. So next time you find a thousand line function, or code full of #ifdefs ask yourself how much of that complexity is there because some customer demanded it. Will your rewritten 'pretty' version duplicate all features that the ugly version has? Do you even understand which ones are features and which ones are bugs? If so, why do you want to refactor it? And if not, how can you expect to get it right first time and not provoke howls of protest from the people that use it.

    And if anyone whines about how old code needs to be rewritten, point them at this

    http://www.joelonsoftware.com/articles/fog0000000027.html [joelonsoftware.com]

    Old code doesn't rust, it gets better, as bugs are fixed. Lou Montulli again: "I laughed heartily as I got questions from one of my former employees about FTP code the he was rewriting. It had taken 3 years of tuning to get code that could read the 60 different types of FTP servers, those 5000 lines of code may have looked ugly, but at least they worked."
    That's just in a PC application. Try refactoring the 'ugliness' out of an embedded system and see how long your employer still has customers, and how long you still have a job. And it's interesting that evolution, an unconscious process that far outperforms human 'intelligent' designers doesn't have any concept of ugliness at all. Maybe that concept is just an artifact of your limited ability to deal with complexity.
    • by iBod (534920)
      Absolutely Hal

      The code that runs most of the world as we know it is pig-ugly. But it doesn't matter because it works, day-in, day-out. Now I'm not advocating ugly code (I try to make mine as pretty as I can) but the fact is, ugly code can be workable and efficient.

      There seems to be a mindset here that only beautiful, elegant code can do the job. Not so!
      • That mindset happens, but that's not the idea of refactoring. The right mindset is that making your code more beautiful and more elegant before your next major functionality change will help with that. If you're not going to change anything other than the code layout, that's pretty silly.

        If you inherit code that's laid out badly (even from yourself when you were tired or rushed) and need to fix a bug or add a feature, the time to clean it up plus fix the bug in the cleaner version might not be much more tha
    • I've worked at a load of places where there's insufficient resources to do things that customers actually want

      As a curiosity, do you mean the companies lack talent or is there some other reasons that they fall short?
    • by halivar (535827)
      The problem comes when the old code doesn't "just work," and you have to fix it. It's one thing to deal with code that has multiple paths for special cases; I'm talking about poorly designed, poorly documented, and poorly written code, with 8 years of patch-work for all the bugs in it. If the code is bad enough, if really is simpler to rewrite it than to figure out what is wrong with the spaghetti. I don't have time to waste on crap that, at some point in the future, is going to make me waste even more time
    • by rk (6314) on Wednesday January 09, 2008 @02:34PM (#21971654) Journal

      But that's not what refactoring really is. Refactoring is not about making code "purdy", it's about making it so it's easier to add those layers of bugfixes that all successful production systems have. What you're referring to is a bunch of lazy, vain chuckleheads who don't want to read code. Refactoring is noticing that an enhancement or bugfix that requires you to make a similar change in umpteen places in the code and working to make it so the next enhancement/fix to it doesn't take so much time in the future. Refactoring is noticing that venerable function with all the layers of complexity isn't even used anymore by anything (and KNOWING that, not just assuming it) and giving it a dignified retirement. It's not going through software like the Code Gestapo and looking for everything that doesn't conform to "The Right Thing As I See It."

    • You seem to be making the mistake of thinking that refactoring means "making ugly software prettier" when a closer meaning is "making bad software better"
    • by Rycross (836649) on Wednesday January 09, 2008 @02:35PM (#21971672)
      In the original article, Joel explicitly states that refactoring is fine and may even be needed. What he's opposed to is rewriting, which is an entirely different thing than refactoring (and, to disagree with Joel, may be completely necessary in certain fringe cases).

      Good programmers can deal with ugly code, but if your code base takes two months to make a developer marginally productive and breaks in unpredictable ways from simple code changes, then you probably need to refactor. If you're spending tons of man hours treading water because the code is such an unbelievable mess that its nearly impossible to make a solid change without breaking something, then you're going to get better productivity if you bite the bullet and come up with a plan for refactoring.

      Also, I always have to laugh at the whole "well a great developer can work with messy code..." Unless you're working in a small, tight team, its completely impossible to make sure that you're working with a good developer, much less a great one. A lot of developers out there are poor or average, and companies, despite their best efforts to avoid doing so, do hire these people.
    • Customers don't care how ugly the code is, so long as it works.

      You've obviously never written a customer facing API.

      And good programmers can deal with ugly code [msdn.com]

      We "can" but I would rather not spend 8 hours grepping through trash, because some idiot used copy-paste coding rather than reusable functions and classes.

      • We "can" but I would rather not spend 8 hours grepping through trash

        Yep. What the parent pretends not to get is that every software developer is posessed of finite cognitive bandwidth. You can expend that bandwidth on the mental bookkeeping necessary to make sense of trashy code, or you can put resources into cleaning up the code so that it is no longer a needless cognitive drain.

        Furthermore, once cleaned up, the code stays cleaned up. The next developer to come along will not have to waste time maki

    • by BagMan2 (112243) on Wednesday January 09, 2008 @02:49PM (#21971890)
      There is no reason to refactor code that works and requires little to no maintenance. However, if you are working on a living code base, refactoring is critical to keeping things sane. I am not a fan of rewriting something just because it is ugly, but if ugly code requires significant modifications to support new functionality that is being added, then refactoring should be highly considered as part of the process. Hacking features into existing systems can be very time efficient in the short term, but almost without fail, the price paid is more difficult maintenance down the road, particularly if additional new features are to be added.

      Obviously refactoring needs to be carefully considered on a case by case basis. How ugly will hacking in the new feature make the code? How likely is it that other new features will also be added to this code down the road? How many other programmers have to deal with this portion of the code? How much time do you have to make the change? How much work is it to refactor the code and do it the right way, versus just hack in the feature? These and many other questions need to be answered before one determines whether refactoring is a worthwhile effort.

      As somebody who works primarily on server-software that is in a continuous state of changing and adding features, where stability is critical and expected lifetime is measured in decades, I personally have found that refactoring is almost always worthwhile in the end. I think the biggest problem with refactoring is not whether there is a need, but whether there is competence to get it done. Often times programmers will refactor something to work differently to their liking, but in reality will not have actually improved the flexibility of maintainability of the code at all.
    • by dcollins (135727)
      "... it's interesting that evolution, an unconscious process that far outperforms human 'intelligent' designers..."

      Won't agree with that. An interesting topic for debate or research, perhaps, but no way in hell can you toss that out like everyone automatically agrees with it.
    • by Krunch (704330)

      That's just in a PC application. Try refactoring the 'ugliness' out of an embedded system and see how long your employer still has customers, and how long you still have a job.

      Nearly three months now. Some of my code should go into production within one or two months, I'll tell you how it goes :)

      But I agree that you have a point.

    • by Aidtopia (667351)

      I've worked at a load of places where there's insufficient resources to do things that customers actually want, but an endless program to refactor away the ugliness of code.

      If the design is clear and appropriate, it takes much less time to implement what the customers need and want. Refactoring is about getting a design back on track so you can deliver more in less time. You should have a motivation for each refactoring step besides making the code prettier. You should undertake refactoring that makes

    • I have done just that. Taken a system that works, which not a damned person could read except the original author and restructured it from the inside out so that it became legible and malleable and worked correctly at each stage. This, on a system that recorded and aged telephone billing transactions in real time.

      Perhaps your rant is no more than that of someone who enjoys having code designed for job security.
    • by tentac1e (62936)

      You're right in the same reality where waterfall works.

      Customers do not, indeed, care how ugly the code is, so long as it work. They also don't care what it takes to implement a change quickly, so long as it's implemented. When they discover a critical bug six months after release, and demand you fix it, they don't care how hard it is.

      There is no excuse for poor code. If you wrote a thousand line function because of a customer demand, you were an idiot to fulfill that demand. You didn't have the time or r

    • by jcnnghm (538570)
      I've noticed this with some of my code. I was paging through the source of an application that I've been using internally for about 10 years now the other day, and I noticed that a good portion of the code base dealt with error handling and bug workarounds that were never present in the original release, but were slowly integrated in as problems crept up over the years, things like leap year bugs that you wouldn't necessarily test for. While I noticed all of that code and all of the different error messag
  • It's nice to see comments about the pitfalls of refactoring. (I'm sure it would be different on reddit :) ) In my experience it is very rare that any refactoring will actually improve an application.

    The worst part of refactoring, it breaks merges.
  • A lot of folks here just don't understand what 'REFACTORING' means.

    Wikki says:

    "A code refactoring is any change to a computer program's code which improves its readability or simplifies its structure without changing its results."

    It has nothing to do with the size source code or the functionality of the program.

    A properly refactored program will have the exact same characteristics and bugs as the original.

    Kids nowadays!
    • So, if you've got a program that shits itself and brings down the system every once in a blue moon and you discover the reason for this during refactoring -- you just keep that bug right in there and bring down the system? Hardly.
      • So, if you've got a program that shits itself and brings down the system every once in a blue moon and you discover the reason for this during refactoring -- you just keep that bug right in there and bring down the system? Hardly.

        You are misunderstanding what refactoring does. Refactoring changes the appearance of code without changing what the code does. Sometimes, changing the appearance of code changes what was a hard to find bug to an obvious bug. Fixing the bug is not part of refactoring. Once the code is refactored, you can then look at the bugs and fix them. Very carefully. If a function doesn't do what it is supposed to do, how do you know things don't break if it does what it supposed to do?

    • Re: (Score:3, Informative)

      I'm surprised that the companion web site [refactoring.com] for the book hasn't been posted here yet. It's the catalog [refactoring.com] that will be of most interest.

  • I see lots of comments about how old code is solid and reliable and should not be refactored. This group must be working in a very different environment than the ones I am accustomed too. All too often, I come into a project where the same bugs keep re-asserting their heads over and over again, and they keep getting fixed over and over again. Usually, it is because the original code contains some routines that were copied and pasted over and over again, and by refactoring you take the best block of code
  • Beautifying code is a subjective business.

    I used to work for IBM on the MVS (now z/os) operating system. At the time it was all written in s/370 assembler, but got rewritten in PL/S (a cousin of PL/I but with lower-level functions like direct register/memory access).

    I spent 3 years of my life (mid to late 80's) refactoring the MVS operating system. It was a mammoth exercise, and exacting too. There were 28 of us on the team, all top IBM sysprogs, based in the US (Armonk NY) and UK (Portsmouth). We had 5 IB
  • I once had to take over the support of a series of 10,000 line assembler programs that did not have a single comment. these programs would communicate through the printer port with a black box device that was use for testing monitoring equipment.

    Each different monitor had its own program so to make an across the board change to the codebase one had to change each program that was similar but different from the other.

    I took a couple days out and first added comments and dividing lines as to what test was bei
  • Refactoring (Score:2, Interesting)

    by jamie(really) (678877)

    There's lots of posts about how Refactoring is a waste of time, broke something or leads to bad code. I would put it to you that taking a saw and a hammer, one can do a lot to damage a perfectly good house. On the other hand, they can be used to build a nice new deck. I imagine that since I have no experience with a hammer that I would do a lot of damage. Why does everyone with no experience at Refactoring, and who tries it with poor results, assume that Refactoring is bad?

    What to about this? Some options:

    • You forgot... (Score:3, Insightful)

      Write tests!

      The only way you can make sure while refactoring an application that at the end of the process it will still behave the same way as it did before the refactoring is to write unit tests. Never (heavily) refactor untested code.

A method of solution is perfect if we can forsee from the start, and even prove, that following that method we shall attain our aim. -- Leibnitz

Working...