When developping a project I follow the OOP principles and break my code into classes and most of the time I go for one file = one class.

Now I dont know how to organize my code into the class and even into my own functions/methods I'm still looking for ways to improve the readability.

I think the general consensus is :

  1. attributes
  2. Constructors
  3. Getters/Setters
  4. Methods

But once I get to the method part I dont know if I should organize by public/protected/private members, or if I should put related methods together ?

IE :

Methods for database operation, then methods for user input validation, then methods for event handling.

What If I put some code in a method, and then I call this method in a lots of my others class method ?

public void f1(){
    // other stuff

public void f2(){
    // other stuff

Where do I put 'mymethod' definition for an optimal readibility ? Should I declare it before f1 and f2 or after both ?

closed as primarily opinion-based by amon, gnat, John Wu, Robert Harvey, 17 of 26 Mar 9 '18 at 19:05

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.


Quit procrastinating. Don't waste your time with this stuff.

Modern tools facilitate jumping around to parts of the code so effectively you could order a classes functions and properties almost completely randomly and most folks wouldn't even notice.

There are tools that can do it for you if it's really that important to you. Find a decent tool that works with your development language and just use one of the defaults. Done.

  • Hundred times this. Order of stuff within class is mostly irrelevant when using modern IDE. The readability and understandability are in different areas. – Euphoric Mar 9 '18 at 18:56

If you're asking this for your own, personal projects, then @whatsisname nailed it. If you're joining a team, take a look at some of the existing code, and use their style.

  • Agreed! Consistency is valuable when working on a team. I'm not opposed to adopting an opinionated styleguide. For example, AirBnB's JavaScript styleguide specifies a very specific structure for React component classes. – Brad Buchanan Mar 9 '18 at 18:54

re: public/protected/private

A good argument is to put the public methods first, cause they are the API of your class and therefore "more important". Let users see them first, to get a feel for what the class can do for them. For example, if they think they want to use this class to talk to a database, they'd expect to seem something like a connect() and a query() method.

Following this argument, private methods are "less important" and can be at the bottom of your class.

Not the answer you're looking for? Browse other questions tagged or ask your own question.