Avoid Long Public Method Names
Long private
method names are OK, but the same is not valid for public
methods?
How come?
Public methods are part of a class’ interface. It’s how external callers interact with it and make it do things.
With public methods, we are looking to convey information concisely. When we scan a list of 20 method signatures, we want to find the best fit for our needs as quickly as possible. We want short method names. Conciseness is king.
Generally, developers prefer overloads (same name, different parameters) rather than methods that explain their entire parameter list. That’s why in .NET there are three File.Open()
method overloads rather than a File.OpenByPath()
, a File.OpenByPathAndWithMode()
, and a File.OpenByPathAndWithModeAndAccess()
.
How could we shorten the methods on the following interface?
public interface ICustomerRepository { Customer GetByEmailAddress(string emailAddress); Customer GetById(Guid id); Customer GetByCustomerNumber(int customerNumber); }
Is it necessary for the method names to reflect the parameter names?
No, that seems redundant.
How about reducing the methods to a set of Get()
method overloads?
public interface ICustomerRepository { Customer Get(string emailAddress); Customer Get(Guid id); Customer Get(int customerNumber); }
Yes, that works.
A word of caution. We should always perform a Gedankenexperiment and mentally double-check whether the shortened names for our public methods still make sense. Here is an example that makes this point.
Below is the signature for the sole public method from class TransactionImporter
:
(We encountered TransactionImporter
code in the previous article on private method naming.)
public async Task<ImportResult> ImportTransactions(ImportAccount account)
Could we shorten method ImportTransactions()
to Import()
?
Let’s see how it might look when we call it:
var result = await importer.Import(account);
What is reference importer importing? We can refer back to the method signature to get an idea, but we shouldn’t need to do that. All great code can be understood contextually—i.e. without taking a peek at the method signature. The upshot here is that we should leave the method name as ImportTransactions() and not shorten it further.
Note: Another way would have been to use a longer reference, for example transactionImporter
, rather than just importer
, and then the shorter method name would work too:
var result = await transactionImporter.Import(account);
So, the guidance here is to Avoid Long Public Method Names, if possible. However, the short names still need to make sense when called.
Leave a Reply
Want to join the discussion?Feel free to contribute!