How much code should be in the main method of a program? - java

I'm new to creating my own software. I'm a student so I've created things that have been layed out step by step but I've never really done the process myself.
I've been trying to implement good design techniques and make good use of OOP but I'm worried that the code I have isn't very well written.
My main worry is the main method. Where I'm making a chat program I created a class ChatClient to house the main method. But I've found that all the code I really need to put in the main method is a call to a JFrame class telling it to show the program's interface. From here the entire functionality of the program is handled in other classes.
Should I be pulling more control of the way the program runs into the main method? Or is it actually fine to have a single line for a main method?

The main method and its surrounding class should ideally be used only as an entry point to start the program.
Each class you develop should be separate and have their own responsabilities since in the future they could actually be usefull on other programs/projects. You should always aim for a project with low coupling and high cohesion (more on this matter here: https://stackoverflow.com/a/14000957/6341202).
So, getting back to your original question, having only a line of code in the main method to initialize your JFrame is totally fine!

In the main method the good practice is to call to other method that is who is going to execute the program.
public static void main(String[] args){
Classname program = new Classname();
program.start();
}
public program(){
//The code that you want in the main
}

Instead of stuffing all the code in main() method its better if you write the code in a manner where it is loosely coupled and necessary modifications to the existing code are possible ie. maintainability

Having single line of code in the main method is good enuough as long as you have written your work flow in other classes and methods using good OOPs concepts.

The main method is the only method to which you cannot assign a meaningful name. Therefore it should not do anything unexpected.
Ideally it contains only one function call. Exception handling and some logging (program version, build date) should also be fine. But not more.

Related

Java Swing without extending

I am trying to make my first 2D game in Java, and I am stuck at the very last thing.
I have already done all the logic in game, and so do I have a class named World which holds all the information about the world, makes turns.
The problem occurs when I am trying to implement some methods to show world in GUI - by that I mean: I have my parent class: World, and then I have child classes WorldGraphic, where i want to show a beautiful world, with images etc, and WorldStrategy where it is mentioned to show only the most important aspects(not so beautiful but much more 'clear' i would say), and I would like them to be swapped in UI.
And i have decided to choose Java Swing library to do it, but I have came across a big problem - I cannot inherit both World and JFrame(which was neccessary to do GUI in my swing guide), Is there any way to omit it?
My best idea so far was to make public function in my world that would output the data to print, but I have doubts about it effectiveness, I would like to keep it private(protected), and do it somehow on inheritance basis, as my GUI will also have some other options(probably I would have to make a lot public methods)
My question is more about how should the structure of my document look like(so the code is probably useless). As i have already mentioned I am fairly new to Java and I am not sure if it is correct to suddenly make every method public just so ONE of my classes(the GUI actually) could use them.
You have several questions in your one question, which is not fully allowed here, but regardless, let me try to approach the main ones
First of all, regarding the need to extend JFrame: This is absolutely not necessary and in fact, is usually not recommended. Much better is for you to use JFrames (and other GUI component) where needed, but not extend them unless necessary. Extend the component if you are extending its underlying behaviors, in other words if you're overriding a method such as a JPanel's protected void paintComponent(Graphics g) method.
Should WorldGraphic and WorldStrategy both extend World? I'm not sure that this is needed or desired. It sounds as if you're trying to separate your program's GUI portion, its "view", from its logic, the "model", and if so, both aspects do not need to and probably shouldn't extend from a parent class, but rather should be connected by a controller class.
Regarding, "As i have already mentioned I am fairly new to Java and I am not sure if it is correct to suddenly make every method public just so ONE of my classes(the GUI actually) could use them.": only make a method public if it is to be called by an outside class.
Of course, for a more detailed and concrete answer, you'll probably want to post your relevant minimal reproducible example code.

Is it necessary to call a function/method outside the main body

Im currently learning java. SO I had this Question if it is necessary to create a method or function(create a class) outside the main body and then create its object and call it in main body?
There's several answers:
It is possible to have all the code of your program in a single main method and not split it into multiple methods or classes. That restricts what exactly you can do, but you could still get pretty far with that.
It's a terribly bad idea to do that, since your code will become really hard to read and you can't easily encapsulate individual sub-tasks and many design patterns won't be usable in such an environment
There is a technical restriction which limits how far you can go with that in Java and that is that the byte code of a single method can not exceed 64k bytes.
tl;dr: yes, but you shouldn't. Also no, you can't (for any serious code).
If you are asking if you can put all your application's code into the main method (without creating any other methods or classes): Yeah, I guess, but it is better to structure your code into smaller pieces. And there is a size limit for a method.
Also see:
https://softwareengineering.stackexchange.com/questions/141563/should-main-method-be-only-consists-of-object-creations-and-method-calls
https://softwareengineering.stackexchange.com/questions/154228/why-is-it-good-to-split-a-program-into-multiple-classes
It's not necessary to create a method/function outside the main body and then call it in main body, but if your code line in main is more i.e. 1000 or 2000 line then it is very difficult to manage code. So, if you create method outside main (In other class file) then call in main method using object then your code will be more readable.
It's part of the concept of object orientation in Java. You are not forced to use objects and methods apart from main, but I would really reccomended it. Java is instead of C based languages not procedural but object oriented.
As vimal said, This totally depends upon your code.
This question is not only limited to java but to all other languages too.
Suppose you are making an movie booking application for the explanation of this answer.
Then writing the whole code inside(Booking a ticket, deleting a ticket, Paying for a ticket purchased, and so on) main function would not be a good idea. One may think to write whole code in main method but it will make the code more tedious and complex. Whereas if you write your code in different functions, It will make your code modular, And also it will make your code easier for others to understand. Hope this helps to clear question.
It depends. You can do both, but there is a huge difference between them.
Java follows OOP paradigm. When you are defining a method outside your main(), you are associating the method with the class. You are defining the behaviour of a class.
However, if you are defining a method within main(), then it's just like any other method. You can call them as per your requirement.

Testing static methods of 3rd party Java SDKs

I've been working with Java, specifically in Android, for a few months now and I've found that working with PowerMockito is something I'd rather not do. The complexities of keeping it working have outweighed any benefit of it. I also think I'd agree with most of the comments I've read on Stackoverflow that say not to use PowerMockito, so please keep that in mind when answering my question. I am looking for guidance to testing without PowerMockito.
My question is, when writing code that interfaces with a 3rd party SDK that has some static method, how would you test it? Specifically, when it seems the only thing really worth testing is a behaviour? ie that the static method was called?
I can and do put these 3rd party services behind adapter classes usually. And I can test that my adapter was called. But how do you live with not ever being able to test that the 3rd party itself was called and maybe confirm which arguments it was called with? Is this the only thing available in my toolbox? to limit logic as much as possible so that the untested area is less likely to fail?
When explaining this to someone coming from a dynamically typed language would you just say that the test wasn't valuable? I'm thinking at this point that these kind of tests are low value, but I can understand why others would want to test this kind of thing. Its the kind of test I've seen written a lot in Ruby projects I've worked on.
The one thing I have done in the past in similar situations:
created a tiny wrapper interface and an impl class calling that static method; and test verifying that the wrapper is called
a single test case that invokes that impl class and thereby the real static method.
If one is "lucky" that call has an observable effect, for example some exception gets thrown (that is the problem with a lot of static code in my context - it simply breaks unless the whole stack is running). And then you check for that. But I also agree: there isn't much value in doing so. It proofs correct plumbing, at the cost of being subject to change whenever the behavior of that static method changes.

Java - Static Programming Style

When I first started learning java GUI (swing) programming the way I was shown was more of an MVC model which involved using interfaces to call things and pass variables across classes.
I recently started programming in a more static way, having a Jframe call its static Jpanel's and using static methods to change components. Bascially i program everything statically so I can call them from the different classes with ease.
Heres an example:
My main JFrame class called "Home", I initialise the Toolbar class statically:
private static Toolbar toolbar = new Toolbar();
Now whenever I want to do something e.g. change the colour I just call from another class:
Home.toolbar.setForeground(Color.green);
Is this an ok way of programming? So far i've not run into any troubles but I was caught out by the fact that the people I learnt from didn't do this when it seems so much easier to do.
Are there any big down sides to this way of programming?
What are the alternatives?
Basically, you should ask yourself:
"Should toolbar be associated with each object I create? Or should it be one for all objects, and once I change it, it changes for all objects?"
If you answer yourself "Yes", then it's OK, otherwise it shouldn't be static.
Of course there are many things to consider beside that.. For example, static resources are not thread-safe.
If it works, then great... It's correct.
However, I make it my goal to write code that's both maintainable and testable. The problem with static instances is that it creates strong coupling throughout the entire project. Moreover, trying to isolate a class is impossible because the static dependency cannot be mocked or injected.
Typically, GUI code cannot be unit tested. MVC, however, ensures that the testable code is separated from the GUI code.

How to access a specific component/method in a class without creating an instance

I have a class GuiApplication and a class ImageHandler. The GUI can work with the ImageHandler (and thus images) trough a class called Crawler which provides a façade for the methods the GUI can use.
There's a separate class called StartUp which has a main method and the only thing done there is create an instance of GuiApplication (so basically it starts the program).
In my GUI, there is a JTextPane which serves as a logger: certain actions and events will be shown there. With output that comes from elsewhere within my GUI, I can easily update its value. However, when there is output that comes from within my domain classes, e.g. ImageHandler, I can't do anything.
There is a Try-Catch block which prevents my program from crashing when an unexpected image URL passes trough my reader, and when it does I would like to show this in the textpane ("Error: File xxx could not be read").
However, I don't see an elegant way to communicate this to my GUI: I can't create an instance because that would create a new GUI and I don't think approaching my GUI trough the StartUp file is good practice either.
I was considering defining the variable in a different class that could be accessed troughout the entire project, but I wanted some opinions first.
The practical way is to throw a RuntimeException, which does not need to change the methods' signature. Catch it in the GUI and do a JOptionPane.showMessageDialog.
The other way is to extend the API of ImageHandler with an event handler, and install a message handler that calls in GuiApplication JOptionPane.showMessageDialog.
One option that comes to mind is a callback: pass an instance (it can be an anonymous class) of some interface to the method doing the work, which it calls when an error occurs.

Categories