Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: ordering of public/protected/private within the class definition?

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.

like image 821
tempname Avatar asked Nov 19 '09 04:11

tempname


People also ask

What is the order in which the public private and protected instance fields should be declared in a class?

static before anything. public before protected before private.

How do you order methods in class?

Member variables at the top of the class, then constructors, then all other methods. And you order the methods to be close together with how they are used within the class (rather than arbitrarily putting all public then private then protected).

What is public/private and protected as together called?

The keywords public, private, and protected are called access specifiers.

What is the difference between the public and private parts of a class?

Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed.


1 Answers

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.

like image 179
Asaph Avatar answered Oct 04 '22 00:10

Asaph