Practice: Programming by Intention

Listen to this post
Subscribe

Programming by Intention is a way of writing code that capitalizes on the way a programmer thinks.

Whenever you write code, what you are essentially doing in breaking down a behavior into its steps. In sense, that’s what code is. So, your brain, as a developer, is good at this. Programming by Intention says let’s capitalize on this fact.

Example

You have a transaction processor that can commit a transaction more than one way, depending on its size. The transaction string needs to be tokenized and normalized before being committed. Programming by Intention suggests you write the code this way:

class Transaction {
   public Boolean commit(String command){
      Boolean result = true;
      String[] tokens = tokenize(command);
      normalizeTokens(tokens);
      if(tokens.Length > getMaximumLength()){
         result =
            processLargeTransaction(tokens);
      } else {
         result =
            processSmallTransaction(tokens);
      }
      return result;
   }
  }
}

Why this is a good idea

The “helper” methods do not exist yet. We are hypothesizing that they will later: we will create them. This is a very simple thing to learn and do. But what is the point? Why is it a good idea?

Coding in this way creates a fundamental separation of concerns.

  • The primary function code is all about the process of the behavior. If, in the example, this code is inherited by a new developer or team, then reading the commit() method in the example will tell the entire story of how this object works.
  • Each helper method is about the implementation of one step along the way. This makes finding defects and integrating new steps much easier. It also makes the code easier to understand, thus requiring minimal comments along the way.

Also, creating discrete methods for each functional step makes for reusability and ease in refactoring. For example, if later it is determined that tokenizing the committed string should be done in different ways under different circumstances, then converting the tokenize() method into a Strategy will be much easier.

Programming by Intention can be adopted as a practice because it does not create additional work: the code written into the helper methods is the same code that would have been written in-line. It’s just written at a different time and in a different location. Also, developers will readily adopt it once they try it even a single time. It proves itself.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.