This is one of the rules from Googles static analyser CodePro AnalytiX:
Summary
Arrays should not be statically initialized by an array initializer.
Description
This audit rule checks for array variables that are initialized (either in the initializer or in an assignment statement) using an array initializer.
Example
The following array declaration would be flagged because of the use of an array initializer:
int[] values = {0, 1, 2};
Now, I can disable it if I don't like it, that's not a problem. But I'm wondering why would this be a problem, and what would be the solution to keep that code from being flagged by the audit rule?
If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The same applies to elements of arrays with static storage duration.
Single Dimensional Array Initialization. The process of assigning values to the array elements is called array initialization. Once an array is declared, its elements must be initialized before they can be used in the program. If they are not properly initialized the program produces unexpected results.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
If you don't initialize an element in an array it works exactly like it would if you weren't initializing a member variable of that specific type: Java will initialize it with the type default value which is 0 for numerical primitive types (int, double, float...), false for booleans and null for objects (String ...
I'd think that is because it is a special syntax that only works when initializing values
.
int[] values = {1,2,3} //legal int[] values2; values2 = {1,2,3} //not legal int [] values3; values3 = new int[]{1,2,3} //legal
The last form values3
is legal wether it is when creating the array or later on. So instead of mixing forms of initializing arrays you'd be better of using the same form always. IMHO that makes for clearer code, following the principle of least surprise.
Strangely though the google code style does not prohibit this form of initialization which is very clear in this example.
It's an interesting question, and this decision is groundless IMHO. (I hope somebody else will answer this thread if there is a legit reason behind this design decision).
Moreover, Google shows how to format those static initializers in their good practice formatting guide https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.8.3.1-array-initializers without saying anything about how bad it is to use those constructs ...
I guess that the person behind that rule just had a tooth against that style of programming :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With