Which is better? private static vs private
In开发者_运维技巧 this code sample:
public class SuperMan {
private static bool IsProper(decimal x) {
return x > 31.0m && x < 45.0m;
}
public bool CheckStuff(string a, string b, string c) {
// lots of code, some of which introduces a variable x
return IsProper(x) && /* other conditions */;
}
}
Should IsProper(..) be a 'private static' or a 'private'. Assuming:
- IsProper(..) doesn't need to access any instance state (even in future.)
- We are not concerned about performance different between the two options (one of the things we should never do is guess about performance without actual measurement and optimize without the need.)
It could be static, since it doesn't seem to have to do anything with the SuperMan class nor its members. But you should ask yourself if that function belongs in that class at all.
If you're checking if decimal is a proper decimal for SuperMan, then it belongs there. But I wouldn't make it static in that case. Chances are that you will later need to replace that constant values with SuperMan properties.
Reasons to make IsProper an instance member:
- IsProper needs another implementation in an inherited class
- IsProper might need access to members in the future
Reasons to make IsProper a static member:
- You have a small performance penalty for making it an instance member.
- If you only need to create an instance of the class to call IsProper, you would make it a static
Static methods can be a bit faster, but on the other hand sometimes it can be harder to refactor.
精彩评论