I've seen this de facto standard in many places in many languages, but I've never understood it - why put your private fields and methods at the top of a class declaration? Metaphorically it seems like private things should be located at the bottom (hidden) and everything public should be at the top, so that when you read through the class top to bottom you first see the public interface then the inner workings.
What is the reasoning behind this?
EDIT: Just to clarify, I don't mean the practice of declaring all members at the top of the class, but of putting private members/methods at the top of a class declaration, before anything public.
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.
Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is "Minimize ripple effects by keeping secrets." When a field is private , the caller cannot usually get inappropriate direct access to the field.
Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.
In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.
It stems from the days when you had to declare everything - that includes functions as well as variables - before you could use them.
The internal (private) variables and functions went at the top of the file and the external (public) functions went at the bottom of the file. This meant that the public functions could reference the internal functions. If you had recursion you would have to forward reference the function by declaring it's profile.
When languages allowed the code to span several files you had to put public function and variable declarations into header files so that they could be included in the other files in the project - or indeed other projects.
It probably comes from the days of C, when all variables had to be defined at the top, as part of the initialisation. Also, the default access specifier is private
, so it can save you a superfluous private:
later on in your class definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With