Should Java methods be static by default?

后端 未结 23 1220
既然无缘
既然无缘 2020-12-04 09:24

Say you\'re writing method foo() in class A. foo doesn\'t ever access any of A\'s state. You know nothing else about what foo does, or how it behaves. It cou

23条回答
  •  眼角桃花
    2020-12-04 09:54

    Do think hard before creating a static method, but there are times when they are a good solution.

    Joshua Bloch in "Item 1: Consider Static Factory Methods Instead of Constructors" in Effective Java makes a very persuasive case that static methods can be very beneficial. He gives the java.util.Collections class's 32 static factory methods as an example.

    In one case, I have a hierarchy of POJO classes whose instances can be automatically serialized into XML and JSON, then deserialized back into objects. I have static methods that use Java generics to do deserialization: fromXML(String xml) and fromJSON(String json). The type of POJO they return isn't known a priori, but is determined by the XML or JSON text. (I originally packaged these methods into a helper class, but it was semantically cleaner to move these static methods into the root POJO class.)

    A couple of other examples:

    • Using a class as a namespace to group related methods (eg, java.lang.Math).
    • The method truly is a private class-specific helper method with no need to access instance variables (the case cited here). Just don't sneak a this-equivalent into its argument list!

    But don't use statics unthinkingly or you run the danger of falling into a more disorganized and more procedural style of programming.

提交回复
热议问题