开发者

What are global states? How do they affect testability and how to avoid them?

List down the various global states like global variab开发者_JS百科le, singleton object etc.,

I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?


Global variables and singletons are so similar from the testability viewpoint that they don’t have to be treated separately. Good OO design should be like bricks of Lego that fit together to create the resulting system. The main problem with globals is that you lose isolation. When you access your collaborators using globals or singletons, the classes are no longer separate bricks that you can easily take and reorganize, use in isolation or reuse in another project. When you take some class that depends on globals, you drag the rest of the design with it. In testing this makes problems because you have to take extra steps to cut the connections from your class to its collaborators, so that you can test it in isolation. (I’ve written more about this on my blog.)

A nice solution to the problem is supplying the class dependencies from the outside. You simply introduce some kind of mechanism (maybe a simple class) that will take all the isolated bricks and connect them into the object graph that makes up your application. This is what Inversion of Control and Dependency Injection is all about.


Start by reading singletons are pathological liars.


There are no various global states. Either something is global state or it isn't. The Singleton anti-pattern just removes various initialization headaches, but it's just the same as a global variable.

How to avoid global state? Make some local state and pass a reference or pointer to it around. In the vast, vast majority of occurrences, global state is needless. There are some instances of necessary global state, like the heap, but they're very rare and if you need to ask, then you almost certainly don't know enough to know when it's correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜