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

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.

Related

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

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.

How to format methods in a class

I have nearly about 12 methods in my class. My doubt is, is there any formatting style like the called method has to be written next to the caller method" Is there any standard that maximum methods per class?
I would suggest reading Robert C. Martin's thoughts on this in his book Clean Code. He writes that a class should be readable as an article or a page of a book, so you preferable keep methods close to which they call into. Of course it is impossible to keep everything this way but you can head towards it. This eliminates the need to browse big sources frequently. For maximum methods Fowler has some rules also but it really depends on the class, but: keep methods and classes as small as possible.
It is impossible to keep calling and called methods next to each other, most obviously due to the fact that they can be in different classes.
There are no standards that would say "you can't have over 20 methods in a class", since it's not something that you can standardize (or rather it wouldn't make sense). With experience you'll learn to see if a class has too many methods (one indication would be that a class seems to be responsible for 2 different things, in which case you'd refactor the class into 2 different classes).
Generally speaking, 12 methods are too many for a class, I think you should think it over, if there are too many methods, maybe they are contradict to object-oriented thoughts. If you are OK with a specific language, you can get to know some design models such as MVC, maybe that will give you some ideas.

Alternative to creating separate class

At the moment I have two classes, first one is called "Building" and second one is called "Happening". Every building has its own name, and ArrayList of events (Happening) for one day. The class Happening has start time and end time. There can be many buildings and every building can have multiple events (Happening). But as you see I am using two classes to get this job done. I know it is probably the best way, but I am curious if I could handle all this with only one class (Building) without needing the Happening class. I tried using Happening as an inner class, but it won't work for me, because my main method that gets data from Building also needs to know this class, because my Building has a method to return all its happenings as an Array. So I am wondering if there is any alternative way of doing this.
Do not consider creating separate classes to be a bad thing. It makes your code easier to read, use and understand. While you undoubtedly could combine these into one class through the use of multi-dimensional lists/arrays or some other hack, the result would be a much less readable codebase. (Think of it as the same reason why, in database design, we try to separate things out into separate tables where we can, unless performance reasons dictate otherwise).

Java Design Questions - Class, Function, Access Modifiers

I am newbie to Java. I have some design questions.
Say I have a crawler application, that does the following:
1. Crawls a url and gets its content
2. Parses the contents
3. Displays the contents
How do you decide between implementing a function or a class?
-- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well?
-- If it should be a class, should it be protected or public class?
How do you decide between implementing a public or protected class?
-- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public?
Thanks
Ron
I think Andy's answer is very good. I have a few additions:
If you believe that a class will be extended in the future, you can set all your private methods (if any) to protected. In this way, any future extending classes can also access these.
I like the rule that a method shouldn't be longer than that you can see its opening and closing brackets ({ }) without scrolling. If a method is longer than that, try to split it up into several methods (private, protected or public by your preference). This makes code more readable, and could also save on lines of code.
So let's say a method is getting big and you split it up into several private methods. If these new methods are only used within the first "mother"-method, it makes sense to move all of that into a class of its own. In this way you will make the original class smaller and more readable. In addition, you will make the functionality of the new class easier to understand, as it is not mixed up with that of the original class.
The best guidance I've seen for these types of questions is the "SOLID Principles of OO Design."
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
The most basic of these principles, and the one that sort of answers your first question is the "Single Responsibility Principle." This states that, "a class should have one, and only one, reason to change." In other words, your classes should each do exactly one thing. If you end up needing to change how that one thing works, you only have one class to change, and hopefully just one place to make the change within that class. In your case, you would probably want a class to retrieve the content from the URL, another class to parse it into some sort of in-memory data structure, another class to process the data (if needed), and yet another class (or classes) to display the content in whatever format you need. Obviously, you can get carried away with classes, but it's typically easier to test a lot of small, single-operation classes, as opposed to one or two large, all-encompassing classes.
The question on public vs. protected depends on how you plan to use this code. If your class could be used independently outside your library, you could think about making it public, but if it accomplishes some task which is specific or tied to your other classes, it could probably be protected. For example, a class to retrieve content from a URL is a good general-purpose class, so you could make it public, but a class that does some specific type of manipulation of data might not be useful outside your library, so it can be protected. Overall, it's not always black and white, but ultimately, it's usually not a huge deal either way.
I like to think of classes as "guys" who can do specific stuff "methods".
In your case, theres a guy who can fetch the content of an url if you tell him which url that is.
Then there is this another guy, that is really good at parsing content. I think he does that with a tool called rome, but i'm not sure. he keeps that private (hint ;) )
Then we have that third guy, who displays stuff. He's a bit retarded and only understands stuff that "another guy" produces, but hey thats fine.
Finally the project needs a boss guy, who gives orders to the other 3 guys and passes messages between them.
ps: I never really though about making classes protected or not. Usually they are simply public without any specific reason. As long as it don't hurt, why bother?

How to know, the number of times a particular method is invoked in java

Is there any way to know how many times a instance of a class has invoked its member method.
I think(not sure), one way is to have a dedicated a member variable for a method, But that will not be feasible if we have so many methods.
For example:
class A{
public void someMethod(){
}
}
and i have a instance say
A a = new A();
So I want to know the Number of times a has invoked someMethod in a program.
We can have any number of methods.
If you need this information inside the program, this is exactly what aspect oriented programming is meant for. Using AspectJ, it would be quite easy. Spring AOP will probably also work.
Indeed, AOP would be the right tool here and I would write a little aspect to use JAMon (which can precisely gather statistics such as hits, time statistics (avg,total,min,max), concurrency statistics and more). See this previous answer for an example (or goolge a bit). If you are using Spring, then Spring has a ready to use JamonPerformanceMonitorInterceptor.
There are a few approaches you could take, depending on how easily you can modify the code:
just add the counter variable as you suggest; clumsy if you have to add it in a lot of places, but easy to code
put your counter code in some other utility class, with a single method that you call from all relevant places to "increment counter for this method"; the utility method in question then examines the call stack-- e.g. via (new Exception()).getStackTrace()-- to see who was calling and increment the relevant counter
use a profiler that provides this facility
use the ASM library to add a counter.
use the Java instrumentation framework to modify the class definitions of relevant methods on the fly as the classes are loaded; this is potentially the most flexible-- you can even instrument code that you haven't actually written yourself and can't modify, and it means you don't have to alter the code of the actual classes you want to perform counting on-- but it is by far the most complex to code.
You may consider using profilers, e.g. one from NetBeans or YourKit, etc.
There a lot of Open Source Java Profilers.
A profiler does dynamic program analysis (as opposed to static code analysis), and shows a program's behavior, gathering information as the program executes. Some of these profilers shows method invocation statistics.
If you have access to JProbe it will tell you the number of times a method was invoked by a particular instance.
They say MAT is also good and its free, I haven't tried it yet.
It's possible to do with java.lang.reflect.Proxy class. In Horstmann's book 'Core Java. Volume I' this technique is described in details.

Categories