Is naming variables after their type a bad practice?

前端 未结 11 742
孤独总比滥情好
孤独总比滥情好 2021-02-02 16:00

I\'m programming C++ using the underscore naming style (as opposed to camel case) which is also used by the STL and boost. However, since both types and variables/functions are

11条回答
  •  情深已故
    2021-02-02 16:42

    Giving a variable the same name as its type is almost always a bad idea, because it makes it very difficult to tell what code refers to the type and what code refers to the variable. For example, consider the following class:

    struct position
    {
        void operator()() { }
    };
    
    // later on, somewhere:
    position position;
    

    Now, if we see a line of code that uses:

    position()
    

    we can't readily tell whether that constructs a position object or calls position::operator()(). We have to go back and see whether there is an object named position currently in scope.

    Naming conventions are a very touchy, subjective, and argumentative thing. I would just recommend picking one that distinguishes types from variables in some way. Personally, I choose to capitalize my types and leave my variables as starting with a lowercase letter.

    It doesn't really matter how you distinguish them (your suggestions of using capitalization or a trailing underscore are both common), just so long as your usage is consistent.

提交回复
热议问题