Saturday, July 18, 2009

Why write programs that don't modify variables?

Slews of bugs happen because variable have values you aren't expecting. To minimize this class of bugs I use a technique a lot of people find surprising. I try to only assign and never modify variables. In C++, I make almost all my variables const. C++ people are now saying -- Um if all your values are const how do you write a for loop? In C++ I can't help myself, I'm stuck with a variable modification eg:

for (size_t x=0;x<6;x++) printf("%d",x)
In python the for loop naturally iterates over a sequence so you don't need to modify a value:
for x in range(6): print x
In C#, you can use either the C++ syntax or a more python syntax via foreach:
for (int x=0;x<6;x++) Console.WriteLine(x);
or
foreach (var x in Enumerable.Range(0,6)) Console.WriteLine(x)
I use the foreach syntax which people initially find confusing. But its value starts to shine when using non zero starting values. Assume I need to generate 113 numbers starting at 27. Which statement do you find expresses it better.
for (int x=27;x<=139;x++) Console.WriteLine(x)
or
foreach (var x in Enumerable.Range(27,113)) Console.WriteLine(x)

1 comment:

Adam said...

It seems more reasonable to say that many bugs happen because values aren't what you expect. Adding more variables doesn't change the number of distinct values you need in your program, and if you need to store changing state, you have to model that no matter what. Either way you have to protect the integrity of your state.