Self-Commenting Code

https://news.ycombinator.com/item?id=170911
by palish • 18 years ago
2 4 18 years ago

Consider this programming style:

  for each function,
    - first write out its algorithm in comments,
    - then implement that.
It seems like that programming style can result in higher-quality code with fewer bugs.

As an example, let's implement a simple "ends_with?" string utility function. The function takes two strings and returns whether the first ends with the second:

  bool endsWith( const char* haystack, const char* ending )
Following our new programming style, we first write out its implementation in comments:
  bool endsWith( const char* haystack, const char* ending )
  {
    // find the end of [haystack] and [ending].

    // if [haystack] is shorter than [ending] then it can't end with [ending], so return false.

    // walk backwards through both strings.

      // if a character differs, return false.

    // otherwise, [haystack] ends with [ending], so return true.
  }

Pretty straightforward. And now we can implement the function in an equally straightforward way:
  bool endsWith( const char* haystack, const char* ending )
  {
    // find the end of [haystack] and [ending].
    const char *haystackEnd = haystack;
    const char *endingEnd = ending;
    while( *haystackEnd ) 
      haystackEnd++;
    while( *endingEnd ) 
      endingEnd++;

    // if [haystack] is shorter than [ending] then it can't end with [ending], so return false.
    if( haystackEnd - haystack < endingEnd - ending )
      return false;

    // walk backwards through both strings.
    while( endingEnd != ending )
    {
      // if a character differs, return false.
      if( *endingEnd != *haystackEnd )
        return false;

      --endingEnd;
      --haystackEnd;
    }

    // otherwise, [haystack] ends with [ending], so return true.
    return true;
  }
What is interesting about this style is that the result will usually be simple to read and understand. The key is to write out the function's comments first, not last. Is this a common programming style?

A friend of mine uses this technique in his game engine to great effect. The engine's source code is beautiful, mostly because each algorithm is simple and can be understood by reading clear English.

Related Stories

Loading related stories...

Source preview

news.ycombinator.com