Instantiate class or use public methods?

Asked

Viewed 426 times

2

When using a class method, there are two approaches: instantiating the class and using the method by the object, or making the method public static and call directly. Is there a problem 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();
  • Yeah.. I thought about it, but there’s always that "best practice," sometimes "unnecessary," like capitalizing the first letter of the class. So when it comes to safety, performance and so on, it doesn’t impact anything?

  • 1

    This is not a matter of opinion, it’s quite objective where you can or can’t use.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

7

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 better to make it static and access by the class. Then you can avoid creating an instance just for that. And the static method is usually slightly faster.

If you have any static analyzer, such as Resharper for example, it has the indication for you to do this. By default if you do not access any of the instance, make it static. If you access, check if it is not better to make it static and receive a parameter to do what you want.

If we look at the 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 don’t like it because in theory it’s not object oriented, but there are pragmatists.

There are those who indicate that this undermines testability. In green it harms more the mock or some similar technique. It is possible to test and most of the time it is not even harder.

  • Got it. In my case I need to do a simple CRUD in database with the values of Forms. In this case make it static would be all right?

  • 1

    Then I have no way to answer. As I said, it depends. I gave you the parameter. You’re looking for a general rule to follow, it doesn’t work, you have to analyze each case.

  • Dude, take a look at this chapter from booklet by Caelum. I think it might help you get ahead! :-)

Browser other questions tagged

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