«    »

Why You Should Polish Your Code

When are you done writing a piece of code? Is it when you have implemented the necessary functionality? When you have tested it? I believe there is more to professional-quality code than just getting it to function properly. What else is there? Making sure the code is maintainable - well designed and understandable. I use the term polishing code to refer to this kind of work that is done on a code base after it is functioning properly. I like the analogy with woodworking: once a piece is assembled and finished, the final step is to polish the surface to make it shine.

Based on the code bases I have seen and worked with, polishing code is not a frequent practice. In fact, I have encountered people who are surprised by my commitment to it, or who do not believe in its value. Many of these people are not developers, or have not spent much time doing ongoing software maintenance. Part of the reason for the lack of appreciation is that polishing code provides long term benefits for a short term cost. This induces project managers and developers on development projects with compressed time frames to skip such kinds of activities. In other cases, non-technical managers simply have no idea of the poor quality of code their developers are producing. One project manager I dealt with personally reviewed and made minor grammatical corrections to the documentation produced by the project team, but had no similar processes in place for the poor quality code produced by the project team.

So why do I believe that polishing code is valuable? I have several reasons. The most important is that it minimizes the long term cost of maintaining the software. To explain this, I like to use the concept of technical debt. Quality issues such as poor design in software represent a debt for which you will need to make continuing interest payments later in the form of increased effort to understand or change the software. This is the case even if the software functions correctly. To pay off that debt, you must address the underlying quality issues - in other words, you must polish the code. Martin Fowler wrote a recent article about this topic in the context of good design that explains the trade-offs involved. Another reason I polish my code is that it is a permanent record of my capabilities as a professional software developer. My reputation amongst developers who need to work with my code later is in large part determined by my code's quality. Code of mine that is difficult to understand or change or is riddled with defects will have maintenance developers cursing at me. I would rather have them be pleasantly surprised at finding helpful comments and a clean design.

So now you hopefully believe that polishing code is valuable, but you may be asking how exactly to go about it. In terms of timing, polishing of code should ideally be done throughout the development of a section of code. In reality, however, it is much easier to focus on one issue at a time, and the primary issue is just getting the code to work. Therefore after the code is written and passing the automated unit tests, it is only natural for it to have some rough spots. This is the ideal point to do a review of your code to identify places to polish. My basic goals when polishing are to improve the understandability of the code and to improve its design. During the review, I look for specific problems impacting these two goals. When I find such a problem, I immediately rectify it by refactoring the code. Often it is as easy as using one of the built-in refactoring tools of the development environment to safely make the change with a near-zero risk of introducing defects.

Some examples of specific problems I look for are:

  • Duplication of logic in two or more places.
  • Undesired dependencies. For applications divided into layers such as persistence, business and user interface, the dependencies between the layers need to be managed. Finding undesired dependencies such as the use of persistence code directly within the user interface layer is a strong indicator of a design problem.
  • Overly complex logic, like a large switch statement or series of nested if-else statements. Sometimes such logic can be drastically simplified through the use of object-oriented design principles.
  • Too many classes within one package.
  • Too many methods within a class, particularly public methods. This is often an indicator that the class is trying to do too much and should be split into multiple classes.
  • Overly long file, in excess of a couple thousand lines. Even in Java where each public class is forced to be in its own file, it is possible to end up with very long files. This may be because there is too much logic within the class, or it may be because of many nested classes or private classes in the same file. In the latter case, these can be moved to one or more separate files.
  • Overly long methods. Anything longer than about one screen warrants a closer look to see if it can be simplified, usually via an extract method refactoring.
  • Poorly named classes, methods, fields or local variables. One indicator I look for is a one-sentence comment describing a vaguely named variable or method. Usually the variable or method can be renamed to capture the essence of the comment and the comment can then be deleted.
  • Lack of a class comment. A concise summary of the purpose of the class is often quite useful. If it is difficult to come up with such a summary, it is an indicator that the class may be trying to do too much or does not have a clear focus.

Ron Jeffries' site http://www.xprogramming.com/ has a great series of articles that provide concrete examples of polishing code, including before and after samples of the source code.

Polishing your own code is good, but it is better if your entire team adopts the practice. An effective way to ensure code is polished within a team is via code reviews. While ideally everyone should polish their own code, having a separate reviewer check for code quality problems is a big help. This is especially true for ensuring that the code is understandable by someone other than the original developer.

Applications with polished code are easier to understand and modify, which helps extend their useful life. Applications with poor quality code are more likely to be partially rewritten or even completely replaced if the cost of ongoing maintenance becomes too high. Which of these applications would you prefer to contribute to? The choice is yours.

If you find this article helpful, please make a donation.

13 Comments on “Why You Should Polish Your Code”

  1. cm says:

    code ages.. So I agree with you in general. But if you look at your polished code in half a year you might think: What the … ;-) At least this is how I feel sometimes.

  2. Mark says:

    Couldn’t agree more Basil, good article. I’ve just finished polishing up a piece of code this afternoon.

    Another code polishing task I consider worthwhile is to reorder the methods in the class to a more logical order. This helps me to solidify my mental picture of the class and makes it more readable/maintainable.

    In fact, I believe one benefit of code polishing in general is that by spending more time looking at and touching the code your mental picture of what the code is doing becomes more clear. This is true both for the code’s workings at a high level and for the low level intricacies of your algorithms, say. This definitely helps if you ever have to revisit the class yourself.

  3. I’m glad you both agree. And yes, cm, looking at my polished code months (or even weeks) later is a good way to feel humble.

  4. Squall says:

    Totally agree with you. In fact, I consider polishing as a part of coding. That means I cannot feel that I have finished coding if I have not polished my code.

    Your list of problems is very helful. Recently, while polishing the code, I have found that one of my method does two different things at a time. Even the method is not long (about 15 lines). I have refactored it and created 2 methods. So I want to add the rule “violation of the principle Single Responsibility” to the list.

    After testing and (quickly) polishing my code, I like to take a break, do other thing within 1 or 2 days and then return to my code for a thorough polishing. With this method, I can have a new look at my code (It’s sad to avow that in my company, noone care about the quality of code, there is even no comment at all – so I do this work really for myself)

  5. [...] Why You Should Polish Your Code Filed under: Software Development, Java, Programming — funjava @ 9:40 am. I highly recommend this article: Why You Should Polish Your Code [...]

  6. Mark says:

    Perhaps you could polish my previous comment Basil, typos galore :-)

  7. Your comment wasn’t the only one needing polishing :) Hopefully I got all the typos.

  8. [...] Why you should polish your code es uno de esos artículos que recomendaría leer a todo aquel (yo, el primero) que ha programado alguna vez. Explica, en inglés, la importancia que tiene programar de una manera clara, estructurada y concisa. [...]

  9. Stefano says:

    Good post, thank you.

    Keeping the code clear and polished helps reading, analyzing, maintaining, debugging and version controlling.
    But be careful when you refactor your code: every change can introduce new bugs. Try to make frequent but small changes, and cover your code with unit testing to make changes safer…

  10. Nick Malik says:

    Would you consider the act of ‘polishing code’ distinctly different, in some material way, from ‘refactoring the code?’ Many of the transformations you suggest are represented in the literation on refactoring.

    The key point of disagreement appears to be “when.” Some say: do it before first release, some say do it as a second pass, still other say to ‘polish’ old code before you work on it, so that you know what you have.

    Have you thought about the variations in “when” to polish the code between various SDLC processes?

  11. Nick, those are great questions.

    Most of the changes I make when polishing code are indeed refactorings. Perhaps the one exception is adding or improving comments. I think the main difference is in intent: refactoring is focused only upon improving the design, whereas when I polish code my overall goal is to improve the maintainability of the code. This of course includes improving the design, but also addresses readability.

    As for when to polish, I agree it could be done at different points in the software development life cycle. My article was focused on doing it on your code just after you have ‘finished’ writing it, both to challenge developers to create better code themselves, and because it fits the analogy of woodworking, where you polish a piece of wood as the final step. So while refactoring the code before you start to work on it often makes sense, to call that polishing goes against the grain of the analogy.

    Your comment seemed to imply that you would normally only polish or refactor code at one point in the SDLC. This I don’t agree with. I believe that you should always polish code after working on it. Refactoring or cleaning up code before you start working on it is optional, but certainly doing both can make sense. So perhaps the key point of disagreement is “how often” instead of “when” :)

  12. Ben Northrop says:

    Great article. Seems like a very fuzzy distinction between “refactoring” and “polishing” though. From the Wikipedia, “a code refactoring is any change to a computer program which improves its readability or simplifies its structure without changing its results.” With this definition, it doesn’t seem like refactoring only applies to design, but rather to any change to code that enhances maintainability…in which case “refactoring” and “polishing” are quite similar, if not the same.

    Anyway, great article. I agree that reputation is a strong motivator for polishing/refactoring.

  13. [...] Why You Should Polish Your Code Having read and refactored a lot of other people’s code, I can’t express how important it is to clean up your code afterwards. Would you want your painter to leave his mess after he finishes painting your house? Clean up after yourself. [...]

«    »