One of the features that I really like in .NET 3.5 is Func<T>. For those of you who aren't familiar with Func<T>, it is simply a delegate. While I generally haven't seen many people who embrace delegates, it may be due to my limited exposure to different programming teams over the past few years. Generally speaking I see frameworks latch on to many of these new features much sooner than the average web application. In this post I want to show that Func usage is simple and within reach for you in your application(s).
As a user I can have a temporary password emailed to me if I forget my own, so that I can regain access to my account.
I've seen various implementations of this over the years and each one seems to want to generate some randomized set of digits and characters with the possibility of special characters in there. Here's a possible implementation I've made leveraging the use of Func. Take a look and then I'll break it down.
1: public string CreateTemporaryPassword(int length)
2: {
3: Func<Random, char> randomNumber = rnd => (char) rnd.Next(48, 58);
4: Func<Random, char> randomCharacter = rnd => (char) rnd.Next(97, 123);
5:
6: var funcArray = new[] {randomNumber, randomCharacter};
7: var chars = new char[length];
8: for (int i = 0; i < length; i++)
9: {
10: var index = random.Next(0, funcArray.Length);
11: chars[i] = funcArray[index](random);
12: }
13:
14: return new string(chars);
15: }
Nice, isn't it? Even if you don't understand Func yet, the code above should be relatively easy on the eyes. It's not overly long and its brevity implies a certain level of simplicity that welcomes you to come and understand what it's doing rather than scaring you off. Let's break it down by line by line:
Right now I have two Func's defined, one for random characters and another for random numbers. To change the sequence I could create another Func and simply add it to the array and voila, I've got another character generation option. I only therefore have to touch two lines, the line where the new Func is defined and the line which adds the Func to the array, line 6. I'm sure there are other ways to add extensibility points, but really how often are you going to want to change your password generation scheme?
If Func seems odd to you make a commitment to use it. As you use it you'll find that it really isn't that bad and pretty soon you'll be getting down with da Func all the time.
This blog contains the thoughts and discoveries of Tim Barcz, a technologist with a interests in computer programming technologies.