Is naming variables after their type a bad practice?

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

    Personally, I capitalise my class names.

    I disagree with, "it is unwise to choose names that differ only by capitalization", in this specific case. It's unwise to choose names which are confusingly similar. PoSItIoN and PoSiTIoN are confusingly similar. Position and position are not. Just make sure that when you search the code, you know and can control whether you're doing so case-sensitive or insensitive.

    In cases where I have a function that only uses one variable of a particular type, then I might well name it after the type, since in English if something was, "the only position we're talking about", we'd refer to it as, "the position". Hence the variable name could reasonably be position.

    Failing that, in your examples I might go with:

    position pos;  // pretty sure people will realise I don't mean "positron".
    
    mouse_over(entity target) // Returns true if the mouse is over the entity
    
    manager &fmanager; // A reference to the framework's manager
    
    devices::audio audio; // The audio subsystem
    audio self; // "this" audio subsystem
    audio audio_out; // The audio subsystem I'm configured to use for output
    

    The last example is supposed to indicate that these problems might be solved by namespaces - outside the namespace in which audio is defined, you can safely refer to it as audio. Inside that namespace, functions operating on the audio subsystem frequently either are parts of the audio class interface which just happen to be free functions (in which case use conventions like self, other, lhs, rhs), or else are some kind of layered device or system which have an audio subsystem as a dependency (in which case, dependency for what purpose?).

    entity and manager are terrible names for classes, by the way, since neither of them tells you anything about what the class represents. Every discrete thing is an "entity", and while not everything manages something else, "manage" is hopelessly vague.

提交回复
热议问题