Monday, April 14, 2014

Dev basics: Purpose explanation

Code reuse is essential to reduce the time spent not only on development (writing the code) but also on maintanence (figuring out what went wrong and where the hell in the huge codebase the problem lies) and it's a generally a good thing. However, to do it properly, any code unit with a potential of re-use should also have a good documentation. And good documentation does not mean this:

    This function returns the background color.
    @returns the background color
Color getBackgroundColor() {}

that's actually bad and useless documentation. Instead, documentation should provide the intention with the highest priority and then any other technical details.

Intention is a very important concept for code documentation. Developers should try to write down the intention they have in mind for a given piece of code (function, class, module) when they are writing it. Any usage of that piece then must be in line with that intention because it wouldn't make sense to use code in conflict with its intention. And when something in a program doesn't make sense, it will break.

You see, code is not just code. It has a meaning. Even when the code implementing a given purpose is very simple and incomplete, it still has a meaning and must be used according to its meaning and purpose. If you use a piece code based on reading its implementation but ignoring its intent, you are going to get in trouble when it changes. But how do you know the intent when the original developer didn't write it down?

Let's see a very simple example. Consider this function:

def join(path_elements):
    return '/'.join(path_elements)

and this function:

def join(path_elements):
    'Creates a WebDAV HTTP request url from given path elements'
    return '/'.join(path_elements)

With the second one, you immediately know that you cannot use it to build paths for the local filesystem because that has different rules than HTTP URLs! It would work at the moment on Linux but break as soon as someone made a WebDAV specific change. And, of course, this distinction should be obvious from the function name, that's the first place where you should attempt to document the meaning. If it's too long or complicated, continue in the function's documentation.

Document the purpose or intent of the code, the rest can be usually read from the code. This is easier said than done, sometimes you're not really sure what the one purpose of the code is or you don't know how to explain it in writing. That's probably a signal that this thing is harder to understand and that's a signal that the next programmer will have trouble as well. And that means that you need to spend more time thinking about this because it will pay off. Help them and write some docs!

No comments:

Post a Comment