硬编码文字是否可以接受? [英] Is hard-coding literals ever acceptable?

查看:115
本文介绍了硬编码文字是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用的代码库中充斥着硬编码的值.

The code base I'm currently working on is littered with hard-coded values.

我将所有硬编码值视为一种代码气味,并尝试在可能的情况下消除它们……但是我不确定某些情况.

I view all hard coded values as a code smell and I try to eliminate them where possible...however there are some cases that I am unsure about.

有两个我能想到的例子,使我想知道最佳实践是什么:

Here are two examples that I can think of that make me wonder what the best practice is:

1. MyTextBox.Text = someCondition ? "Yes" : "No"
2. double myPercentage = myValue / 100;

在第一种情况下,最好的做法是创建一个类,使我可以执行MyHelper.Yes和MyHelper.No或在配置文件中进行类似操作(尽管它不太可能更改,并且谁知道(如果可能的话,其用法会区分大小写).

In the first case, is the best thing to do to create a class that allows me to do MyHelper.Yes and MyHelper.No or perhaps something similar in a config file (though it isn't likely to change and who knows if there might ever be a case where its usage would be case sensitive).

在第二种情况下,除非数学定律发生变化,否则找到除以100的百分比不太可能会改变...但是我仍然想知道是否有更好的方法.

In the second case, finding a percentage by dividing by 100 isn't likely to ever change unless the laws of mathematics change...but I still wonder if there is a better way.

有人可以建议一种适当的方式来处理这种硬编码吗?有人能想到硬编码是可以接受的做法吗?

Can anyone suggest an appropriate way to deal with this sort of hard coding? And can anyone think of any places where hard coding is an acceptable practice?

推荐答案

还有谁能想到可以接受硬编码的任何地方?

  • 小应用
  • 单人项目
  • 扔掉
  • 短期生活项目
    • Small apps
    • Single man projects
    • Throw aways
    • Short living projects
    • 简而言之,是其他人无法维护的.

      For short anything that won't be maintained by others.

      Gee,我刚刚意识到过去作为维护人员的编码员对我有多大伤害:)

      这篇关于硬编码文字是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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