Code Analysis: Global State

Global mutable state by itself can make a program harder to work with because instead of  having a call tree that’s simply a tree structure, you end up with more of a graph structure.  Any given point in the program that interacts with the global state can be effected by any other point in the program that interacts with the same global state.  You can get the same issues that you do with mutable state except the issues aren’t isolated to a single sub call tree of the program.

But what happens if you isolate the global state behind an abstract data type so that the complexities of interacting with global state are managed by the abstract data type?  Well there’s a reason we talked about abstract data types in the last blog post.  If you have a strong abstract data type, then you shouldn’t encounter any issues (this is assuming that your strong data type also takes care of multi-threaded situations properly).  However, things get much harder if you’re dealing with a weak abstract data type.


When you have global state being interacted with at different parts of your program, you can linearize the tree structure of your call tree into a sequence of events.  With a weak abstract data type, this sequence must be in the correct order so that you can avoid invalid situations.  Having to go through your program to determine if the sequence is correct can be difficult and time consuming.  Additionally, any program with some sort of conditional code execution can potentially have multiple paths of execution.

If your weak abstract data type has API calls that occur in different conditional parts of your program, then instead of needing to understand the linear form of your program you will have to understand all possible linear forms of your program.  This will be much more difficult and may not even be possible.

Simply avoiding weak abstract data types may not be an option.  Things like sockets and file pointers are all weak because you cannot read data from the object when it’s closed.  Some constructs are legitimately weak and that’s okay.  It just means that you need special attention when you are using them to ensure that you do not end up in situations where the program becomes overly problematic.


Next time, exceptions.

The following two tabs change content below.

David Inman

Latest posts by David Inman (see all)

Add your comment

Your email address will not be published.