我应该使用常量而不是字符串,即使字符串只被使用一次吗? [英] Should I use constants instead of strings even if the strings are only ever used once?

查看:152
本文介绍了我应该使用常量而不是字符串,即使字符串只被使用一次吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码解析一些晦涩的文本文件。

此文本文件可以包含各种关键字。在某些时候,有一些冗长的部分,如下所示:

  void loadKeywords(){
tmpString = getValueForKeyword (宽度);
if(tmpString!= NULL){
/ * do something for several lines * /
}

tmpString = getValueForKeyword(height);
if(tmpString!= NULL){
/ *为几行执行某些操作* /
}

/ *等等十几次* /
}

这些字符串heightwidth只用于这段代码。仍然,我想知道是否最好使用定义的字符串常量如

  #define KEYWORD_WIDTH(width)$ b 



$ b

$ b


解决方案

开始时不提取常量。然后,以后,你的编辑可能可以为你做这个,如果你需要它的某种原因后来。



虽然如果你认为它会提高代码的可读性,那么你可以使用常量。如果您可以通过这样做添加更多语义:

  BROWSER_WIDTH =width
CONNECTION_POOL_MAX_SIZE =max_size


I have a piece of code that parses some obscure text file.
This text file can contain various keywords. At some point, there is some lengthy part that reads like this:

void loadKeywords() {
    tmpString = getValueForKeyword("width");
    if (tmpString != NULL) {
        /* do something for several lines */
    }

    tmpString = getValueForKeyword("height");
    if (tmpString != NULL) {
        /* do something for several lines */
    }

    /* and so on a few dozen times */
}

These strings "height" and "width" are only ever used in this very piece of code. Still, I am wondering if it would be better to use defined string constants like

#define KEYWORD_WIDTH ("width")

instead of those literals in the code above.

What would you do?

解决方案

Start without extracting constants. Then later on, your editor can probably do this for you if you need it for some reason later on.

Though if you think it will improve the readability for your code, then you can use constants. Do this if you can add more semantic meaning by doing so:

BROWSER_WIDTH = "width"
CONNECTION_POOL_MAX_SIZE = "max_size"

这篇关于我应该使用常量而不是字符串,即使字符串只被使用一次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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