Java – how to name a variable for a copy of a parameter?

I have a method to handle the collection < nodes > passed in as a parameter This collection will be modified, so I think it's good to make a copy first How do I name parameters and local variables, such as nodes, in the following example?

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

As another example, consider that the following variables are int parsed from the string parameter:

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

Solution

A good way to solve the name variable problem is to use a name that prompts the actual meaning of the variable In your example, the name you use has no effect on the meaning of method functions or variables, so it is difficult to choose a name

There are many examples in JDK, such as yours 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,copy,Math.min(original.length,newLength));
    return copy;
}

In this case, they call a copy of the parameter original and local variables, fully indicating that the return value is a copy of the parameter To be exact, replication is done in this way, so it is named

Using the same reasoning as in your case (please consider refactoring to provide more meaningful names for your methods and variables), I will name your local node, similar to processednodes, to express what the variable is and consistent with the name of your method

Edit:

The name of the new method you add in the edit does not provide hints about its operation I'll assume that it modifies some properties of the user who passes the ID through the parameter (possibly in the database)

If this is the case (or similar), I think the appropriate method you can apply for is that each method should have a responsibility According to the name of your method, it should handle users, because you need an int userid The responsibility for resolving string userid should be outside the scope of this method

Using the proposed method has the following advantages:

>If you have to add additional validation to the input, your course will not change. > Your course is not responsible for handling numberformatexception, which must be the responsibility of the application. > If you have to process different types of input (such as float userid), your processuser method will not change

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>