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

2

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

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

For example, if we have a very simple program, like the 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();
   }
}

Can this be considered bad practice?

    
asked by anonymous 28.12.2018 / 13:21

1 answer

9
  

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

This has nothing to do with good practice, or you do it because you need to, or you do not.

Otherwise the rest of the paragraph does not seem 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 language-specific mechanism or specific algorithm that does not really matter the code itself, but to exemplify style, practice, elegance, one has to watch every detail, one blank can change everything. Speaking in style, the class does not make sense and should not be written like this.

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

If this method was a factory method 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 her responsibility to facilitate the creation of its objects.

Have you noticed that context is very important to know what is elegant?

    
28.12.2018 / 13:28