How do I give a short, unambiguous name to a variable?

Source: Internet
Author: User

Transferred from: http://kb.cnblogs.com/page/548394/

English Original: Long Names is long

Translation/giraffe

One of the smartest rules Google does is to strictly enforce code review. Each change will go through two forms of review before it goes live. First, people on the team perform regular review to make sure that the code completes the functionality it should do.

The next step is to review the readability level. As the name implies, it is to ensure that the code is readable: is it conducive to understanding and maintenance? Does it conform to some of the conventions of the programming language? Do you have good documentation?

Dart has started using Google internally, so I was fortunate to be involved in the n-th type of code review. As the designer of the language, this is a fascinating work. I can see directly how people use Dart, which is helpful for the further development of language. At the same time as reivew, I was able to clearly understand the more common mistakes and the most used features, and I was like a human scholar who recorded the lives of local residents.

Of course, the above is not about the gist of this article, this is not an article about dart. The main article is to discuss some of the maddening code I've seen: the variable naming of these codes is really too long ...

Yes, the name of the variable can be very short. Back when the external identifiers in the C language only need to be differentiated by the first six characters, the automatic completion function has not yet been invented, and the long naming brings many problems every time the keyboard is as hard as the snow uphill. Fortunately, the world we live in now is so beautiful that keyboard manipulation has become so simple.

But we now seem to be on the other extreme, we shouldn't be Hemingway, but we don't have to be Tennessee Williams. Using an extra-long name in your code can affect the clarity of your code. Also, long variable names can cause line breaks, which can affect the structure of the code and are not easy to read.

    • Long class names can make it difficult for developers to declare variables of that type.
    • A long method of naming makes it difficult to understand.
    • Long variable naming is not conducive to code reuse, resulting in too long chain of methods.

I've seen more than 60 characters in a variable named, and you can even write a poem. Don't panic, let's take a look at how to solve this problem.

Choose a good name

The name has two goals:

    • Clarity: You need to know what the naming is about
    • Precise: You need to know what the naming is not

When a name completes the above two targets, the remaining characters are superfluous. Here are some of the naming principles I developed at the time of development:

There is no need to include words that represent variables or parameter types in naming

If you use a static type language such as Java, developers usually know the type of the variable. Because the implementation of the method is generally short, even if you are looking at a local variable that requires inference to know the type, or if the static parser such as code review is not available, we can know the type of the variable by looking at a few more lines of code.

Therefore, it is superfluous to add the type description to the variable name. We should abandon the Hungarian nomenclature, as follows:

Bad: string Namestring;dockablemodelesswindow dockablemodelesswindow;//Improved: String Name;dockablemodelesswindow Window

Especially for collections, it is best to use the plural form of nouns to describe their contents, rather than using the singular form of nouns. If the developer cares more about what is stored in the collection, then the variable naming should reflect that.

a bad:list<datetime> holidaydatelist; Map<employee, role> employeerolehashmap;//improved:list<datetime> holidays; Map<employee, role> employeeroles;

This also applies to the naming of the method. The method name does not need to describe its parameters and the type of the parameter--the parameter list already illustrates these.

Bad: Mergetablecells (list<tablecell> cells) sorteventsusingcomparator (list<event> events,    Comparator<event> Comparator)//Improved: Merge (list<tablecell> cells) sort (list<event> events, Comparator<event> Comparator)

  Omit words that are not used to disambiguate in naming

Some developers tend to plug all the information they know about the variable into the naming. Remember that naming is just an identifier: it just tells you where the variable is defined. is not used to tell readers all the details they want to know about this object. This is the definition of what should be done. Naming just lets you find the definition of it.

When I see an recentlyUpdatedAnnualSalesBid identifier called (the most recently updated annual sales Bid), I ask:

    • Is there a full year sales bid that is not recently updated?
    • Are there any recent annual sales bids that have not been updated?
    • Is there a recently updated non-annual sales bid?
    • Is there a recently updated annual non-sales bid?
    • Is there a recently updated all-year sale of non-bidding stuff?

The answer to any of the above questions is "No", which means that useless words are introduced into the naming.

Bad: finalbattlemostdangerousbossmonster;weaklingfirstencountermonster;//improvement: boss;firstmonster;

Of course, you might think it's over. For example, simplifying the identifiers of the first example bid, would be a bit confusing. But you can be confident to do so, if in the later development you feel that the naming will cause conflict or ambiguity, you can add some modifiers to refine it. Conversely, if you take a long name from the beginning, you can't come back and simplify it later.

Omit a word in a name that can be obtained from the context

I can use "I" in the article because the reader knows it's a blog by Bob Nystrom. My stupid face hangs there, and I don't have to keep saying my name. The same is true for writing code, where the variables in the methods/properties and methods in a class are present in the context and do not need to be duplicated.

Bad:class Annualholidaysale {  int _annualsalerebate;  void Promoteholidaysale () {...}} Better:class Annualholidaysale {  int _rebate;  void promote () {...}}

In fact, the more hierarchical a named nesting, the more relevant the context it has, and the shorter it is. In other words, the smaller the scope of a variable, the shorter the name.

Omit words without any meaning in the name

I often see the naming of words that contain no meaning in many game development, and some developers like to add words that look a bit serious in their names. I guess they thought it would make their code seem important, or that they might feel more important.

In fact, there are some words that have no practical meaning, just some cliché. For example: data, state, amount, value, manager, engine, object, entity, and instance.

A good name can draw a picture in the reader's mind. Naming a variable "manager" does not convey any information to the reader about what the variable is doing. Is it used for performance evaluation? Does it manage a raise?

In naming, you can ask yourself, do you want to remove the word meaning? If it is, then be decisive to remove it ~ ~

Practical examples--waffles

In order to let you know how the above naming principles are applied in practice, there is a counter-example of all the above principles. This example is as heartbreaking as the piece of code I actually review.

Delicious Belgian Waffle class Deliciousbelgianwaffleobject {  void garnishdeliciousbelgianwafflewithstrawberrylist (      List<strawberry> strawberrylist) {...}}

First, with the argument list we know that the method is used to process a list of strawberry, so you can remove it from the method name:

Class Deliciousbelgianwaffleobject {    void Garnishdeliciousbelgianwaffle (        list<strawberry> Strawberries) {...}}

Unless the program also contains delicious Belgian waffles or other national waffles, we can remove these useless adjectives:

Class Waffleobject {  void Garnishwaffle (list<strawberry> strawberries) {...}}

Method is included in WaffleObject the class, so there is no need for a waffle description in the method name:

Class Waffleobject {  void garnish (list<strawberry> strawberries) {...}}

Obviously it is an object, anything is an object, this is the legendary "object-oriented" meaning, so the naming does not have to Object include:

Class Waffle {  void garnish (list<strawberry> strawberries) {...}}

Well, it looks much better.

The above is a fairly concise naming principle that I have summed up. Some people may find it unnecessary to expend too much effort on naming, but I think naming is one of the most basic tasks in the development process.

———————————————— – I am the dividing line of the Moe ————————————————

The name of the sensory variable or method is seemingly simple and difficult in practice, especially for a concise, readable naming. Oneself also often with what data , xxxlist to name, the author said quite right, the former meaningless, the latter is a bit wordy. However, for the variable of the collection type, it is easy to confuse the noun plural name. For example, for the Apple class, there may be variables for list and map two collection types. I think the variables of list type can be named by plural nouns, and the variables of map type can be named by Valuebykey format, which is easier to distinguish.

How do I give a short, unambiguous name to a variable?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.