硬编码的STRINGS可以接受吗? [英] Are hard-coded STRINGS ever acceptable?
问题描述
类似于可以接受硬编码文字吗?,但是我我在这里特别想到魔术弦".
Similar to Is hard-coding literals ever acceptable?, but I'm specifically thinking of "magic strings" here.
在一个大型项目中,我们有一个配置选项表,如下所示:
On a large project, we have a table of configuration options like these:
Name Value
---- -----
FOO_ENABLED Y
BAR_ENABLED N
...
(数百个).
通常的做法是调用通用函数来测试如下所示的选项:
The common practice is to call a generic function to test an option like this:
if (config_options.value('FOO_ENABLED') == 'Y') ...
(当然,在系统代码中的很多地方都可能需要检查相同的选项.)
(Of course, this same option may need to be checked in many places in the system code.)
在添加新选项时,我正在考虑添加一个函数来隐藏魔术字符串",如下所示:
When adding a new option, I was considering adding a function to hide the "magic string" like this:
if (config_options.foo_enabled()) ...
但是,同事们认为我过分了,并反对这样做,而是更喜欢硬编码,因为:
However, colleagues thought I'd gone overboard and objected to doing this, preferring the hard-coding because:
- 这就是我们通常要做的
- 它使调试代码时更容易看到发生了什么
麻烦的是,我明白他们的意思了!实际上,我们绝不会出于任何原因对选项进行重命名,因此我能想到的函数的唯一优势是,编译器会捕获任何类似fo_enabled()的错字,但不会捕获到"FO_ENABLED".
The trouble is, I can see their point! Realistically, we are never going to rename the options for any reason, so about the only advantage I can think of for my function is that the compiler would catch any typo like fo_enabled(), but not 'FO_ENABLED'.
您怎么看?我是否还错过了其他优点/缺点?
What do you think? Have I missed any other advantages/disadvantages?
推荐答案
if (config_options.isTrue('FOO_ENABLED')) {...
}
将硬编码的Y检查限制在一个地方,即使这意味着为Map编写包装类.
Restrict your hard coded Y check to one place, even if it means writing a wrapper class for your Map.
if (config_options.isFooEnabled()) {...
}
在您拥有100个配置选项和100个方法之前,可能看起来还不错(因此在这里,您可以在决定实现之前对未来应用程序的增长和需求做出判断).否则,最好为参数名称使用一类静态字符串.
Might seem okay until you have 100 configuration options and 100 methods (so here you can make a judgement about future application growth and needs before deciding on your implementation). Otherwise it is better to have a class of static strings for parameter names.
if (config_options.isTrue(ConfigKeys.FOO_ENABLED)) {...
}
这篇关于硬编码的STRINGS可以接受吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!