Should Java methods be static by default?

后端 未结 23 1232
既然无缘
既然无缘 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:44

    Interesting question. In practical terms, I don't see the point in making class A's private helper methods static (unless they're related to a publicly-accessible static method in A, of course). You're not gaining anything -- by definition, any method that might need them already has an instance of A at its disposal. And since they're behind-the-scenes helper methods, there's nothing to say you (or another co-worker) won't eventually decide one of those stateless helpers might actually benefit from knowing the state, which could lead to a bit of a refactoring nuisance.

    I don't think it's wrong to to end up with a large number of internal static methods, but I don't see what benefit you derive from them, either. I say default to non-static unless you have a good reason not to.

提交回复
热议问题