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.
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?
– Leopoldo Nascimento
This is not a matter of opinion, it’s quite objective where you can or can’t use.
– Maniero
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).
– Maniero