Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

If I had this program:

public class heartPrint {  
   public static void drawHeart() {
      System.out.println(" _  _");
      System.out.println("/ \\/ \\");
      System.out.println("\\    /");
      System.out.println(" \\  /");
      System.out.println("  \\/");
      System.out.println();
  }

   public static void main(String[] args) {

      int i = 0;

      for (i = 0; i < 10; i++) {
        drawHeart();
      }
   }
}

I'm curious whether or not I should have the main method at the top of the other methods or at the bottom. Our prof puts it at the top, but I don't like conceptually that I always think of code reading top to bottom, and in this case it reads down, up, down, up, down, up, etc. as the method call is referencing the methods below it.

Is it "better" (I realize both work) to do it one way?

share|improve this question
apparently it compiles both ways. – Kevin Nov 8 '11 at 0:50
Off-topic. But neither is "better". – Oli Charlesworth Nov 8 '11 at 0:50
Sounds like a bike shed argument to me. Who cares? Use an IDE that can show you all the methods at a glance. – duffymo Nov 8 '11 at 0:54
2  
I compiled it and fell in love at first millis. – jalopaba Nov 8 '11 at 0:56
2  
Alphabetically is just as arbitrary. – Loki Astari Nov 8 '11 at 2:55
show 5 more comments

migrated from stackoverflow.com Nov 8 '11 at 0:53

closed as not constructive by Aaronaught, Steve Evers, ChrisF Nov 8 '11 at 14:17

As it currently stands, this question is not a good fit for our Q&A; format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

11 Answers

Following the PLA (Principle of Least Astonishment), since it is "unusual" for a class to have a main() method (not many classes define them), it makes sense to put it at the top of the class.

All arguments about code style and code formatting should be made primarily from the standpoint of readability. Many developers will argue that methods ought to be designed in order of dependence–in other words, a method that calls another method should always be defined after the one it calls–as well as a million other things.

To understand if these are good conventions or not, I always ask myself: does it make the code more readable? If I encounter a bunch of packages containing code I've never seen before, what are the styles and conventions that will help me figure things out the quickest?

I find that the biggest help for well-designed classes is to list things in the following order:

  • main method
  • public enums
  • public constants
  • private constants
  • constructors
  • public methods that implement interfaces (from most to least visible, this generally means most general to most specific)
  • static methods
  • inner classes
  • static inner classes

Of course you could argue with specific aspects of this ordering, but it generally follows the principle and at some point it matters more than one is consistent across the entire code base than the particulars.

The main() method, however, I feel is an exception. That one should be placed at the top because it is used so infrequently that it should be front and center for the reader when it does exist so they don't miss its presence. Simply being consistent in putting it at the bottom in the case of a main() method doesn't make sense because wherever it appears has the capacity to "consistently" surprise the reader.

share|improve this answer

"Uncle Bob" Martin in his book Clean Code advocates putting methods in a top-down ordering like you suggest. With this, I agree with him because I like to see what's going on before I see the details on how.

I do this as a rule as long as the language permits it.

share|improve this answer

This is a convention inherited from C. C functions needed to be defined before they are used, meaning either the code or a definition had to appear in the source code before the function was called. In order to avoid cluttering the source code with spurious and error prone function definitions, programmers coded "ass backwards" with the trivial used once functions at the top of the file followed by the functions that called them and eventually, at, the end of the source file the "main" function.

There is no reason to do this in Java, and, except for the special case of a "test" method which allows you to invoke a tests in "main" from the command line, but, the main() function is not otherwise used.

I like to code in the order the methods are likely to be invoked. I find this is by far the most readable convention.

share|improve this answer

main() is typically at the bottom because most classes don't have one, or if they do it's an ad-hoc testing appendage. The important bits of a class are the members and methods. main() is just something you use to parse arguments and fire off the interesting stuff.

In your example the issue is that you've written a trivial static method class that doesn't really do anything... in a non-trivial application the amount of non-main code (heh) will (should?) completely outweigh your static code.

share|improve this answer

The general convention is to define methods before calling them. This results in methods with no dependencies being at the top, with higher-level methods further down the file. In this way, main is always at the bottom.

The ordering of methods doesn't cause compile errors like it might in C, but the convention remains, and it's what most people are expecting.

share|improve this answer
Why would the order of method definitions have any impact on their size or complexity? – Aaronaught Nov 8 '11 at 3:23
Size and complexity was misleading. It's more about dependencies and abstraction. I've updated the answer. Thanks. – SystemParadox Nov 8 '11 at 8:55
C and similar languages use forward declarations and/or header files, so changing the call order will not result in a compile error. I certainly don't know every language out there, but I'm struggling to recollect where or when this was even a convention, let alone a requirement. Way back in my Delphi/Pascal days there was even an (admittedly silly) convention of using alphabetical ordering for method names, which the code completion tried to nudge you into. So where is this a real convention and not personal preference? COBOL maybe? – Aaronaught Nov 8 '11 at 13:17
In C, functions that are not part of the public API can (and probably should) be omitted from the header file. Forward references can be used in the C file for convenience, but aren't strictly necessary. Still, maybe convention is the wrong word. It's more like a natural consequence. It's certainly not rigid by any means. – SystemParadox Nov 9 '11 at 0:39

Most of main methods I write are testing ones. And I usualy write them after lot of other code. So it feels natural to put it last (not so important, added after other things).

And to be consistent, i prefare to have "usefull" main last too.

Another thing. Lot of classes are built around their data, so the first thing i want to see after I open this class is what data it have. So private fields first. Followed by constructor (how can I create this class?)

If I'm interested what some method do, its usualy becose its called from somewhere. So I click on it and go to definition, so its not important how far from top it is.

And finally, classes should be small enough for this not to matter much + IDE helps a lot.

share|improve this answer

I consider it a Java convention to have the main(..) method at the bottom. I don't have any good reason why, though. Most of the time I don't bother sorting methods myself since I don't navigate the file with the cursor (I use my IDE to look up methods) and it is hard to maintain a specific order whenever the IDE generates code.

share|improve this answer

Neither is better; just depends on what's going on.

Most classes don't have a main anyway, and if they do, it's for "testing" only, thus belongs out of the way at the bottom.

A non-"testing"-oriented main is the class's entry point, and should likely go at the top, as it dictates all other behavior, and if you're exploring, you'd need to see it first.

share|improve this answer

i put methods that clients are most likely to call first.

share|improve this answer

I like to have the entry point at the top of the class, and any implementation methods below. This way you can read the entry point to the class to get a logical overview of what the class does.

For example:

public static void main(String[] args) {
  // Conceptual overview of the actions that take place
  prepareToDrawHeart();
  drawHeart();
  cleanUpDrawingResources();
}

// Methods here are defined order of being called

This only applies when you aren't implementing a class that has multiple entry points (as an example extending the List interface requires multiple entry points for clients of your code).

share|improve this answer

As plenty of the other answers indicate, people have their own preferences. What wasn't pointed out yet, is it might be fruitful to establish a convention within the team that is working on the project.

A few principles which are worth taking into account when deciding on these conventions:

  • Code should be readable in the first place.
  • Code with high cohesion should best be grouped together, so that you don't have to jump back and forth while investigating that particular 'area' of code.

An example of the latter: while you can formulate arbitrary conventions that state all private members should be declared at the top of your class, placing a member variable which is only used in one function right next to that function gives you the entire context to understand that method in one glance.

share|improve this answer

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