class-design

Why put private fields and methods at the top of class?


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?

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.


Solution

  • 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 its 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.