DEV Community

loading...

Is my code self-documenting?

Juha-Matti Santala
I'm a developer community builder and full-stack web developer from Finland. I blog occasionally here and weekly at my own blog at hamatti.org
・1 min read

So you know how some people say that "Good code documents itself"?

Is this what they meant?

def self_documenting_sum(a, b):
    with open(__file__, 'r') as source:
        data = source.read().split('\n')

    with open(__file__, 'w') as source:
        if not data[1].startswith('    "'):
            documentation = '    """Sums up two integers"""'
            new_source = data[:]
            new_source.insert(1, documentation)
            source.write('\n'.join(new_source))
        else:
            source.write('\n'.join(data))
    return a + b


print(self_documenting_sum(2,5))
Enter fullscreen mode Exit fullscreen mode

(It's a Python script that adds docstring to its only function on the first run.)

edit: I expanded on the idea a bit in hamatti/self-documenting-code

Discussion (0)