命名:为什么命名常量在C ++ / Java中都是大写的? [英] Naming: Why should named constants be all uppercase in C++/Java?

查看:849
本文介绍了命名:为什么命名常量在C ++ / Java中都是大写的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,对于C ++和Java,它是一个完善的命名约定,常量应该全部大写,用下划线分隔单词。像这样(Java示例):

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-example):

public final static Color BACKGROUND_COLOR = Color.WHITE;
public final static Color TEXT_COLOR = Color.BLACK;

这个命名约定很容易理解和遵循,但我问自己,为什么选择这个命名约定对于变量的正常命名约定:

This naming convention is easy to understand and to follow, but I ask myself, why choose this naming convention over the normal naming-convention for variables:

public final static Color backgroundColor = COLOR.WHITE;
public final static Color textColor = COLOR.BLACK;

Theres似乎不需要改变常量的外观。如果我们要为它们分配一个值,编译器会防止这一点。事实上,它会出现问题,如果稍后将常量将更改为一个合适的变量(因为颜色可以配置为实例)。

Theres seems to be no need to change the look of constants. If we want to assign a value to them, the compiler will prevent this anyways. Actually it makes problems, if later the constant will be changed into a proper variable (because the colors get configurable for instance).

那么最终的原因是写命名常量全部大写?历史原因?

So what's the ultimate reason to write named constants all uppercase? Historical reasons?

推荐答案

我认为这不是一个技术问题,而是一个心理问题。命名约定不是为了编译器处理(计算机并不真正关心名字),而是浏览代码的程序员尽可能少的努力尽可能多的信息。

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.

这篇关于命名:为什么命名常量在C ++ / Java中都是大写的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆