Friday, April 8, 2011

naming convention for public and private variable?

Is it wrong to use m_varname as public and the same class with _variable as private

From stackoverflow
  • Assuming that you're working with C++, the my answer is NO. It's perfectly reasonable, but you'll should really stick to that convention.

    However, statically typed languages such as C# assume such naming conventions to be somewhat redundant.

    Personally I think it's ugly, but it's not apparent where a variable comes from in C++ as such the sugaring might help.

  • Everyone has his/her own preferences as far as naming conventions are concerned. I'd say more people would agree on not having any public variables in a class.

  • Some concerns:

    • Why do you have public variables?

    • Identifiers starting with _ and __ are reserved for system libraries. In practice this doesn't matter very often, but it's nice to be aware.

    With those things said, there's nothing wrong with creating a naming convention, regardless of how it looks. Just be consistent.

  • The same goes for C++ and for Java: you do not need any hungarian notation nor any prefixes/suffixes. You got keyword "this"!

    class MyClass {
        private:
            int value;
    
        public:
            MyClass(int value) {
                this->value = value;
            }
    }
    

    Of course in this simple example you can (should!) use constructor initialization list ;)

    So, instead using any awkward notations just employ language's possibilities. When you know the name of your member variable - you know that it is perfect. Why would you obfuscate it with "_"?

    As for using the same names for public and private members: this absolutely wrong thinking! Why would one need two things to represent the same in the same class? Make it private, name it perfectly and give getters and setters public.

    Brian Neal : "this" is a pointer in C++.
    Marcin Gil : Right. Will correct!
  • You should not use names that begin with an underscore or contain a double underscore. Those names are reserved for the compiler and implementation. Besides that restriction, you can use any naming convention you and your team likes. Personally, I hate any form of "Hungarian" notation and dislike the m_something notation as well. It really bothers me that if I need to change the type of a variable I need to go update its name everywhere where it occurs. That's a maintenance headache.

0 comments:

Post a Comment