When I teach Java programming to students without any background in programming, I teach code structure along with logic and syntax. This means that I require my students to layout their code in a very specific format. One of these requirements is about how to use the main method.
I explain that the main method is like the CEO (Chief Executive Officer) of the application. This CEO builds the company and puts it in the hands of his underlings to run. The CEO does not get involved with the mundane and day to day issues. The CEO just starts it going and collects stock options while sitting on their yacht. This gets a few chuckles.
When you start a new Java project in NetBeans IDE, it will conveniently create a class with a main method. Here is the dialog for creating the project:
Notice the checkbox Create Main Class. For the longest time, I instructed my students to uncheck this box. For me there are two things wrong with it. One is the choice of the package name and I will save that as a topic for another article. The second, and the reason for this post, is the code generated.
Here is the code that comes out:
So what upsets me? It is the comment:
// TODO code application logic here
Application logic belongs in methods that are members of a class. It has been my experience, going all the way back to teaching the C language, that if you show students that they should solve problems in main, then that is where they will try and solve everything. When you finally get around to explaining that the code should go into methods, all they do is move all the logic into one other method.
I instruct my students to write an application class with a main method like this:
I am an "objects first" proponent. Nothing should work without an object being created. For a console application, the main method should only ever be three lines long. It may instantiate the class it is in. Later in my beginners course, I have the students place main in its own class and have it instantiate another class. This is what I call the program’s COO (Chief Operating Officer).
The method perform is my arbitrary name. I tell my students that methods should be named with verbs and the word "perform" is as good as any other.
This may all look like I am substituting main with perform, but I quickly require private methods to handle the different aspects of the program’s logic. They have already called upon perform and so they feel comfortable calling other methods
In my next article, I will show you how to have NetBeans create this file when your students create a Java application.