Instantiate class or use public methods?

1

When using a method of a class, there are two approaches: instantiating the class and using the method by the object, or making the method public static and calling directly. Is there any problem in using one or the other? Security, performance, etc.

For example:

Cliente cliente = new Cliente();
cliente.cadastrarCliente();

Or make the method static and something like:

Cliente.cadastrarCliente();
    
asked by anonymous 13.01.2017 / 13:47

1 answer

5

It depends. If you access an instance member you have no option, you have to call the instance-based method.

If you do not access anything from the instance, that is, the method is only utility to the object and therefore belongs to the class it is best to make it static and access by the class. There you can avoid creating an instance just for this. And the static method is usually slightly faster.

If you have a static parser, such as Resharper , for example, it tells you to do this. By default, if you do not access anything from the instance, make it static. If you access it, check if it is not better to make it static and get a parameter to do what you want.

If we look at class String , for example, it has a huge amount of static methods since it often does not need to access the instance itself. Even these methods will work with an instance of String , but you can receive it as a parameter. You do not need privileged access to the object.

Some people do not like this because in theory this is not object oriented. But there are the pragmatists.

Some people point out that this impairs testability. In green harms goes mock or some similar technique. It is possible to test and most of the time neither is more difficult.

    
13.01.2017 / 13:51