Complexity In Short Functions

 

One beautiful property of sub-ten line functions is that they don’t support many different paths through the code. There is only room for one or two levels of indentation most of the time. The programming feels well-thought-out and structured.

We have arrived at Structured Programming—creating systems that are simple to follow due to the judicious use of control flow constructs (if/else), repetitions (while/for loops) and splitting the code up into subroutines (helper functions). Alongside Object-Oriented Programming and Functional Programming, Structured Programming is the third programming paradigm. It’s worth learning about the concepts of Structured Programming.

These days, I’d say about half my methods have only a single indentation level. Only a single path through the code – no conditionals or loops. Here’s an example:

  private async Task<OrderedAccountTransactions> GetBankTransactions(ImportAccount account,
     DateRangeQuery dateRange)
  {
     await BankLogin(account.Credential);
     return await BankClient.GetTransactions(account, dateRange);
  }

This method linearly progresses through the login with the bank and then gets the transactions. It couldn’t be simpler.

About the other half of the time, my methods contain a conditional or loop – adding a level of indentation and some minor, necessary complexity:

  private async Task<CompletedAccountTxList> CalcAndSaveNewCompletedTransactions(
     OrderedAccountTransactions savedTx,
     OrderedAccountTransactions bankTx)
  {
     var newTx = CalcNewCompletedTransactions(savedTx, bankTx);
     if (newTx.Any())
        await SaveNewCompletedTransactions(newTx);
     return newTx;
  }

The code branches off and does one thing if there are newly completed bank transactions and then proceeds to save them. Otherwise, we skip the saving and carry on. Overall clarity is still high since we only have a single if statement.

Rarely I end up with a combination of a loop and a conditional bumping the code indentation level to three, as in this example:

  private bool HasAtLeastOneArchivedClient()
  {
     foreach (var client in Clients)
        if (client.IsArchived)
           return true;
     return false;
  }

Still very clear and easy to read. What do you think?

The power of the short function lies in the difficulty of writing hard-to-follow code. (Having said that, where there is a will, there is a way.)

Functions shorter than ten lines don’t have room to hide much complexity.

And that is an excellent place to be.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply