简体   繁体   English

我什么时候应该使用变量vs原始值?

[英]When should I use a variable vs a raw value?

When should I define a variable? 我什么时候应该定义一个变量? Would it be faster to just have a raw value inside a if statement vs a variable for one time use? 在if语句中使用原始值与变量一次使用会更快吗? For example, a raw value: 例如,原始值:

if(variable == 503) {
    //run code 
} 

VS this: VS这个:

if(variable == anotherVariable) {
    //run some code
}

I am looking for which one would be faster and more secure (in a if statement and in general). 我正在寻找哪一个更快更安全(在if语句和一般情况下)。

I would say that depends on what the variable represents. 我会说这取决于变量代表什么。 If it is some global constant that will be reused in more than one place then definitely use a variable. 如果它是一个将在多个地方重用的全局常量,那么肯定使用一个变量。 Otherwise if it's a one time use value, there is not need for a variable. 否则,如果它是一次性使用值,则不需要变量。

What I tend to do is to start out with a value. 我倾向于做的是从一个值开始。 Then as soon as I encounter another case where I reuse that same value, then I move it into a global(or the necessary scope) variable. 然后,当我遇到另一个我重用相同值的情况时,我将其移动到全局(或必要范围)变量中。

EDIT: 编辑:

After some discussion in the comments, it is clear that on the long run it is preferable to write out values with descriptive variable names. 在评论中进行了一些讨论之后,很明显从长远来看,最好用可描述的变量名来写出值。

The rule of thumb is to always use descriptive names for variables and values (and possible add comments to them). 经验法则是始终对变量和值使用描述性名称(并可能为它们添加注释)。 However, it is at the discretion of the programmer to determine if there is enough context for a value to exist without a variable name. 但是,程序员可以自行决定是否有足够的上下文来存在没有变量名的值。 Do consider future developers reading your code and don't assume that they will obviously know what you are talking about (an easy mistake to make). 请考虑未来的开发人员阅读您的代码,并且不要认为他们显然会知道您在谈论什么(这是一个容易犯的错误)。

I suggest always using a descriptive name for such values. 我建议总是为这些值使用描述性名称。 In this particular case, what does 503 mean? 在这种特殊情况下,503是什么意思?

I completely agree with the other answers - just try to give another inspiration... I remember when I started to code I was over engaged in micro optimization like which variable will perform better but after all I personally came up with this rules for my coding style explicitly about variables and function names also: 我完全同意其他答案 - 只是尝试给出另一个灵感......我记得当我开始编码时,我已经过度参与微优化,比如变量会表现得更好但毕竟我个人想出了我的编码规则关于变量和函数名称的样式也明确:

  1. Others also have coding styles. 其他人也有编码风格。 Learning from the experienced ones means using theirs experience on the one hand and getting closer to an -so to say- "global" style which leads to better readability among each others code. 从经验丰富的人那里学习意味着一方面使用他们的经验并且更接近 - 或者说 - “全球”风格,这导致彼此代码之间更好的可读性。
  2. Choose names as discriptive as possible. 选择名称尽可能具有描述性。 Not only that it makes your code much more readable and maintable but also this leads to focus on functionality inside of the code structure itself. 它不仅可以使您的代码更具可读性和可维护性,而且还可以将重点放在代码结构本身的功能上。
  3. Stay consistent doesn't mean to be flexible anymore and not to develop your style after new experiences but its a good practice in general. 保持一致并不意味着不再灵活,不要在新体验之后发展你的风格,但这是一般的好习惯。
  4. Let the name tell you the type also. 让名字告诉你类型。
  5. Let the name tell you the scope also. 让名称告诉你范围。

So after this general rules here are some practical examples: 所以这里的一般规则是一些实际的例子:

I just choosed an very abstract example to show the general functionality... 我刚刚选择了一个非常抽象的例子来展示一般功能......

var _outerScope = 'I prefer to mark my variables with the most global scope with a leading underscore';

(function (){

    var innerScope      = 'while this variable has its scope inside of this function its just meant to be used in here'
    if (_outerScope !== innerScope) {
        'everything is a bit more clear';
    }

    var fSetAttrTitle   = function ( $Selector, iSelector ) {         // read as: "function set attribute title" awaits an "jQuery object" and "integer"
      sOriginalTitle = $Selector.attr('title');                       // ra: "string original title" = "jQuery object selectors attribute title"
      $Selector.attr('title', 'this container has id: ' + iSelector); // ra: "jQuery object selectors attribute title" = "this container has id: " plus "integer selector"
      return sOriginalTitle;                                          // ra: "return string original title"
    };

    var isIdSel2inArray = false;                       // this should be self explanatory
    var aSelector       = ['#sel1', '#sel2', '#sel3']; // ra: "array selector" = [...]
    var iSelector       = aSelector.length;            // ra: "integer selector" = length of "array selector" | normally i would use "i" instead of iSelector in this case but for illustration lets stay with it
    while ( iSelector-- )                       // ra: "iterate until iSelector is 0"
    {
      sSelector = aSelector[ iSelector ];              // ra: "string selector" is a piece out of "array selector" with number "integer selector"
      if (sSelector !== '#sel2') {                     // ra: "if string selector is not '#sel2' then array selector is return value of set attribute title"
        aSelector[ iSelector ] = fSetAttrTitle( jQuery( sSelector ), iSelector );
      } else {                                         // ra: "if string selector is '#sel2' then '#sel2' is in array"
        isIdSel2inArray = true;
      }
    }

    if (isIdSel2inArray === true) {
      alert('ra: "if boolean is id sel2 in array is true alert this text"');
    }

}).call(this);

if (typeof innerScope === 'undefined') {
    'Of course I can not use this variable here while it has no underscore '
    + 'its not in the outer scope but the next one has an underscore so it is '
    + 'save to use it here ' + (typeof _outerScope !== 'undefined');
}

hope its a bit inspiring :) 希望它有点鼓舞人心:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM