141

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out within a class?

A : 1) public methods 2) private methods 3) public vars 4) private vars

B : 1) public vars 2) private vars 3) public methods 4) private methods

C : 1) public vars 2) public methods 3) private methods 4)private vars

I generally like to put public static vars at the top, but then would a public static method be listed ahead of your constructor, or should the constructor always be listed first? That sort of thing...

I know it's finnicky but I just wondered: what are best practices for this?

PS: no I don't use Cc#. I know. I'm a luddite.

skaffman
  • 398,947
  • 96
  • 818
  • 769
tempname
  • 1,413
  • 2
  • 10
  • 5
  • 15
    There's nothing wrong with not using C#. I've never written a stitch of C# in all my years as a professional developer. Use whatever language is appropriate to the task, and tell anyone who says anything different where they can go stick it! – Ether Nov 19 '09 at 18:45
  • 1
    Possible duplicate of http://stackoverflow.com/questions/150479/order-of-items-in-classes-fields-properties-constructors-methods – Michael Freidgeim Apr 28 '13 at 22:06

10 Answers10

201

In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much. This is a more sensible way to organize code rather than by access modifier.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 13
    I've had good luck also adding: getters/setters last. It helps the classes feel less bulky, to me. – Dean J Nov 27 '09 at 15:12
  • What about constructors? – VitalyB Nov 30 '14 at 20:21
  • 7
    Constructors at the top, right after the member variables. In OOP, execution begins with object instantiation. – Asaph Nov 30 '14 at 21:01
  • @Asaph, do you remember the chapter? – 2xMax Dec 01 '14 at 08:40
  • What if you initialize a field with a function? Does it mean that some functions should be above fields? Should you prefer consistency or story-like readability? – VitalyB Jan 05 '15 at 09:31
  • 13
    Causing the reader to jump around the code too much probably needs to be balanced with forcing the reader to read all the nitty-gritty detail of private methods. The newspaper metaphor is probably misunderstood in that your public methods should represent broadly what your class does, and your private methods supply the details (almost like a footnote that you can refer to if you need to). – Kenny Hung Oct 26 '15 at 15:16
  • 3
    I'm confused. You said: _(constants first, then private members)_. OK. Where do the public members go then? – mfaani Sep 06 '18 at 20:03
  • 2
    @Honey They would go right after the constants and the private members. So that would be in the following order : Constants, private members, public members. – Pierre Gillet Feb 27 '19 at 20:14
  • No C. Martin doesnt strictly say it like that. he says put them at the top, but that may depend on the language. important is to put them where people expect them. Java: at the top (all his examples are in java), C+++ at the end. And he makes no assumption about const, public or private members. he just talks about "instance variables" when he talks about class wide variables in his book. – Welcor Jul 02 '20 at 08:17
91

The best practice is to be consistent.

Personally, I prefer putting public methods first, followed by protected methods, following by private methods. Member data should in general always be private or protected, unless you have a good reason for it not to be so.

My rationale for putting public methods at the top is that it defines the interface for your class, so anyone perusing your header file should be able to see this information immediately.

In general, private and protected members are less important to most people looking at the header file, unless they are considering modifying the internals of the class. Keeping them "out of the way" ensures this information is maintained only on a need to know basis, one of the more important aspects of encapsulation.

LeopardSkinPillBoxHat
  • 28,915
  • 15
  • 75
  • 111
  • LeopardSkikPBH, I totally agree... that makes sense! I guess I have been confused as to whether within that, var or funcs take precedence. Thanks! – tempname Nov 19 '09 at 04:32
  • 16
    I do not agree that the best practice is to be consistent. There are a lot of ways to consistently write unreadable, unmaintable code. – jason Nov 19 '09 at 04:44
  • 11
    @Jason that's like saying it's not best practice to stay on your side of the road because you can still have accidents there. – Rex M Nov 19 '09 at 04:55
  • 1
    @Jason - Maybe I should have been more clear. In this particular, fairly subjective case (ordering of methods) I think the best practice is to be consistent. Everyone will have opinions about the best way to order things, but if you're consistent by nature it should be fairly maintainable. I agree that "be consistent" is not always the best practice for all areas of code, especially when you consider the poor code quality you often have to deal with. – LeopardSkinPillBoxHat Nov 19 '09 at 04:56
  • 4
    @Rex M: No, what I said is not akin to your interpretation at all. My point is that merely being consistent is not a strong argument in this case. For some cases consistency is fine (e.g., placement of braces). But the choices here actually affect the readability of code. Thus, an argument stronger than consistency is needed. – jason Nov 19 '09 at 16:20
26

Personally I like to have public at top, protected and then private. The reason for this is that when somebody cracks open the header he/she sees what he/she can access first, then more details as he/she scrolls down.

One should not have to look at the implementation details of a class in order to use it, then the class design is not done well.

AndersK
  • 35,813
  • 6
  • 60
  • 86
14

This would be my ordering

  1. Static Variables
  2. Static Methods
  3. Public Variables
  4. Protected Variables
  5. Private Variables
  6. Constructors
  7. Public Methods
  8. Protected Methods
  9. Private Methods

I use the following rules:

  • static before anything
  • variables before constructors before methods (i consider constructors to be in the category of methods)
  • public before protected before private

The idea is that you define the object (the data), before the behaviours (methods). Statics need to be separated because they aren't really part of the object, nor it's behaviour.

barkmadley
  • 5,207
  • 1
  • 28
  • 31
  • thank you barkmadley... that's interesting! that you would put 4 and 5 before constructor. I will definitely think about that – tempname Nov 19 '09 at 04:31
  • Like this order although having static methods near the top is interesting. I worked with a developer that put private variables at the bottom, I could see the idea but it didn't feel right – Carlton Apr 27 '18 at 11:36
  • What about finals? where are they in that order - with final and without? – Shai Alon Feb 17 '22 at 13:05
12

I think I have a different philosophy on this than most. I prefer to group related items together. I can't stand having to jump around to work with a class. The code should flow and using a rather artificial ordering based on accessibility (public, private, protected etc. ) or instance versus static or member versus property versus function doesn't help keep a nice flow. So if I nave a public method Method that is implemented by private helper methods HelperMethodA, HelperMethodB etc. then rather than have these method far apart from each other in the file, I will keep them close to each other. Similarly, if i have an instance method that is implemented by a static method, I will group these together too.

So my classes often look like this:

class MyClass {
    public string Method(int a) {
        return HelperMethodA(a) + HelperMethodB(this.SomeStringMember);
    }

    string HelperMethodA(int a) { // returns some string }

    string HelperMethodB(string s) { // returns some string }

    public bool Equals(MyClass other) { return MyClass.Equals(this, other); }

    public static bool Equals(MyClass left, MyClass right) { // return some bool }

    public double SomeCalculation(double x, double y) {
        if(x < 0) throw new ArgumentOutOfRangeException("x");
        return DoSomeCalculation(x, y); 
    }

    const double aConstant;
    const double anotherConstant;
    double DoSomeCalculation(double x, double y) {
        return Math.Pow(aConstant, x) * Math.Sin(y) 
            + this.SomeDoubleMember * anotherConstant;
    }       
}
jason
  • 236,483
  • 35
  • 423
  • 525
  • In my practice this method quickly fails. Usually a class is very coherent and multiple methods will be using the same set of variables. – Seideun May 13 '22 at 17:13
4

I used to care a lot. Over the last several years using modern IDEs pretty much everything is only 1 or 2 keystrokes away, I've let my standards relax substantially. Now, I start with statics, member variables, then constructors after that I don't worry about it much.

In C# I do let Resharper organize things automatically.

ScottS
  • 8,455
  • 3
  • 30
  • 50
  • I agree. My normal mode of navigating the members in a file is to use a tool built into whichever IDE or editor I am using. The actual grouping of the members becomes secondary. However, I agree that members should be grouped to avoid pure random ordering, and I use resharper do the grouping and ordering automatically. – Phillip Ngan Nov 30 '09 at 19:22
2

I generally agree with the public, protected, private order as well as the static data, member data, member functions order.

Though I sometimes group like members (getters & setters) I generally prefer listing members within a group ALPHABETICALLY so that they can be located more easily.

I also like lining up the data/functions vertically. I tab/space over to the right enough so that all names are aligned in the same column.

AlanKley
  • 4,592
  • 8
  • 40
  • 53
1

To each his own, and as Elzo says, modern IDEs have made it easier to find members and their modifiers in an easy way with colored icons in drop-down menus and such.

My take is that it is more important for the programmer to know what the class was designed for, and how it can be expected to behave.

So, if it is a Singleton, I put the semantics (static getInstance() class) first.

If it is a concrete factory, I put the getNew() function and the register / initialize functions first.

... and so on. When I say first, I mean soon after the c'tors and d'tor - since they are the default way of instantiating any class.

The functions that follow are then in:

  1. logical call-order (e.g. initialize(), preProcess(), process(), postProcess() ), or
  2. related functions together (like accessors, utilities, manipulators etc),

depending on if the class was meant primarily to be a data-store with some functions, or function provider with a few data members.

Fox
  • 2,078
  • 17
  • 18
0

Some editors, like Eclipse and its offspring, allow you to reorder in the outline view the the vars and the methods, alphabetically or as in page.

Asaph
  • 159,146
  • 25
  • 197
  • 199
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
0

The sequence of public followed by protected and private is more readable to me, It's better to describe the class logic in comments at top of the header file simply and function call orders to understand what a class dose and algorithms used inside.

I am using Qt c++ for a while and see some new sort of keywords like signal and slot I prefer to keep ordering like above and share my idea with you here.

#ifndef TEMPLATE_H
#define TEMPLATE_H


class ClassName
{
    Q_OBJECT
    Q_PROPERTY(qreal startValue READ startValue WRITE setStartValue)
    Q_ENUMS(MyEnum)

public:

    enum MyEnum {
        Hello = 0x0,
        World = 0x1
    };

    // constructors

    explicit ClassName(QObject *parent = Q_NULLPTR);
    ~ClassName();

    // getter and setters of member variables

    // public functions (normal & virtual) -> orderby logic

public slots:

signals:

protected:

    // protected functions it's rule followed like public functions


private slots:

private:

    // methods

    // members

};

#endif // TEMPLATE_H
saeed
  • 2,477
  • 2
  • 23
  • 40