Java “ANSI constants”

人走茶凉 提交于 2019-12-08 14:36:15

问题


I hit this little tidbit while browsing the Java Code Conventions:

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

(From here.)

What are these "ANSI constants" this document speaks of? And how do they make debugging harder?

The text makes it sound as if there is a dichotomy between "variables declared class constants" (which I interpret as ordinary static final variables) and these "ANSI constants", but I'm not aware of any way to declare constants in Java other than to make them static final variables.


回答1:


They are most likely referring to ANSI C constants, defined as follows

In ANSI C constants can be defined two ways: through the #define statement and through use of the const modifier. For example, the following two statement, are equivalent:

#define LENGTH 10       /* Length of the square in inches */

const int length = 10;  /* Length of the square in inches */

Now there are obviously no C constants in Java, because Java is not C :-) (that's not the strangest part of the official coding conventions, but I digress).

So why did they write ANSI constants? This is most likely just a convenient way of referring to final primitives and immutable objects. Remember that in C the fields of a const struct can't be updated after initialization, and there's no corresponding Java term for such "constant" (final doesn't capture the notion of immutability very well).




回答2:


The only references on the internet on what are ANSI constants are in forums where people who have read the naming conventions ask the same question. It seems that the term was invented by the person who wrote the document and you would have to ask them what they meant.

ANSI is a national standards body in the USA, known for example for the ASCII character set standard and the ANSI C language standard. ANSI is also what Microsoft Windows calls the regional ASCII-based default character encoding. It's possible that the author was referring to string literals.




回答3:


I would expect it has something to do with static initializers or non-compile time constants, but I really dont know (I was googling for that term in the code conventions and this brought me here :)

public class TestClass
{
  final static Object ANSI_CONSTANT;
  static { ANSI_CONSTANT = new Object();
}


来源:https://stackoverflow.com/questions/19174748/java-ansi-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!