Is naming variables after their type a bad practice?

前端 未结 11 719
孤独总比滥情好
孤独总比滥情好 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:46

    The biggest problem with this naming convention imo is that it's unclear to the programmer whether an expression refers to a type or an object. A way to eliminate such ambiguity is by wrapping your code inside a namespace (as it should) and using explicit qualifications, even on internal usage:

    namespace my_ns {
    
    struct audio { ... };
    struct string { ... };
    
    // Internal function whose logic doesn't require explicit qualifications.
    void do_something()
    {
        // Use explicit qualification nevertheless.
        my_ns::audio audio;
        audio.play("impenetrable.sd2"); // okay
    
        my_ns::string string;
        string.size();          // okay
        // string{}.size();     // oof, tryna re-instantiate object? compilation error
        my_ns::string{}.size(); // okay, size of just created temporary string
    }
    
    }
    

    This is much like the way you use standard types such as std::string. Since all user-defined types will be qualified with their namespace, there'll be no ambiguity between types and objects. The downside of this is, of course, more verbosity:

    namespace my_ns {
    
    struct audio {
        // Using explicit qualification; pretty verbose.
        void play(my_ns::string a1, my_ns::string a2, my_ns::string a3);
    
        // Without explicit qualification; saves 21 characters.
        void play(string a1, string a2, string a3);
    };
    
    }
    

提交回复
热议问题