How to name a variable that is a copy of a parameter?

Roland :

I have a method that will process a Collection<Nodes> that is passed in as a parameter. This Collection will be modified, therefore I thought it would be good to first make a copy of it. How do I name the parameter and local variable, e.g. nodes in the example below?

List<Nodes> process(Collection<Nodes> nodes) {
  List<Nodes> nodes2 = new ArrayList<>(nodes);
  ...
}

As another example consider the following where the variable is an int parsed from a String parameter:

public void processUser(final String userId) {
  final int userId2 = Integer.parseInt(userId);
  ...
acm :

A good approach to the name variables problem is to use names that suggest the actual meaning of the variable. In your example, you are using names that do not say anything about the method functionality or variables meaning, that's why it is hard to pick a name.

There are many cases like yours in the JDK, e.g. Arrays#copyOf:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings("unchecked")
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

In this case they call the parameter original and the local variable copy which perfectly expresses that the returned value is a copy of the parameter. Precisely, copying is what this method does and it is named accordingly.

Using the same reasoning for your case (consider refactoring to give more meaningful names to your method and variables) I would name your local copy of nodes something like processedNodes, to express what that variable is and to be consistent with your method's name.

Edit:

The name of the new method you added in your edit does not provide hints about what it does either. I'll assume that it modifies some properties (maybe in a database) of the user whose id is passed via parameter.

If that is the case (or similar), I think that an appropriate approach you could apply would be that every method should have a single responsibility. According to your method's name it should process the user, for that you need an int userId. The responsibility of parsing an String userId should be out of the scope of this method.

Using the proposed approach has, among others, the following advantages:

  • Your class won't change if you have to add additional validation to your input.

  • Your class won't be responsible for handling NumberFormatException which must be the application responsibility.

  • Your processUser method won't change if you have to handle different types of inputs (e.g. float userId).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452948&siteId=1