Instantiating an object in the same constructor class is "inelegant"?

Asked

Viewed 256 times

2

It is always seen as a good practice of programming if we create a class for the object, where we have the constructor and make the methods and another class where we instantiate several objects of the previously created class.

However, I would like to know if it is considered inelegant or a bad style you create the objects in the same class where you created the methods and constructors.

For example, if we have a very simple program, like this one below:

public class Main {
    private int var1, var2, soma;

    public Main(int var1, int var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    public void sum(){
        soma = var1 + var2;
        System.out.println("resultado = " + soma);
    }

    public static void main(String[] args) {        
        Main m = new Main(2,5);
        m.sum();
   }
}

This can be considered bad practice?

1 answer

9


It is always seen as good programming practice to create a class for the object

This has nothing to do with good practice, either you do it because you need it, or you don’t do it.

Other than that the rest of the paragraph doesn’t seem to be relevant or just "it rains in the wet", nor do I know if I understand it.

The class as a whole is not very good. Probably because it is an artificial example. Artificial examples work to denote a specific language mechanism or algorithm that doesn’t much matter the code itself, but to exemplify style, practice, elegance, you have to look at every detail, a blank space can change everything. Speaking of style, class doesn’t make sense and shouldn’t be written like this.

I imagine the focus of the question is whether it is good to put this method main() which must be the application’s entry point. For an exercise, a quick demonstration, everything is valid, the code will be thrown out next. For a code in production, for something that will be maintained, it makes no sense. Each class must have only one responsibility. If it takes care of the object should not be the application entry point.

If this method were a Factory method then it would make sense, you would create the object in a static method in the class, and it would make sense to be inside it because it is its responsibility to facilitate the creation of its objects.

Realized that context is very important to know what is elegant?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.