Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for putting main(String args[]) at the bottom of your code?

In my text book they put the main function at the bottom of the code examples. As a conventional book reader, I start reading from line 1. While I do understand that coding has a different control flow than there is in books (from bottom to top, line per line), I do not understand why you would want your first line of code not to be the entry point of your program. Is there particular reason for this?

like image 937
Joop Avatar asked Feb 11 '23 13:02

Joop


1 Answers

I can't speak for the author but I can think of several reasons:

  1. The author may have wanted to emphasize the actual methods in the class. In practice very few Java classes even have main methods (less than 1%). What is important in a class is how its objects behave; perhaps the main method is almost an afterthought or nice-to-have.

  2. Java was influenced by the C programming language. Although in Java the order in which methods are declared does not matter, in C (at least in older versions of C), you could only call functions from main if they were declared above main. So people either used prototypes or just put main at the bottom. So many people did this out of habit that, oh I don't know, this subconsciously influenced their thinking that they carried this over into Java.

But your sense that the entry point should appear first, and that functions should call each other going "down the page" is shared by many people. Robert C. Martin (Uncle Bob) has said this is a Good Thing.

ADDENDUM

I was looking for a reference to Uncle Bob's suggestion of reading down the page, something known more-or-less as the Newspaper Metaphor. I found this snippet from a book review of Martin's Clean Code book:

... the newspaper metaphor that is mentioned with regards to formatting your code. This describes the idea of making code read like a newspaper article. We should be able to get a general idea of how it works near the top of the class before reading more and more details further down.

But, you know, I really think it is a tradition inherited from C (gotta declare those called functions first) or a perceived emphasis on bottom-up-ness that makes main often appear on the bottom in Java.

like image 96
Ray Toal Avatar answered Feb 14 '23 01:02

Ray Toal