Naming: Why should named constants be all uppercase in C++/Java?

前端 未结 15 1657
情歌与酒
情歌与酒 2020-12-15 16:13

I know, that for C++ and Java it is a well established naming convention, that constants should be written all uppercase, with underscores to separate words. Like this (Java

相关标签:
15条回答
  • 2020-12-15 16:16

    With uppercase constants long formulas are much easier to read, you don't have to guess which element can vary and which can not. It's of course only a convention, but helpful one.

    0 讨论(0)
  • 2020-12-15 16:19

    When programming, it is important to create code that is understandable by humans. Having naming conventions helps to do this. This is best when looking at code that you didn't write and makes the code more maintainable because it is easy to distinguish from constants and variables.

    0 讨论(0)
  • 2020-12-15 16:21

    If I know something is a constant, I can refer to it multiple times and know it won't change. In other words, I know that:

    Color black = Colors.BLACK;
    foo(black);
    foo(black);
    

    is the same as:

    foo(Colors.BLACK);
    foo(Colors.BLACK);
    

    That can be useful to know sometimes. Personally I prefer the .NET naming convention, which is to use Pascal case for constants (and methods):

    Foo(Colors.Black);
    Foo(Colors.Black);
    

    I'm not a big fan of shouty case... but I do like constants being obviously constants.

    0 讨论(0)
  • 2020-12-15 16:22

    Coding conversions are to improve readability. You don't have to use letters. Java allows $ symbol for example.

    public final static Color $$ = COLOR.WHITE;
    public final static Color $_ = COLOR.BLACK;
    

    You could number your variables too, but that doesn't mean its a good idea. ;)

    0 讨论(0)
  • 2020-12-15 16:24

    I think it is not a technical problem but rather a psychological one. Naming conventions are not for the compiler to process (the computer does not really mind names) but rather for the programmer that is browsing the code to have as much information as possible with as little effort as required.

    Using a different naming convention is clearly telling the reader that what you are reading is something that is FIXED at compile time and you don't need to follow through code to determine where and how the value got there.

    0 讨论(0)
  • 2020-12-15 16:25

    Do not use ALL_CAPS for constants just because constants used to be macros.

    This quote from C++ Core Guidelines sums it all.

    0 讨论(0)
提交回复
热议问题