Documenting Code
I'm pretty sure we all hate documenting code, and we are all guilty of not updating the documentation when we make a change. We are all also equally frustrated when we are asked to work on something that hasn't been documented and is difficult to read.
So, how should we approach this onerous task.
The first thing to decide is what the documentation is supposed to give us. In my view this really quite simple and gives me text that never needs to change, even when I refactor my code.
Documentation is supposed to tell us what the documented code does. It should never try and say how it does it. We can read the code to learn that. We can use tools and formats for this kind of documentation so that IDE's can give us nice helpers.
The other thing we can do is make our code easier to read. We can so easily write what I like to call self documenting code by choosing good variable and functions, method and class names.
Lets take a single line of code in a basket management method as an example.
// Add $a to $b and store the results in $x
$x = $a + $b;
I can easily see that this adds 2 numbers together - so the comment is useless. The comment can also go out of date if I refactor the code and change the variable names.
I know that this is basket code so a DocBlock at the start of the method can detail what kind of basket functionality we are dealing with. A little thought given to the variable names will make the line of code abundantly clear without having to have a comment at all. The maths is there to calculate the total of goods and shipping to give a grand total, so if I write it as follows...
$grandTotal = $totalProductCost + $shippingCost;
I can really understand what is going on because the code is self documenting. If I refactor the purpose of the code remains the same so I don't need to alter my DocBlock which describes the purpose.
What was once onerous becomes not only easy, but a lot less work. It's also incredibly simple - and the most effective things we can do are often this simple.