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

In my tutorial, they put the main function at the bottom of the code examples. As a regular book reader, I start reading from line 1. While I understand that coding has a different flow of control than the books (bottom to top, line by line), I don't understand why you want your first line of code not to be the entry point of your program. Are there any specific reasons for this?

+3


source to share


2 answers


I cannot speak for the author, but I can think of several reasons:

  • Perhaps the author wanted to highlight the actual methods in the class. In practice, very few Java classes even have methods main

    (less than 1%). What's important about a class is how its objects behave; perhaps the method main

    is almost belated or pleasant.

  • 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 them main

    at the bottom. So many people did it out of habit that, oh, I don't know, it subconsciously influenced their thinking that they brought it over to Java.

But your feeling that the entry point should come first and that functions should call each other is shared by many people "down the page". Robert K. Martin (Uncle Bob) said it was a good thing.

ADDITION



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

... a newspaper metaphor that refers to the formatting of your code. This describes the idea of ​​writing code like a newspaper article. We should be able to get a general idea of ​​how it works at the top of the class before reading more and more details.

But, you know, I do believe that this is a tradition inherited from C (you have to declare these functions first), or the perceived bottom-up emphasis that makes it main

often appear at the bottom in Java.

+4


source


The main function is the entry point. there is no hard and fast rule, the main one should appear at the bottom. This is completely the prerogative of the developer. One logic is the main function based on several other functions and data. The declaration of these dependent functions must be declared and defined in Java so that the main function can access them (otherwise the forward declaration is avoided).



+1


source







All Articles