Rule: be coherent. If modifying someone else's code written with a different style, adopt that style too so that the source style remains coherent.
Several styles for indentation have been shown in the previous chapter, comparing them for struture only. Sometimes
other factors are introduced in evaluating those styles, such as for example the cost of adding and removing lines
of code. These metrics are rarely completely objective and universally accepted though, so it's probably better
to prefer visual clarity over saving half a second when selecting a block to copy.
The last two examples in the previous chapter, the BSD style and K&R style, have similar features and most people find it very easy to read them. Those styles, and especially K&R, also translate nicely to other languages. For example, they produce indentation patterns similar to those found in Java and Python (a language where indentation is part of the language itself).
Style of course doesn't refer only to indentation but also to other very important elements such as where declarations are placed, their relative order, how function headers are formatted and so on. These style elements are at least as important as the visual elements of grouping and indentation.
The most important and possibly the only rule that can be stated for style is: be coherent. Pick up any one style and always stick to it. It is most annoying to read some code without being able to find out at least some basic rules that can help read it or find things around.
A consequence of the above is that when you modify someone else's code you have to adopt the style and convention of the code you are modifying and not your own personal preferences. Again, this makes sure that the resulting code only follows one set of rules, making it considerably easier to read and understand.
Well... is all of this really useful? Structure and style? Placement and ordering? In my opinion, it is. Even if a programmer has never seen a piece of code before, she will start to undestand it and make connections within minutes as long as there are connections to make, that is if the code is well structured. And since the source code structure reflects the program structure, the latter becomes easier to understand and in general to work with. This is very good for you in the first instance, but becomes even more important if your code has to be maintained by different programmers: they will appreciate it a lot! At least, as a programmer who has spent literally thousands of hours on someone else's code, at least I know I do.
Top: Table of content | Previous: Structure | Next: Comments
Copyright (c) 2003 Alessandro Scotti. All rights reserved.