Frage

Ich komme aus einer .NET -Welt und ich bin neu im Schreiben von C ++. Ich frage mich nur, was die bevorzugten Namenskonventionen sind, wenn es darum geht, lokale Variablen und Strukturmitglieder zu benennen.

Zum Beispiel hat der Legacy -Code, den ich geerbt habe, viel davon:

struct MyStruct
{
   TCHAR           szMyChar[STRING_SIZE];
   bool            bMyBool;
   unsigned long   ulMyLong;
   void*           pMyPointer;
   MyObject**      ppMyObjects;
}

Als ich aus einem C# -Hintergrund kam, war ich schockiert, als ich die Variablen mit ungarischer Notation sah (ich konnte nicht aufhören, über das PP -Präfix zu lachen, als ich es zum ersten Mal sah).

Ich würde meine Variablen stattdessen lieber auf diese Weise benennen (obwohl ich nicht sicher bin, ob es eine gute Konvention ist, den ersten Buchstaben zu nutzen. Ich habe andere Wege gesehen (siehe Links unten):

struct MyStruct
{
   TCHAR           MyChar[STRING_SIZE];
   bool            MyBool;
   unsigned long   MyLong;
   void*           MyPointer;
   MyObject**      MyObjects;
}

Meine Frage: Ist dies (der frühere Weg) immer noch ein bevorzugter Weg, Variablen in C ++ zu nennen?

Verweise:

http://geosoft.no/development/cppstyle.html

http://www.syntext.com/books/syntext-cpp-conventions.htm

http://ootips.org/hungarian-notation.html

Vielen Dank!

War es hilfreich?

Lösung

Diese Art von ungarischer Notation ist ziemlich nutzlos und möglicherweise schlechter als nutzlos, wenn Sie die Art von etwas ändern müssen. (Das richtig Art ungarischer Notation ist eine andere Geschichte.)

Ich schlage vor, Sie verwenden alles, was Ihre Gruppe tut. Wenn Sie die einzige Person sind, die an dem Programm arbeitet, nennen Sie sie, was für Sie den größten Sinn für Sie am sinnvollsten ist.

Andere Tipps

The most important thing is to be consistent. If you're working with a legacy code base, name your variables and functions consistently with the naming convention of the legacy code. If you're writing new code that is only interfacing with old code, use your naming convention in the new code, but be consistent with yourself too.

No. The "wrong hungarian notation" - especially the pp for double indirection - made some sense for early C compilers where you could write

int * i = 17;
int j = ***i;

without even a warning from the compiler (and that might even be valid code on the right hardware...).

The "true hungarian notation" (as linked by head Geek) is IMO still a valid option, but not necessarily preferred. A modern C++ application usually has dozens or hundreds of types, for which you won't find suitable prefixes.

I still use it locally in a few cases where I have to mix e.g. integer and float variables that have very similar or even identical names in the problem domain, e.g.

float fXmin, fXmax, fXpeak; // x values of range and where y=max
int   iXmin, iXMax, iXpeak; // respective indices in x axis vector

However, when maintaining legacy code that does follow some conventions consistently (even if loosely), you should stick to the conventions used there - at least in the existing modules / compilation units to be maintained.

My reasoning: The purpose of coding standards is to comply with the principle of least surprise. Using one style consistently is more important than which style you use.

What's to dislike or mock about "ppMyObjects" in this example apart from it being somewhat ugly? I don't have strong opinions either way, but it does communicate useful information at a glance that "MyObjects" does not.

I agree with the other answers here. Either continue using the style that you are given from the handed down for consistency's sake, or come up with a new convention that works for your team. It's important that the team is in agreement, as it's almost guaranteed that you will be changing the same files. Having said that, some things that I found very intuitive in the past:

Class / struct member variables should stand out - I usually prefix them all with m_
Global variables should stand out - usuall prefix with g_
Variables in general should start with lower case
Function names in general should start with upper case
Macros and possibly enums should be all upper case
All names should describe what the function/variable does, and should never describe its type or value.

I'm a hungarian notation person myself, because I find that it lends readability to the code, and I much prefer self-documenting code to comments and lookups.

That said, I think you can make a case for sacrificing your preferred style and some additional maintainability for team unity. I don't buy the argument of consistency for the sake of uniform code readability, especially if your reducing readability for consistency... it just doesn't make sense. Getting along with the people you work with, though, might be worth a bit more confusion on types looking at variables.

Hungarian notation was common among users of the Win32 and MFC APIs. If your predecessors were using that, you can probably best continue using it (even though it sucks). The rest of the C++ world never had this brain-dead convention, so don't use it if you're using something other than those APIs.

Ich denke, Sie werden immer noch feststellen, dass die meisten Geschäfte, die in Visual C ++ mit ungarischer Notation oder zumindest eine verwässerte Version davon programmieren. In unserem Geschäft ist die Hälfte unserer App Legacy C ++ mit einer glänzenden neuen C# -Ebene oben (mit einer verwalteten C ++ - Schicht in der Mitte). Unser C ++ - Code verwendet weiterhin ungarische Notation, aber unser C# -Code verwendet Notation wie Sie. Ich finde es hässlich, aber es ist konsequent.

Ich sage, benutze alles, was dein Team für dein Projekt will. Wenn Sie jedoch an Legacy -Code arbeiten oder sich einem Team anschließen, bleiben Sie bei dem Stil, der für die Konsistenz vorhanden ist.

Es ist alles auf persönliche Präferenz. Ich habe für 2 Unternehmen mit ähnlichen Schemata gearbeitet, bei denen Mitgliedsvars als M_VARName bezeichnet werden. Ich habe bei der Arbeit noch nie eine ungarische Notation gesehen und mag es wirklich nicht, aber es geht wieder auf die Präferenz. Mein allgemeines Gefühl ist, dass IDEs sich darum kümmern sollte, Ihnen zu sagen, welchen Typ es ist, so lange der Name beschreibend genug von dem, was es tut (M_Color, M_Shouldberenemed), dann ist das in Ordnung. Die andere Sache, die ich mag, ist ein Unterschied zwischen Mitgliedsvariablen, lokalem VAR und konstantem Namen. Es ist also leicht zu erkennen, was in einer Funktion passiert und woher die VARs kommen. Mitglied: m_varname const: c_varname lokal: varname

Ich bevorzuge auch Camelcase, in der Tat habe ich Leute gesehen, die Camelcase in C ++ verwendeten. Persönlich Ich benutze keine Präfixe, die für private/geschützte Mitglieder und Schnittstellen erwarten:

class MyClass : public IMyInterface {
public:
    unsigned int PublicMember;
    MyClass() : PublicMember(1), _PrivateMember(0), _ProtectedMember(2) {}
    unsigned int PrivateMember() {
        return _PrivateMember * 1234; // some senseless calculation here
    }
protected:
    unsigned int _ProtectedMember;
private:
    unsigned int _PrivateMember;
};
// ...
MyClass My;
My.PublicMember = 12345678;

Warum ich beschlossen habe, Präfixe für öffentliche Mitglieder wegzulassen:Weil auf öffentliche Mitglieder direkt wie in Strukturen zugegriffen werden können und nicht mit privaten Namen zusammenbrechen. Stattdessen habe ich unter Verwendung von Unterstrichen auch Personen gesehen, die den ersten Unterrichtsbrief für Mitglieder verwenden.

struct IMyInterface {
    virtual void MyVirtualMethod() = 0;
};

Schnittstellen enthält pro Definition nur reine virtuelle Methoden, die später implementiert werden müssen. In den meisten Situationen bevorzuge ich jedoch abstrakte Klassen, aber dies ist eine andere Geschichte.

struct IMyInterfaceAsAbstract abstract {
    virtual void MyVirtualMethod() = 0;
    virtual void MyImplementedMethod() {}
    unsigned int EvenAnPublicMember;
};

Sehen Hohe Integrität C ++ Codierungsstandhandbuch für etwas mehr Inspiration.

Unser Team nutzt Google C ++ Codekonvention:

Dies ist ein Beispiel des variablen Namens:

string table_name;  // OK - uses underscore.
string tablename;   // OK - all lowercase.

string tableName;   // Bad - mixed case.

Wenn Sie Camelcase verwenden, können Sie den ersten Buchstaben für Klassenstrukturen und nicht primitive Typnamen nutzen und den ersten Buchstaben für Datenmitglieder senken. Die Kapitalisierung von Methoden ist tendenziell eine gemischte Tasche. Meine Methoden sind in der Regel Verben und werden bereits von Parens unterschieden, sodass ich keine Methoden nutze.

Persönlich möchte ich keinen Camelcaper -Code lesen und es vorziehen, einen niedrigeren Fall für Daten- und Methodenkennung, Kapital zu treiben und Großbuchstaben für Akronyme zu reservieren, und den seltenen Fall, in dem ich ein Makro verwende (Warnung dies ist ein Makro).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top