Name methods and variables with respect to the owning class by asking the question “If I were the class, what would the method or variable be called from my perspective? What would I call it when I wanted to refer to it?”
For example, an IntegrationPartnerConnection class is used to store communication details so we can query external systems. It has two names for JMS queues in it, one for incoming data and another for outgoing data. But is it “incoming” with respect to the external party or with respect to the IntegrationPartnerConnection?
public class IntegrationPartnerConnection
{
:
// is it our incoming or the external partner incoming queue?
private String incomingQueueName;
// is it our outgoing or the external partner outgoing queue?
private String outgoingQueueName;
:
}
The answer can be determined by looking at where the queue variables are defined. They are defined in the IntegrationPartnerConnection so they should be named with respect to it.
“If I was an IntegrationPartnerConnection, what would I call my incoming queue?”
So the queues are always named with respect to the owning class, but an added comment to avoid any ambiguity helps.
eg.
public class IntegrationPartnerConnection
{
:
// My queues, from the perspective of me, the Connection
private String incomingQueueName;
private String outgoingQueueName;
:
}
As another example, think of a piece of code that deals with a folder that used both an import or export directory. Class OrderUploader uses the folder as an export directory (it places a file there), and OrderProcessor uses the folder as an import directory (it reads a file from there).
public class OrderUploader
{
private File exportFolder;
:
}
public class OrderProcessor
{
private File importFolder;
:
}
Therefore the name of the folder in OrderUploader is “exportFolder”, and the name of the folder in OrderProcessor is “importFolder”. ie. “am I exporting or importing?” This example seems simple enough but for more complex tasks, getting the right context is important.
Trap: a common mistake is to name variables based on other classes that will be using the variables even though they are not the owners of the variable. Repeat the question: “If I am the owning class, what does the variable represent to me?”.
After applying this rule, if you still can't work out if the name of the variable should be 'input' or 'output', perhaps it is defined in the wrong class. Your fellow programmers are always happy to discuss the best choice of naming convention and variable location.