ForInfinity ForInfinity - 1 month ago 11
Java Question

Is it considered a good practice to create separate classes for objects for short programs, instead of using the class that contains main?

Let's assume I do want to create a small program that uses few objects, one constructor only and a formula to calculate value of one of the fields of the objects.

Is it considered bad to use the class that also contains main, if the program is short and simple? (example below)

public class testClass{

<fields, constructors, getters/setters, methods>

public static void main(String[] args) {
<creating/using objects>
}
}


Should I be creating a separate class for this, and if so, why? (example below)

class anotherClass{
<fields, constructors, getters/setters, methods>
}

public class testClass{
public static void main(String[] args) {
<creating/using objects>
}
}

Answer

I think it does not really matter. If a program is really small, you might as well use one class only, as every class adds some boilerplate code. In your case that additional class is not really needed.

Many of best practices are more relevant to larger programs anyway. If you have a program consisting of one class, you can refactor it in a few minutes anyway. So unless you are doing something obscure, any Java programmer will understand what you are trying to do.