Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use public static methods

There are a lot of people out there against the use of "public/private" static methods. I have search around,with no luck, and tried to find anyone that advocates good use of static methods.

Assuming the methods will always be Cohesive where are the acceptable areas to use public static methods? Do these methods vary between Java and .NET (aka is it more acceptable in one then the other)?

This recent SO post spurred my anger/interest in this topic.

like image 461
Nix Avatar asked Jul 30 '10 13:07

Nix


People also ask

When should I use public static?

Use public static methods if the method can be considered a unit, and can be effectively tested on its own. It's plain hard to implement dependency injection or mocks on types that use static method. I use static methods for utility methods with few/no dependencies, and well defined input/output.

Why do we use public static in method?

In Java programming, the main motivation for making a method static is convenience. You can call a static method without creating any object, just by using its class name. So if you need a method, which you want to call directly by class name, make that method static.

Should static methods be public?

private or public doesn't make a difference - static methods are OK, but if you find you're using them all the time (and of course instance methods that don't access any instance fields are basically static methods for this purpose), then you probably need to rethink the design.

What is the use of public static in Java?

The keyword public static void main is the means by which you create a main method within the Java application. It's the core method of the program and calls all others. It can't return values and accepts parameters for complex command-line processing.


1 Answers

Use public static methods if the method can be considered a unit, and can be effectively tested on its own. It's plain hard to implement dependency injection or mocks on types that use static method.

I use static methods for utility methods with few/no dependencies, and well defined input/output.

like image 137
kbrimington Avatar answered Oct 15 '22 20:10

kbrimington