I'm quite new to Java and wrote a little to-do list project.
At the beginning of the project I added a bunch of static methods to the file where my main() code is, and it got a little out of hand. I want to transfer these methods to another file.
Is there a proper way to do this, or do I just have to create some sort of Behaviour class for these methods, and then in main() create an instance of it to call it's methods?
You can extract these methods to a separate class (say FooUtils), and then in your main method you can call them using the class name - FooUtils.someStaticMethod()
Depending on what you have, it may make sense to group your methods into different classes, or to make them instance methods.
Related
I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.
Currently, my "main() class" file looks a bit like the following code. Rather than clutter up this example code with //comments for discussion, I have simply labelled four code lines with numbers (1 to 4), and these numbers refer to questions that appear after the code. Thank you.
// package myPackage; // **1**
import myOtherPackage.*;
class mainProject{ // **2**
// **3**
private int myVar;
mainProject(){
myVar = 0;
}
public static void main(String args[]){
// Keep main() looking fairly simple?
// Perhaps just have some "essentials" here, such as error handling?
new mainProject().start(); // **4**
}
private void start(){
// The project gets going here..
}
}
1 Unlike other class files in my project, I have not assigned a package name for my "main() class" file. Is this a bad design choice?
2 Is there a good naming convention for the "main class"? Is it helpful to incorporate the word "main" in to this class name? Would something roughly like "mainProject" be a good idea?
3 Various coding constructs can appear inside the main class file. For example, local variables, constructors, the main() method, and local methods. Do they have a "best order" in which they appear in this file?
4 Is it worthwhile to keep the main() method looking fairly "lean and simple"? In this example, I have just called a local private method called start(), which is intended to get the project started.
Ok, here is how I do it in my professional projects.
For 1. every class should have a package. Main or no main makes no difference. Package is the way java organizes your classes at runtime in form of namespaces. So if you stop giving packages then you may end up with two class files with same name in the same folder or jar and when that happens, JVM picks the first class it finds by the name on the classpath. That may not exactly be the one you want.
For 2. main (speciallypublic static void main(String[] args) is a specific and standard signature that Java needs. Any runnable program, a program that produces an output and can be executed needs a main method with this signature. I will try to explain the signature and that maybe will help you understand why it's like that.
It's public because you want the JVM runtime code to execute the method. Using private or protected won't allow the JVM code to see your method.
It's static because without static the JVM code would need an instance of your class to actually access the method. Remember that static methods and fields can be accessed by just using the class name. However non static members need a valid live object to reach them.
It's void because main does not return anything to its caller. It's like any method having a void return type.
And it's called main because the Java creators thought to give it that name. JVM runtime code which executes this method needs to know about the name of your method which will kick off the execution. Now, if I name it anything then it's impossible for the JVM code to make a wild guess. So name standardization called for a standard name and Java creators stuck to main.
String[] is actually a string array containing the command line arguments that you pass to your program. args is the name of the argument and ironically this is the only thing that you can change to any name you want.
For naming the main class, I usually prefer the names like MyProjectLauncher or MyProjectBootstrap where myProject is the name of your project like tomcat or bigben or anything you like.
For 3. standard convention is:
public class MyClass{
//private members
//protected members
//constructors
//private methods
//protected methods
//public methods
//hashcode and equals
//toString overrides
}
You can pick what you need and drop what you need. Public methods also include the getters and setter for your variables if you use them.
For 4. When designing classes you need to keep in mind scalability and manageability of code. It's very common to have a main class and a few classes at start of the project and then when they grow into oversized kangaroos of thousands of lines then refactor code to adjust it. What you should do is create classes based on functionality, service helpers or actions. Keep main separate in a different class. Just use main to initialize a few things, parse command line options and delegate to start or initialize method which does the remaining things to kick off your program.
Hope this helps.
1 yes you should always use packages. But dont use camelcase in them... So myotherpackage rather than myOtherpackage.
2 yes, it is good convention to incorporate the word main, e.g. MyApplicationMain. Remember class names start with a caps letter.
3 yes, the common order would be statics, members, constructors, methods, much like you have already
4 yes! This enables better testing and you should not use a static context for any longer than you need to.
If you add a package and take on board my tips for caps letters, i think what you have above is absolutely fine.
Usually, it is good to define your own packages in order to avoid naming clashes with any other classes on your classpath. This also applies to the main class. Imagine what would happen if somewhere else in your dependencies there is a class whose creator used the same approach of leaving it in the default package. So yes, put iinto a package.
The naming is left at your latitude, but Java coding conventions definitely urge you to capitalize the name of the class. So, Main or MainProject or EntryPoint would be better choices.
I think you refer to fields and methods as members of the class. Please note that local variables and local methods have a totally different meaning (they're not members of the class itself). The usual ordering is static fields, instance fields, static methods constructors, instance methods. I don't think there is a strong convention, but these are the habits.
It is worthwhile keeping any method clean and simple ;)
ALWAYS use a package. No matter what. This is your namespace!
Don't use camelCase in your package names.
Avoid to import whole packages.*, better import a single package.Clazz.
Class names should ALWAYS be UpperCaseAndCamelCase.
Leave a space between the class or method name and the opening braket {, it improves readability.
The rest seems to be ok. It is more or less a matter of pragmatism. Your code has to fulfill the purpose it was written for and also needs to be testable and readable (by others).
All these criteria will form a ruleset for you or your team.
What if someone else has a main class with the same name? Its better to place it in a package for all but the simplest test programs.
Incorporating "Main" in the class name is a good idea because it quickly tells the reader the purpose of the class, but "mainClass" should be "MainClass" according to java language conventions
The usual order is variables, constructors, and methods in whatever order is reasonable
Yes, keep the main method small and easily readable. The logic in it should mostly just be related to parameters passed to the program, and even that should be factored out when it gets to be too large.
1 packages should definitely be used. It is better for maintenance purposes, if your project gets larger with time then there could be exact same syntax for main used. the package name should be meaningful as well and provide concise containment for relevant functionality classes.
2 yes, it is good to include the word main in the class name and should start with capital letter.
3 commonly the order is variables, constructors, methods.
4 keep the main concise and simple. the lesser code it has the better as you already have done.
I want to write a general function for my project that will be used across many different files and I don't want to have it in a particular class.
Where am I supposed to put it?
Inside a new package as a class?
Is this the only option?
Create a new package as util and create all common methods in there, for example:
Create package as com.xyz.util.
Create a class as Util in above package.
Then write your all common methods in this Util class.
You can write static methods in this class and access them as Util.method_name();.
In Java every method lives in a class. So yes, its the only option. A common approach is to use a utility class containing only static methods. You can use it from everywhere without creating any instances.
I am trying to understand how the following code ties into two other .java files that are in the package template. In the main method are three class being instantiated? Why put them in the main method if everything is in the package template? Will these all have Driver class as a superclass? And finally are any of the words in the three classes that are being instantiated java specific words with the exception of the work "new". Thanks for any insight into this. I am trying to understand how a project fits together so that I can write a recursive algorithm to search files. Thank you
One more question I want to make sure that I understand is why is gui in the parameter for DirectoryLister....DirectoryLister(gui);??? Does it need to be there in the main class so that it can call methods from gui??
package template;
import javax.swing.*;
public class Driver
{
public static void main(String[] args)
{
GUI gui = new GUI();
DirectoryLister dl = new DirectoryLister(gui);
gui.registerModel(dl);
}
}
Lot of questions:
In the main method are three class being instantiated?
No, only two are explicitly instantiated: GUI and DirectoryLister.
Why put them in the main method if everything is in the package template?
main method is just the entry point for your program. You may or may not put everything inside main method. Just keep in mind that that's where your program will start executing.
Will these all have Driver class as a superclass?
If you are referring to GUI and DirectoryLister then the answer is NO. Not at all. They're completely independent.
Are any of the words in the three classes that are being instantiated Java specific words with the exception of the work "new"?
No. None of them.
I want to make sure that I understand is why is gui in the parameter for DirectoryLister....DirectoryLister(gui);??? Does it need to be there in the main class so that it can call methods from gui??
DirectoryLister probably expects a GUI instance in one of its constructors. You are building your dl object with gui element by calling DirectoryLister(GUI g) constructor.
--
Also, keep in mind that your question is not related to JavaME as you tagged it. It's just a plain Java question. You won't be using JavaME here since you are importing javax.swing.* which is not available for JavaME edition.
You need to learn basic java. You are instantiating only two classes.
Why does the main method have to be put into a class? I understand the main ideas of OOP but I cannot get why the main program is defined within a class. Will such a class instantiated somewhere? I mean there is no code outside the class. What is a reason to define a class and never use objects of this class?
The Java Virtual Machine (JVM) has to start the application somewhere. As Java does not have a concept of “things outside of a class” the method that is called by the JVM has to be in a class. And because it is static, no instance of that class is created yet.
While it's true that java has no concept of methods outside of classes, it would be pretty easy to allow developers to skip all the broilerplate of actually writing out the class definition and simply let people write the main function directly, if they wanted too.
But back when people were developing java, people were more dogmatic about OO then they are now, and that probably played a big part. Think of it as an example of Opinionated software
It has one useful feature though, which that you can main functions to any class and launch them as programs. It's handy for testing specific features of those classes when you're working on them. If main() had to be in a separate file, and not part of a class, that would make things difficult. What if you want more then one main() function? What if you wanted to write functions to be called by main outside of the class? Would they go in a global namespace? Would multiple main() functions collide?
Not like those problems are impossible to solve, but other then a little extra typing, which can be especially annoying for newbies the current solution isn't too bad, especially since IDEs will generate the basic class structure when you create a new file.
It does simplify the design of the virtual machine. Since virtual machine already knows how to run a static method of a class then it can treat the main method just as any other static method.
If you put the main method in any other construct other than a class then the VM has to be modified to know about another construct complicating things even more.
When the Java language was designed, the notion that everything must be an object was a point of dogmatism. (though they left in a few primitive types). These days you could perhaps design a language that uses a closure -- even one outside any class -- instead.
What #Bombe said. I would add that to OO purists, the fact that the entry class is not instantiated is a misstep. The reason is the static main prevents someone from writing a family of main classes that share the same main() method written using a template method pattern.
If Java had been written to instantiate the main class and invoke the main method, users would have enjoyed the benefits of inheritance and interfaces.
As we know main is the entry point for the JVM to start. And in java there is nothing except classes and interfaces. So we have to have a main method in the class that too it should be a public class. and the main should always be public static, because it should be accessible for JVM to start and static because it starts without creating any objects
The main reason is so that multiple classes can have a main method. So a codebase can have many "entry points" and one just uses the class to specify which one is called. Also, this is inline with the OO design where (almost) everything is an object.
Main in java is a static method, therefore the class it's in doesn't need to be instantiated into an object, the class simply needs to be loaded.
That's simply how Java was designed: (almost) everything is an object, and code can only exist as part of a class.
Since the main() is static, it being called does not automatically lead to an instantiation of the class. However, it's perfectly possible (and quite common, at least in small Swing programs and Applets) to have the class that contains the main() be an otherwise normal class that is instantiated and used like any other class.