Reviewing the Simple Stack Representation
The techniques in this article require you some familiarity with the stack representation. When I was at Michigan State University as an undergrad we had to implement stacks, and they seemed very hard at the time. Beginning programmers will benefit from a quick review of stacks here; they are easily devised in VB6 from a collection and can be very useful.
A stack is a data structure that follows a last in first out rule
(pronounced LIFO) supported by two basic behaviors called push
. To add something to a stack you push
it, and to remove something you pop
it. The last thing you added by calling push
will be the first thing you get when you call pop
. For example, if we have a stack of integers and pushed 1, 2, 3, 4, 5, and then called pop
five times we would get 5, 4, 3, 2, and 1. Hence, stacks are good data structures for back tracking and, interestingly enough, are fundamental to the way your CPU tracks the path your code takes as it runs.
However, a collection can easily be a stack simply based on where you insert at and remove items from. By inserting and removing at the end of the collection very little support code is needed to devise a stack. For example, to implement push call collection.Add; to implement pop call collection.Remove(collection.Count). Simply using the tail end of the collection as the front of the data structure effectively converts a collection into a simple stack. You can see an example of this in Listing 2 in the PushStack and PopStack methods.
Finally, there are several excellent revisions you could make to the example code in this article. Moving the collection, PushStack and PopStack to a Stack class would clean up the form and make a nice general Stack class. Improving the design of code like this is called refactoring. Learning to refactor code is an excellent complement to learning about patterns. You can learn more about Refactoring in Martin Fowler's Refactoring: Improving the Design of Existing Code from Addison-Wesley and more about patterns in Erich Gamma and company's book Design Patterns, also from Addison-Wesley.
The Quality of Your Tools
In this article you learned about a tool, the Command behavior pattern. If you find that invoked behaviors need to be undoable, or that your invocation code is becoming too complex then I hope you remember this simple but powerful tool. Other concepts discussed hereUML, patterns, and refactoringthese, too, are tools.
There is no one perfect tool for every job. (Remember the adage 'if all you have is a hammer then every problem is a nail'?) My dad used to say that a craftsman is known by the quality of his tools. In other words, the more tools you have the more you can build.