Long Private Method Names Are OK

Sometimes software developers are reluctant to use long names for private methods. 

Private methods are those that may only be called within a class. Other classes do not have access to them.

 

It’s OK for private methods to have long, descriptive names

 

Why? 

When a private method name clearly describes its behaviour, we won’t need an explanatory comment. To be unambiguously descriptive means the naming may end up a bit longer than what we usually deem acceptable. 

An extended method descriptor is preferable to a comment in almost all situations.

Comments, as we have discovered previously, tend to decay with time. Overall, method names tend to stay more truthful as to a method’s purpose. 

Maybe it simply comes down to us developers updating a method’s name when we change its behaviour—and yet we are less conscientious with comments.

 

Either we sprinkle comments throughout our code to describe what’s going on, or we can use our expressive, modern languages to do so. The latter is, by far, the preferred option.

 

An example is in order. Below we have the code from a class called TransactionImporter. TransactionImporter manages a high-level workflow for reading and saving bank account transactions:

  private async Task<AccountTransactionImportResult> TryImportTransactions(ImportAccount account)
  {
     var dateRange = DateRange = CalcLatestTransactionPeriod();
     var repoTx = await GetRepoTransactions(account, dateRange);
     var bankTx = await GetBankTransactions(account, dateRange);
     var newTx = CalcNewCompletedTransactions(repoTx, bankTx);
     if (newTx.Any())
        await SaveNewCompletedTransactions(newTx);
     var pendingTx = bankTx.PendingTransactions;
     await SavePendingBankTransactions(pendingTx);
     return CreateSuccessResult(account, dateRange, newTx, pendingTx);
  }

Each of these methods is private. Notice how the method names are long and descriptive. And so we understand the gist of what is going on: 

  1. Calculate a period for which we want transactions,
  2. Get transactions from the repository for the account and period,
  3. Get transactions from the bank for the account and period,
  4. Calculate whether there are new, completed transactions,
  5. If there are, then save them,
  6. Save the pending transactions,
  7. Create and return a successful result.

It’s OK to use long descriptors—for private methods at least. What about public ones? We explore the naming of public methods here.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply