I submitted an application I wrote to some other architects for code review. One of them almost immediately wrote me back and said "Don't use static
. You can't write automated tests with static
classes and methods. static
is to be avoided."
I checked and fully 1/4 of my classes are marked static
. I use static
when I am not going to create an instance of a class because the class is a single global class used throughout the code.
He went on to mention something involving mocking, IOC/DI techniques that can't be used with static code. He says it is unfortunate when 3rd party libraries are static because of their un-testability.
Is this other architect correct?
update: here is an example:
APIManager
- this class keeps dictionaries of 3rd party APIs I am calling along with the next allowed time. It enforces API usage limits that a lot of 3rd parties have in their terms of service. I use it anywhere I am calling a 3rd party service by calling Thread.Sleep(APIManager.GetWait("ProviderXYZ"));
before making the call. Everything in here is thread safe and it works great with the TPL in C#.
static
is fine;static
fields need to be treated very carefully – Marc Gravell Aug 13 '12 at 22:00public class CountedInstance { private static _count = 0; public static int Count {get{return _count;}} public CountedInstance() { _count++;}}
– Aug 13 '12 at 22:22static
methods in C# are a necessary feature, because it's the only way to write free functions in C#. Aclass
that is created to hold free functions should be markedstatic
to express the fact that it should not be instantiated. – Laurent LA RIZZA Sep 08 '14 at 09:16Thread.Sleep(APIManager.GetWait("ProviderXYZ"));
is a bad idea because how will you stub out the provider for tests? Also what's the advantage ofAPIManager.GetWait("ProviderXYZ")
overAPIManager.WAIT_FOR_PROVIDERXZYZ
? – user253751 Oct 20 '17 at 05:23