Zack Teater Zack Teater - 3 months ago 9
Java Question

Why not use static array of Strings?

Came across this coding standard from Oracle:


Do not use a static array of strings.


What is the reason for this recommendation?

Answer

Since no answers currently cover this, I feel it's due to people using String as a replacement (most likely unintentionally) for enumeration.

It could be targetting common design flaws at the time this was written

For all we know, this article could be targetting the Java 4- code base. Not saying this was written during Java 4, but that most production code at the time was written in Java 4. The lack of autoboxing pitfalls (which are quite common) and no mentions of generics (raw types) lead me to believe this.

Why would Oracle enforce such a cryptic principle?

I don't believe it has to do with global state, since I'm sure singletons would have been mentioned (being the pinnicle of global state). I doubt concurrency is the issue, since the article does not mention anything else about sharing data across threads, or even using multiple threads. You would assume they would have mentioned SOMETHING about the thread environment.

Misusing String for type enumeration purposes was common back in the day, so I'm sure this statement (if related to what I think it is) was a lot easier to understand back then. The other answers seem to be suggesting the statement was just as confusing back then as it is now. I'm pretty sure someone would have questioned it when this article had more traffic.

My Answer

With that said, here's the reasoning behind my thoughts:

Beginners today are still using String for type information. With the lack of enumeration, I could see how a developer may be tempted to do something along the lines of:

class Demo {
    static String MAGE = "MAGE";
    static String ARCHER = "ARCHER";

    static String[] fighterTypes = {
        MAGE, ARCHER;
    };
}

Using the array for easy looping (as one would do with Enum.values()).

Although I can't promise this is the correct answer, it seems to be the only answer that does not depend on the use of modifiers that weren't mentioned in the statement, and this kind of String misuse was extremely common back in the day.

Yes, the example above does not use proper constants (lacks the final). But although constants should be preferred, they are not required to benefit from this design (being able to use String for type information) nor does the design require it to work . Since people may not have always used constants for this, they could have left out the final or "array of constants" for this purpose.