Settings

Theme

Public Static Is Harmful

divye.in

1 points by divyekapoor 4 years ago · 5 comments

Reader

galaxyLogic 4 years ago

I we don't need public static methods then why would we need private static methods either? So, no static methods at all?

The reason to define a public static method is it serves as a simple entry-point to the functionality of your class.

And what is a constructor if not syntactic sugar for a "static method", which creates and returns an instance?

I also don't see the point about 'static coupling". The class whose static method you are calling could come as an argument, so it would not be static coupling after all?

  • divyekapoorOP 4 years ago

    @galaxyLogic: you're right - we don't really need private static as well except for the single nifty/dubious feature that a private static method can't affect member variables of the class (which is useful for thread safety guarantees).

    The only reason the recommendation isn't as strong for private static is that the scope of the "virulent" recursive refactor is limited to the class within which this method was located. If there wasn't a public static method calling this private static one, the refactor ends there.

    Personally, I recommend against both public static and private static (I think they produce needless work) however only public static meets the bar for a style guide.

drost 4 years ago

> Every public static method can trivially be replaced with a non-static implementation at the cost of a single stack pointer bump.

What about static factory methods?

  • divyekapoorOP 4 years ago

    Re: static factory methods - Those are called just once (so perf isn't really the point).

    With respect to non-perf reasons, Factories should also be non-static. Here's why: 1. Factories that are part of a dependency injection framework (Guice, Dagger, Spring) are actually "objects" that the DI framework is moving around. These DI frameworks already enforce object creation (see: https://github.com/google/guice/wiki/GettingStarted for example -- everything is an object). 2. public static factory classes have significant disadvantages (eg. depending on another factory class is a direct, "hardcoded" brittle dependency). Avoiding this is straightforward - create factory objects (aka Modules) and register it with the DI framework (the only public static "singleton" object) - when an object is needed, ask for it and the DI framework will give it to you (implicitly through the factory).

divyekapoorOP 4 years ago

private static is fine. Just don't use public static - it leads to virulent refactors and brittle dependencies.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection