While coding for the MIX challenge, I was trying to find as compact as a form as possible to write code. And given the repetitions, I had created a helper class (named H), see below:
static class H
{
public static void For(int i, Action<int> a) { for (var x = 0; x < i; x++) a(x); }
public static void For(int o, int i, Action<int> a) { for (var x = 0; x < i; x++) a(x); }
public static void For<T>(IEnumerable<T> l, Action<T> a) { foreach (T i in l) a(i); }
public static R While<R>(R i,Func<R,bool> e, Func<R,R> f) where R: class {while (e(i)) { i = f(i); } return i; }
public static T GetV<T>(Object c, DependencyProperty prop) { return (T)((DependencyObject)c).GetValue(prop); }
public static void SetV(Object c, DependencyProperty prop, Object v) {((DependencyObject)c).SetValue(prop, v); }
public static T New<T>(T v) where T : new() { return new T(); }
public static T New<T>(T v, params Object[] a) { return (T)Activator.CreateInstance(typeof(T), a); }
}
This helped in reducing the characters count, for example, a double loop to initialize 15x15 squares on the board could be written like this:
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
Board.Add(new Square(j, i));
}
Now, using the helper class (H) the same could be written like:
H.For(15, i => H.For(15, j => Board.Add(new Square(j, i))));
LINQ and it's related features obviously are a big help in writing compact code, one of them I use extensively is automatic properties. However, as of the current version of .NET we can't initialize them, which meant writing thing like this.
public ObservableCollection<Letter> Bag { get; set; }
// and to initialize
Bag = new ObservableCollection<Letter>();
Again, for the sake of brevity I wrote the same thing with the helper as:
public ObservableCollection<Letter> Bag { get; set; }
// and to initialize
Bag = H.New(Bag);
The interesting thing is, and which I've not seen used anywhere else is, in using the generic type on the static 'New' method with the 'new' constrain and a dummy parameter - the dummy parameter ensured we didn't need to specify the type needed and also without which the compiler wouldn't be able to infer the type.
Obviously these are not production quality coding practises, rather just interesting ways to keep things under 10K.
Posted by Rishi on 05-Feb-09 9:56 PM, 11 Comments