Showing posts with label threads. Show all posts
Showing posts with label threads. Show all posts

Thursday, January 13, 2011

Why static methods and variables complicate everything

My most useful sources for this were:
rancorbeast
blog by misko
blog by jagregory

Unit testing depends on being able to set the variables which part of your program uses, and then see whether the part of your program which you're testing uses them correctly. But if what you're testing requires manipulating or reading static variables, the test cannot be written efficiently, because the static variables are static and hold their value for the entire run of the program. Because having static variables makes unit testing difficult or impossible, it is less likely that a programmer who uses static variables will use unit tests. This implies that their test may break without the programmer knowing about it, and that the programmer might not follow other best practices, since they don't follow the one about testing.

Static methods make code harder to change, because other parts of the code may rely on the static methods being static. This coupling makes your design difficult to change. Having a design that is easy to change (refactor) is good, because then you can refactor it to make it better. Static methods imply the presence or incoming presence of bad design because the programmer has not given thought to making the program easy to add functionality to, and to refactor. If refactoring and/or added functionality is tried in the future, the code may begin to accumulate workarounds to the static methods. This will make the code longer and more complicated than it needs to be.

Static variables make thread safety almost impossible to achieve because they are a shared state, which is almost always bad. Static variables, and anything they access, can be accessed concurrently by different threads unless you take pains to synchronize access to them. While you can guard them, if you have too many of them your design is harder to validate because the locking will be more complicated. If there are enough of them, then performance will suffer because of different parts of the program waiting for other parts of it to wait for locking to resolve.