开发者

To static or not to static [duplicate]

This question already has answers here: What is better? Static methods OR Instance methods (7 answers) Closed 9 years ago.

I really like to use static metho开发者_运维问答ds (especially for helpers classes). But as static methods are not stubbable, eventually they are a bad practice, aren't they? So I have to choose between static methods usage convenience and testability. Is there any compromise?


It depends on what the static methods do.

Is it something that really has to be stubable? Like data access, long running operations etc. or is do you mean helper methods like .ToSlug()?

If it's the former case, I'd make them instance methods to increase testability / speed of tests.

If it's the latter, I'd leave them static and just verify their correctness.


If you can guarentee that the static method always returns the same result for a given input and the only reason they are there is helper methods (converting or transforming input -> output without sideeffects) I don't see a problem. For extra kicks, you could make them extension methods (as of c#3.0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜