Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
  ...
like image 285
Roland Avatar asked Aug 25 '16 08:08

Roland


People also ask

How do you name variables in your code?

You see those kinds of variables in every piece of software code. I use the following convention for naming those kinds of variables: numberOf<something> or alternatively <something>Count. For example, numberOfFailures or failureCount. Someone might use the variable name failures.

How do you pass a variable from one object to another?

By using concat () method: Create a new array variable and then concatenate the older one in the new array. Pass by reference in Object: The same point goes for objects, it also affects the original object.

What are the best practices for naming variables in JavaScript?

Standard, common naming - For dumb environments (text editors): Classes should be in ProperCase, variables should be short and if needed be in snake_case and functions should be in camelCase. For JavaScript, it's a classic case of the restraints of the language and the tools affecting naming.

What should a variable name say about it?

As Robert Martin says: The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. From Clean Code - A Handbook of Agile Software Craftsmanship


2 Answers

It ultimately comes down to what you want to communicate to future programmers. The computer obviously doesn't care; it's other people you're talking to. So the biggest factor is going to be what those people need to know:

  • What is the logical (abstract, conceptual) meaning of this variable?
  • What aspects of how this variable is used could be confusing to programmers?
  • What are the most important things about this variable?

Looking at your first example, it's kind of hard to understand enough about your program to really choose a good name. The method is called process; but methods generally speaking implement computational processes, so this name really doesn't tell me anything at all. What are you processing? What is the process? Who are you processing it for, and why? Knowing what the method does, and the class it's in, will help to inform your variable name.

Let's add some assumptions. Let's say you're building an application that locates Wi-fi access points in a building. The Node in question is a wireless node, with subclasses Repeater, AccessPoint, and Client. Let's also say it's an online-processed dataset, so the collection of nodes given may change at any time in response to a background thread receiving updates in what nodes are currently visible. Your reason for copying the collection at the head of the method is to isolate yourself from those changes for the duration of local processing. Finally, let's assume that your method is sorting the nodes by ping time (explaining why the method takes a generic Collection but returns the more specific List type).

Now that we better understand your system, let's use that understanding to choose some names that communicate the logical intention of your system to future developers:

class NetworkScanner {
    List<Node> sortByPingTime(Collection<Node> networkNodes) {
        final ArrayList<Node> unsortedSnapshot;

        synchronized(networkNodes) {
            unsortedSnapshot = new ArrayList<>(networkNodes);
        }

        return Utils.sort(unsortedSnapshot, (x,y) -> x.ping < y.ping);
    }
}

So the method is sortByPingTime to define what it does; the argument is networkNodes to describe what kind of node we're looking at. And the variable is called unsortedSnapshot to express two things about it that aren't visible just by reading the code:

  • It's a snapshot of something (implying that the original is somehow volatile); and
  • It has no order that matters to us (suggesting that it might have, by the time we're done with it).

We could put nodes in there, but that's immediately visible from the input argument. We could also call this snapshotToSort but that's visible in the fact that we hand it off to a sort routine immediately below.

This example remains kind of contrived. The method is really too short for the variable name to matter much. In real life I'd probably just call it out, because picking a good name would take longer than anyone will ever waste figuring out how this method works.

Other related notes:

  • Naming is inherently a bit subjective. My name will never work for everyone, especially when multiple human languages are taken into account.
  • I find that the best name is often no name at all. If I can get away with making something anonymous, I will--this minimizes the risk of the variable being reused, and reduces symbols in IDE 'find' boxes. Generally this also pushes me to write tighter, more functional code, which I view as a good thing.
  • Some people like to include the variable's type in its name; I've always found that a bit odd because the type is generally immediately obvious, and the compiler will usually catch me if I get it wrong anyway.
  • "Keep it Simple" is in full force here, as everywhere. Most of the time your variable name will not help someone avoid future work. My rule of thumb is, name it something dumb, and if I ever end up scratching my head about what something means, choose that occasion to name it something good.
like image 127
Mark McKenna Avatar answered Oct 29 '22 02:10

Mark McKenna


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).

like image 36
acm Avatar answered Oct 29 '22 00:10

acm