What is the point of declaring variables at the end of the class?
I have seen several examples on MSDN that are used to declare internal fields at the end of a class. What's the point?
I find this a little awkward because every time Visual Studio adds a method, it adds it to the end of the class, so it needs to be moved every time ...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
a source to share
In C ++, it makes sense to place the public interface of a class on top so that any user of the class can open your header file and quickly see what's available. Essentially, protected and private members are placed at the bottom.
In C # and Java, where interface and implementation are completely intertwined, people probably won't open your class's source code to see what's available. Instead, they will rely on code completion or generated documentation. In this case, the ordering of the members of the class does not matter.
a source to share
If it is obvious that the variable has been declared and the code is as an example, then perhaps this will cause the bit to be demonstrated faster - that's all I can think of.
Add-ons like ReSharper will allow you to standardize and automatically apply this layout with a single keystroke press, by the way, if that's what you want.
a source to share
Many programmers gravitate towards self-documenting code that helps clients understand this. In a C ++ class declaration, they will go from the most important (that is, what is probably the most frequently checked) to the least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Based on this, if you are using Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same goes for protected and private slots. There is no particular reason why I prefer signals over slots; perhaps because the signals are always public, but I think their ordering will depend on the situation, anyway, I'll keep it consistent.
Another bit I like is to use access specifiers to visually separate behavior from data (following order of importance, behavior first, last data, because behavior is of the highest interest to the class designer):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule in mind helps prevent visual scattering of class components (we all know how some legacy classes look over time when variables and functions are mixed, not?).
a source to share