Why would var be a bad thing?

前端 未结 17 1934
误落风尘
误落风尘 2020-12-04 17:21

I\'ve been chatting with my colleagues the other day and heard that their coding standard explicitly forbids them to use the var keyword in C#. They had no idea

17条回答
  •  旧时难觅i
    2020-12-04 18:18

    Understanding 'var' in Plain English

    I'm going to show you that using AND not using 'var' is about communicating clearly.

    I'm going to show examples of cases where using 'var' makes the code easier to read, and other examples when using var makes things hard to understand.

    More than that you'll see that how clear 'var' is depends a lot on what you name everything else in your code.

    Take this example:

    Jake said hello to Bill. He didn't like him so he turned and went the other way.

    Who went the other way? Jake or Bill? In this case "Jake" and "Bill" are like the type name. And "He" and "him" are like the var keyword. In this case it might help to be more specific. The following for example is much clearer.

    Jake said hello to Bill. Jake didn't like Bill so he turned and went the other way.

    In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.

    Bill likes books, so Bill went to the library and Bill took out a book that Bill has always liked.

    In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, this is the equivalent of using the var keyword.

    Bill likes books, so he went to the library and took out a book that he has always liked.

    Those analogies cover the gist, but they don't tell the whole story. See in those examples there was only one way to refer to the person. Either with their name, for example Bill, or by a more general way, like "he" and "him". But we're only working with one word.

    In the case of the code you have two "words", the type and the variable name.

    Person p = GetPerson();
    

    The question now becomes is there enough information there for you to easily determine what p is? Would you still know what people is in this scenario:

    var p = GetPerson();
    

    How about this one:

    var p = Get();
    

    How about this one:

    var person = Get();
    

    Or this one:

    var t = GetPerson();
    

    Or this one:

    var u = Person.Get();
    

    Whether the keyword var works in a given scenario depends a lot on the context of the code, like what the names of the variables, classes, and methods are, as well as the complexity of the code.

    Personally I like to use the var keyword it's more comprehensive to me. But I also tend to name my variables after the type so I'm not really losing any information.

    That said sometimes I make exceptions, such is the nature of anything complex, and software is nothing if not complicated.

提交回复
热议问题