Wednesday, November 16, 2005

Code Advice #8: Reformat all your code. Yes. Do it.

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


(See intro for a background and caveats on these coding advice blog entries.)



In my previous entry I covered source code archaeology. That entry was leading up to a coding tip: Reformat your source code.



Sometimes you find yourself working on an old code base. Perhaps it has some accidental embedded tabs here and there, perhaps it follows an old-school formatting style (perhaps from a recently converted C++ programmer still hanging on to the unholy GNU bracing style.



If you own the source code yourself, or if all the programmers cooperating on this source base agree on a coding style, consider reformatting all of it to your agreed upon style - and keep it that way.



I won't go into the arguments against reformatting again - I cover those in the source code archaeology entry. Let me just state how this can work. In my case, I use the Jalopy plugin to NetBeans to do source formatting - but of course it has plugins for other IDEs (or even command line usage) so the IDE choice is not limited by your decision to reformat the source base. Now, the formatting settings can be exported to XML. Check this XML file into your versioning system, and have everybody import it. Now you'll be sure people format the source code in the same consistent way and you won't have "noisy diffs" as two developers take turns checking in versions of a file using different formatters or settings.



Here's my settings-file. It's basically the default jalopy settings (which closely match the JDK style) but with some tweaks. First, line lengths are bumped to 100. Second, limit grouping in import statements to only differentiate between top level domains, e.g. java, javax, org and com.



Two final comments:


  • First, make sure that your formatting checkins don't contain any other changes (e.g. code changes); with lots of diffs it will be a lot harder to discover what they are. Future source code archaeologists should be able to read your "source reformat - no semantic change" comment and be able to mostly ignore that delta.




  • Second, if you're dealing with branches, you might think you would have a hard time merging changes back to the (reformatted) trunk, but no - that's easy: just perform a source reformat on the branch code too before diffing!



No comments:

Post a Comment