I created a private validation method for a certain validation that happens multiple times in my class (I can't store the validated data for various reasons). Now, ReSharper suggests that the function could be made static. I'm a little reluctant to do so due known problems with static methods. It would be a private static method. My question is, can private static methods cause similar coupling and testing problems like public static methods? Is it a bad practice? I would guess not, but I'm not sure if there is a pitfall here.
|
|
I would think: "Do I need to test this?" If your method is private anyway, meaning you don't want to unit test the logic in the method itself, then as far as testability and maintainability are concerned your class is a black box either way, the inner workings of your class are its business and its alone. Refactoring will not be affected either, which is also something to consider. So, in my opinion: No, making a "private" method "private static" will have no long term ramifications whatsoever. |
|||
|
|
|
Private static methods are the easiest thing possible, from my point of view. DataIn -> Method -> DataOut There are no dependencies on external objects, no side effects. Why do you consider them bad? |
|||||||
|
|
Testing classes that use public static methods can be hard, as it's not (particularly) easy to stub / fake / mock out the static methods. Instance methods, on the other hand, can be mocked easily, especially if they're virtual or satisfy an interface. However, I can't see any reason to not use private static methods. Indeed, there's a slight performance benefit, as you don't need an instance of the class to occupy memory. On the other hand anything static is a bit of a code smell. Is this actually a "helper class"? Could it be that the method could more usefully reside on one of the classes passed as a parameter? The answer to those questions is often "it's fine as a static" but it's worth remembering. |
|||
|