10

Can someone imagine when this code:

public static void main(final String[] args) {
   // do something
}

should become this:

public static void main(final String[] args) {
   String[] argsCopy = doCopy(args);
   // do something
}

(In our company we have a Sonar rule that forces such coping or arguments for all methods.) I can imagine why it can be important for standard methods, but I cannot find any benefit of having it done at a start of tools main method. Am I missing something?

dantuch
  • 9,123
  • 6
  • 45
  • 68
  • 5
    You obviously should use languages where it is impossible to mutate callers state. That being said, it is poor the tool does not recognize if the argument is actually mutated. – Ingo Sep 23 '14 at 17:55
  • some discussion is here: http://stackoverflow.com/questions/11580948/sonar-violation-security-array-is-stored-directly – przemek hertel Sep 23 '14 at 17:59
  • 1
    I am not an enthusiast of this sonar rule. What is more - I consider this rule as bad idea. What if I want to store large binary data byte[] in my objects? Copying then just after being built from some stream is unnecessary in my opinion. – przemek hertel Sep 23 '14 at 18:06
  • You might consider using something like Google's Java library called Guava which contains Immutable collections. You could then call `ImmutableList.of(args...)` which will make an immutable list of the arguments you receive from the command line. Then instead of copying the list between methods simply pass the immutable reference to the rest of the code that needs the list of immutable strings. – lucidquiet Sep 23 '14 at 18:08

2 Answers2

6

The reason you copy array parameters is to avoid a possibility of someone modifying the array once you have validated its elements. This is a very good defensive technique, which protects you from malicious calls in a caller.

However, in this case the caller is JVM itself. If you do not trust JVM to be free of malicious code, you have a much larger problem than something that could be solved by copying an array.

The only exception is when you pass args to some of your functions. In this case, making a copy is a very good idea, in case some method decides to change the content of the args. That's the only case when I would recommend making a copy. If main is the only place where args is used, making a copy is not necessary.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

I can imagine quite a bit, the two most obvious (to me) are:

  • If you modify them but still need to refer to the original values
  • If you use main as a "normal" method, e.g., not just called from the command line

In general, though, it's not super-useful in this case.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302