Image by Török Gábor (nyuhuhuu) on Flickr
Musings on mutable stateIn this video, Misko Hevery argues that global state is bad from a testability point of view. Global state resides in global variables and singletons. They make the API deceptive in the sense that when you repeat the same calls, you can still expect different results because the results depend on both the object's state and on global state which is not obvious to someone reading the code. After seeing that video it occurred to me that the exact same argument applies to mutable data members in a class. They are a kind of "globally available state inside a given object instance" that can make the API deceptive. Consider the following code: As you can see the "Display" method changes internal state of a TestClass instance, and causes different results for every new API invocation. So the arguments Misko Hevery use seem valid ones, but applying them rigorously has deep implications: it seems to me it really argues against side-effects and thus in favor of purely functional programming. By now I have seen a fair share of hard-to-trace bugs caused by side-effects of method calls, so it struck me that perhaps it is possible to find some compromise between mutable state and purely function programming (and it's really just that: an idea resulting from a brainstorm; I haven't actually used it in production as I fear it may have significant performance implications). If you have additional insights into the matter, feel free to comment.
Proposal: Forbid non-const methods.