Java - how much logic to put in the main class? - java

How much logic do you normally put in the main class? Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
If you have any suggestions on this topic (or external articles), I'd appreciate it.

For small tools, I'm happy to have most or all of the logic in the main class - there tends to be less of a model to work with. (For very small tools, I confess I usually don't bother with unit tests. In particular, there's less benefit on the design side of things than there is if you're building something which will be a component in a larger app.)
For large scale apps, the main class is really just involved with setting things up and getting them in motion. If you're using a DI framework that can be very little code indeed; if you're not using dependency injection then the main class often acts as a "manual" dependency injection framework.

Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
Yes. main method and its surrounding class should ideally be used only as an entry point to start the program. The mere existence of the surrounding class is just an artifact of the way Java programs are composed (everything must be inside some class), and there's no reason why it should contain other stuff in addition to the main method (but there definitely are reasons why it shouldn't).
When you get the interesting classes (those that form the actual program) separated, you open doors for all kinds of flexibility. Perhaps some of those classes could be used in some other projects. Perhaps some day you'll want to replace some of them with better implementations. Maybe you'll find a better order to instantiate all those classes - so just swap a few lines. Or how about executing lengthy startup loadings and instantiations in parallel threads? Just wrap some of them to suitable Executors. Good luck trying this with a 1000+ line main class.
This kind of flexibility matters for everything except maybe for 100-line elementary examples, prototypes and such. But given that even small tools tend to grow, why not do it correctly right from the beginning?

It's not so much a question of whether a class is "the main class". It's a question of how much logic is in the public static void main(String args[]) method. Ideally, it should contain very little logic. It should essentially construct one or two objects, and then call methods on those objects. One of those objects might be a this() - an instance of the main class, and that's ok.
You have to put the main() method somewhere - there's no need to create a special class just to hold that method.
As a general rule, try to avoid having too much in static methods - static methods can't be mocked for testing.

The main class should be an entry point to your program and should thus be relatively small. However this all depends on your actual program. If it's 50 lines long, it might be overkill to create two files for it.
As an example, consider the default Swing Application Framework Desktop Application as it would be generated by the NetBeans template, which is simple and short, and whose main() method is a single line that launches it:
public class MyApp extends SingleFrameApplication {
#Override protected void startup() {
show(new MyView(this));
}
#Override protected void configureWindow(java.awt.Window root) {}
public static MyApp getApplication() {
return Application.getInstance(MyApp.class);
}
public static void main(String[] args) {
launch(MyApp.class, args);
}
}

Related

How and when to declare a Main Method

This may seem like a stupid queestion to most of you, but I have been learning Java using BlueJ, and BlueJ is created for learning, and as such Main Methods are not necessary given the BlueJ extensions provided by my University.
Therefore, now that I am playing around in both NetBeans and IntelliJ - I really want to get a good idea of when to declare a Main Method.
I know the Main method is the entry point of a package when it is compiled and run. But that is the extent of my knowledge.
If I am to build some apps in a full blown IDE, should I place all of my Class methods within a Main Method? Should the Main method be seperate from all others? Do I declare instance Variables within the Main Method?
Are there any good sites, or tutorial materials available that can help me structure my BlueJ Java knowledge into an IDE that requires a Main Method?
Thanks
Ok.
Main method is an entry point to your application.
If you watch any Java related tutorial, you'll probably see something like this.
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
This has been taken from Oracle's website.
When working with IntelliJ, you'll be presented with a package main on the top, or something else.
You see. Java unlike some other languages distinguish between namespaces using those packages. Think of them as a little packages full of Java classes that you can reuse.
For example, if you look at Log4J's repo => here, all these folders are essentially packages.
That way you can have many packages, and a single file that will trigger your main method, and start everything else.
That's how it's usually done.
But if you really want to learn Java from scratch. My suggestion is go to YouTube. Derek has done some marvelous job with his tutorials.
Best of luck.
While technically you can have more than one main method, for most use cases you only need one.
You should define it where it makes sense to do so in some "central" class responsible for bootstrapping your application and getting everything going.
The main method is static though so it can't access your class' instance. Typically this is how you'd get around this.
class TicTacToe {
public void theEntryPointToYourApplication() {
// ...
}
public static void main(String[] args) {
// This doesn't necessarily have to be the same class where you
// defined your main method
TicTacToe ticTacToe = new TicTacToe();
ticTacToe.theEntryPointToYourApplication();
}
}
This is just a small example though there are many ways and different approaches depending on your specific use case and needs.
Personally I have never used BlueJ.I've always been a netbeans fan.But the answer to your question is a general rule that most of the Object Oriented Programming Languages follow.You know that main method is the entry point of a package when it is compiled and run.Let me explain it in simple language.
Consider a soccer game.Assume that the field is the main method.The players are different functions.You are free to define any number of functions, but only 22 functions are called in the field.The whole game is controlled and played by these 22 functions only.So what do you learn from this?
We learn that java is only concerned with what is present in its main method just like the fans sitting in the stadium are only concerned with the 22 players who are currently playing.So if a programmer is writing a small program,normally the whole logic goes into the main method.But if its a large program,the program is distributed into various modules/functions and then these functions are called in the main method so that they get executed.

How to correctly implement communication between Java classes

I'm a beginner in Java programming and I'm currently working on an app with more complex class structure and a GUI. This might be a stupid questions, but it is very hard to google, so I'm asking here.
I have a main class, looking like this:
package app;
public class App {
private FirstClass fc;
private SecondClass sc;
public App () {
fc = new FirstClass ();
sc = new SecondClass ();
// ... code continues ...
}
}
Say the SecondClass is defined outside of this .java file (like GUI forms are). Is there a way for me to access the "fc" instance (or other member variables of the App instance) from the "sc" instance (without passing the "this" pointer)? Something like:
class SecondClass {
public void someMethod() {
getWhoeverCreatedThisInstance().fc.getSomeData();
// ... code continues ...
}
}
And if not, what am I doing wrong? Should I design this differently? Maybe setting the "fc" as static? But what if I want more of my app's classes to communicate with each other, should I make them all static? What would be the point of having something non-static then? I could pass the "this" pointer of "App" or "fc" instance in the constructor of "SecondClass", but that solution just seems non-elegant when the number of classes that need this behavior rises.
Any ideas? Thanks in advance!
My suggestion is to implement a callback system with interfaces. Each of your classes communicating with each other should implement these.
The classes should Register to the creating class.
Then they can call a method in the creating class which invokes the interface method of each registered class and passed the data this way.
This SO answer might help
https://stackoverflow.com/a/18279545
If you want to develop GUI applications, you should really get into the basic concepts. This can be very time-consuming, but it is necessary, otherwise you will encouter strange behaviour. I will just give you a basic understanding to answer your question.
You think of simple console applications, where you usually have a single thread and passing around objects is valid. With multiple threads, this is fatal, even with static variables. Each variable or object can be modified concurrently and the other thread may not be able to 'see' the changes in time. This is a complex matter, since there are also caches and separate stacks for each thread. In short, fc may not always be synchronized in App and sc, therefore reads and writes may be inconsistent.
What to do now? Learn the concepts of GUI programming. Often you do not even have to share objects for simple things. If a GUI control triggers an action, use a Listener, look here. If you want to access a database for example, then just make a new connection object for each request or button click, whatever. This is simple to start, add complexity later.
A simple variant to share objects is to use the synchronized keyword, which ensures that a method or a field is only accessed by one thread at a time. Here is an example. Also look at thread-safe data structures provided by Java (java.util.concurrent).
For advanced purposes you would have a separate thread and you would connect them with Sockets to pass messages or data.

In java, do I always need a Main class?

I know that I'll need a main method, but can that main method be in a different class other than the Main class?
Not all Java applications require a main method.
Java can also be used to create web applications, for instance, which don't require main methods to run.
The answer to your question depends on what exactly you mean. Do you mean a class with the name 'Main'? Then, no, there is no requirement for this at all.
The only requirement that Java has, is that the signature of the method is correct. the main method must:
be public
be main
be static
have returntype void
accept an array of Strings as (only) parameter
It's easier to add it in the public class in a file, but not mandatory. The name of the class it is in, is entirely up to you, though many will choose a name like 'Main' or 'Open', simply to more easily find it.
If you want to be able to run your application, by simple double-clicking the .jar file, you'll need to point to the class that contains the main method (to use: your application might contain a lot of main classes, used for internal testing, but only one can be used to start the actual application) in the manifest file: Manifest files
Prior to Java 7, it was possible to run a desktop application without a main method, by (ab)using an instantiation block, but this was removed as of Java 7, because this is not what the instantiation block was intended for.
It's not necessary to define yout main method in a main class. You can place your main method wherever you want, as long the syntax i correct :
public static void main (String[] args){
//...
}
You absolutely don't.
The method itself can be placed whereever you want it to be, there is no limitation.
However, I personally would recommend putting it in a class which at least contains something like "Main", because when others look at your code, and they are not using an IDE which supports jumping to the main method, people usually have an easier time finding your starting point.
However, that is just for sake of readability, and as I said, jumping to main is/should be usually a widespread supported feature
Yes, the Main method is required to run a function although a java class can be without the Main method. Though, it won't run...

why do we use java files without main ? What purposes does it meet ? How useful it is .?

I am new to java programming and i just came across to a java program composed of many files and only one of the file had a main function while others did not. I didn't really understood that why don't we have a main function in every java file.
Not every file needs a "main" function. For example, you may want to import a file with specific function or class. In this case (a java file without a "main" function), the java file simply represents a chunk of code, which is added to your program. So it doesn't need a separate "main" function, if you already have one.
In java, main() is an entry point to a program/application. Sometimes in a application we just need only one entry point to start the program and from this point other necessary code are used.
But not all application necessarily need an main() method - like web application or java applet where a container initiate the application/program.
Every Java program must have an entry point, and that entry point must have a certain signature. Which, as you have noticed, is public static void main(String[] args)
After that, the class that is the entry point can create instances of other classes and/or invoke their methods, or invoke static class-level methods. It is not necessary for those classes to have an entry point, because the program is already running (executing your code) in the Java Virtual Machine (JVM).
You'll notice that a common error novice (and sometimes even seasoned) programmers make is trying to run a program for which the runtime environment cannot find an entry point. E.g., Eclipse: Java, no main method found (in this example, the problem was that the OP had the wrong method signature). The runtime has to find something to, well, RUN.
If your code is going to be run by some other code (e.g., you are developing a library or an API that contains functionality that will be used as part of another application) it may not be necessary for you to have a main method. If you look through the .jar files of some of the standard libraries using your IDE, you should discover that very few of them have classes with a main method - this is because they are not intended to be run alone, but rather in the context of another application.
The public void main(String args[]) method in java is the entry point to the program. If it is run directly, it will start from the main method. However, not every class that you might make in Java is an acceptable entry point. In fact, in many applications, you should have exactly one main method. There is generally not too much need for more. Some java libraries has no main method anywhere at all. This code is generally designed so that it can be used by other java code, and often has no sensible way to run itself. It's not designed to do that. It is designed to help other programs that do.
What classes without a main method are used for, is a) to provide functionality for other java programs (dependancies for instance), b) to provide additional functionality to the program that is invoked through the main method.
Here is a couple example files that illustrate the second.
MainExample.java
public class MainExample{
public static void main(String args[]){
OtherClass other = new OtherClass()
other.doExpensiveComputation1();
other.doExpensiveComputation2();
}
}
OtherClass.java
public class OtherClass{
public void doExpensiveComputation1(){
//do stuff here
}
public void doExpensiveComputation2(){
//do other stuff here
}
}
Now, you might be asking, "couldn't I just write those methods inside the main class?". In some cases the answer might be yes, but for more complex code, it generally isn't. In some cases it will be impractical simply because it clutters up the main class too much to keep track of. It is much easier to keep track of code that keeps its classes in different files.
Execution of Java program always starts from Main method.Class having main method is the entry point for the program and further from there you can get the rest of the desired functionality.
If You want you can have main method in each java file, which will behave as multiple entry points for your program.

is there any benefit of writing public classes for the main method?

We can write a java program with one non-public class containing a main method -- it'll compile and run just fine. Why do people make the main class public?
Is there any benefit?
There is no benefit of making the class public for the sake of it having a main method.
That being said, there isn't really much of a reason not to either. Chances are the main class is either going to be very short with few, if any, substantial methods in it, or it's going to be baked into one of the core classes like
class Server {
public static void main(String[] args) {
Server s = new Server();
s.start();
}
// rest of Server class here
}
And typically those core classes are something you'd want to be public.
But this isn't about the benefits of having classes be public. This is about the benefits of having a class be public because it has the main method and there are no direct benefits as a result of that.
Simply because clients will have access to create objects of your class based on the accessibility you specify for your class. If you look at Java source libraries you will see lot of private (inner classes) classes too. Depends whom do you want to allow access to create objects of your class.
Benefit you will have only when classes you are using in main method doesn't belong to same package.Public class will have visibility across all the packages.

Categories

Resources