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.
The best practice is to be consistent.
Personally, I prefer putting
public
methods first, followed byprotected
methods, following byprivate
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
andprotected
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.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.
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 methodsHelperMethodA
,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:
This would be my ordering
I use the following rules:
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.