Step 3: Improving the Count Property ImplementationAs always let's start with our current task list:
Let's tackle item 7. In order to create a non-empty stack we need a mechanism to put an element onto the stack. Our next test may therefore look as follows:
1: [Test] 2: public void CountWithOneElement() { 3: Stack stack = new Stack(); 4: stack.Push(5); 5: Assert.Equals(1, stack.Count); 6: } This won't compile as the Push method doesn't exist yet. Also, whether you use an integer to push onto the stock or whether it is 5 doesn't matter. Any object - in the widest sense - will do for now. The simplest Push implementation might look as follows: 1: public void Push(int p) { 2: } Let's compile and run the tests. This is not quite a surprise. The question is now what we do with the implementation. To pass this test we could change Count to return 1, but that would fail CountWithEmptyStack. So what to do? Maybe we have reached the point where "fake it 'till you make it" doesn't work any longer. But wait.... What about the following (changes/additions in bold type face): 1: namespace StackLib { 2: public class Stack { 3: public Stack() { 4: } 5: public bool IsEmpty { 6: get { 7: return true; 8: } 9: } 10: public int Count { 11: get { 12: return _count; 13: } 14: } 15: public void Push(int p) { 16: _count++; 17: } 18: private int _count = 0; 19: } 20: } Let's run the tests. - They pass! So we can tick off two items from our list, but we need to add an item that makes sure that when we call Push first and the Pop the same object is returned:
To be continued... Further MaterialYou can find a much more detailled introduction in this style in Kent Beck "Test Driven Development: By Example"
|
Sponsors:
|
||||||
Copyright © 2002-2008 by Agile Utilities NZ Ltd. All rights reserved. Site design by Andreas Weiss. This site is protected by bot traps. |