Guru Tips: Making ToString Useful, Plus Not Getting Fooled by Closure
Julian Bucknall is the Chief Technology Officer at DevExpress. I asked him if he had a tip for .NET developers. Julian said he had two (and that doesn't count the bonus he threw in).
First Tip: ToString() is your friend. When the CLR team wrote System.Object, they included the very minimum of methods needed for all objects. All of them are 100 percent vital, no fat here. One of them is ToString(), the method that provides a human-readable string of the important properties in your class -- especially important for debugging. The default is boring and uninformative: you should work on creating your own overrides for your own classes. Your fellow developers will thank you, since they won't have to go spelunking through your class' properties when debugging -- they can just call your ToString method.
Bonus Asp.Net Tip: Do the same with the toString method for your prototypes in JavaScript. Much more informative than getting back the default "[object Object]'.
Second tip: Closures capture variables, not values. Writing anonymous functions is great fun, but beware: If an anonymous function captures a local variable, it captures the variable, not the current value of that variable at the time the anonymous function is defined.
This code has two anonymous functions, both of which use the variable called constantValue. The code sets constantValue before defining each function, but, when the functions are executed it's the latest value of constantValue that's used:
delegate int AddConst(int x);
class Program {
static void Main(string[] args) {
var constantValue = 7;
AddConst AddSeven = (x) => { return x + constantValue; };
constantValue = 2;
AddConst AddTwo = (x) => { return x + constantValue; };
Console.WriteLine(AddSeven(4)); // result: 6 !?!
Console.WriteLine(AddTwo(4)); // result: 6
Console.ReadLine();
}
}
Here, the AddSeven and AddTwo functions aren't capturing the current value of constantValue when the functions are created; they're capturing the variable. When the functions are run, they use whatever the value of currentValue is at the time of execution. Beware!
Posted by Peter Vogel on 02/16/2012