If you've ever implemented GetHashCode you probably did it the way suggested in MSDN which is using XOR. And if you use R# you might have seen that it generates a different GetHashCode using prime numbers. So what should you do? I think there are three properties you want to aim for when it comes to implement GetHashCode, in order of importance.
Given all this it turns out that the approach R# uses is pretty powerful into achieving all these goals. But the best possible approach is to use pick an algorithm that is suitable for your data. A few examples:
If you want to read more about a number of different hashing options there a is a pretty good list here with lots of good information.
This was recently sent to me and anybody who has worked at Microsoft knows that a lot of teams (if not all) have a lot of meetings and do a lot of communication over email. The essence of the article linked is that people who's work mainly consists of meetings need to understand that people who contribute mostly outside meetings will be less effective if their day is chopped up with a bunch of meetings. I think it is hard to argue that this is wrong since yes; meetings do take time from other things and with less meetings more things tend to get done. And if you have a few meetings in a day it makes sense to try to have them back to back I think.
However I believe meetings is the less disruptive thing during my work day since meetings are scheduled. Every time I walk into somebody's office to discuss something without booking a meeting I interrupt whatever they are doing and vice versa. But that does not mean I want to batch them up. Most of the time a short interruption is not that bad I think and if it means somebody else on the team quickly can be unblocked without writing long emails and/or booking meetings I think the team as a whole will be more productive. And then there is email notifications, instant messages, phone calls etc that cause interruptions. So I think it is more important to make sure the team can handle interruptions and defer them until they can be handled. My favorite method for that is the Pomodoro technique!
I am a believer in the Pomodoro technique since I do not think you can be productive and in the zone for hours. I do think the brain need some time to process thoughts in the background to quickly find solutions to problems. And I've felt the feeling of accomplishment when you know exactly how much you've gotten done in a day. The manager's vs maker's schedule article is good and worth reading but IMO it's just the tip of the iceberg and not addressing main problem. But it makes an important point that should not be forgotten.
The IDisposable is probably one of the most abused interfaces in .Net. Except from all the cases where you actually have an unmanaged resource you need to release I've seen it being used a lot of times (including by myself) just to guarantee some code is executed immediatly when a variable go out of scope. I've used this in test utilities to make sure certain validation happens before the test execution ends but I've also seen this used in non-test code. The people who like to use IDisposable probably (like myself) have some experience from C++ and using smart pointers or similar there. I wish there was a similar construction in .Net where I could force execution of a certain method on an object immediatly when it goes out of scope if (and only if) I explicitly want that. Kind of an IDisposable that does not generate FxCop warnings when not disposed properly...
Anyway, the best guid I've seen so far on how to actually implement IDisposable can be found here. Follow those guidelines and do what I do; stop abuse IDisposable constructs just because you think they make the code look neat.
I just wanted to make sure you did not miss this article describing a mechanism to pause asynchronous processing. Just like the article state that this came out of a problem encountered in the UI World I think this is something I would not expect to see a lot outside the UI world. But it could be used for processing items in a work-flow at different priorities; i.e. pausing less important work in favor of more important work.
And when you're done reading about the PauseToken you should definitely read this one with some common problems people encounter.
It's been a while since I last looked at Rx and I must confess that my first impression was that the amount of possibilities to do the same thing and all the extension methods was overwhelming at start. But like with any new framework you learn you'll settle for a few to solve your most common problems after a while. But then I never saw a really compelling reason for using Rx and it has been very rare among my friends and colleagues to use Rx. So last week I was excited to read that Netflix uses it a lot and I'm looking forward to read more about how they uses and what they've learned along the way.
This was brought to my attention and I was blown away by the fact that somebody would mark classes as TestClass without any tests in them just to reuse some setup code. And that they then make any assumptions on in which order the methods are called. If you really want to do that the constructor is a great place for that and that is also why prefer xUnit.Net which does not have a TestInitialize through attributes but actually use the constructor instead. But I actually think it is better if you're more explicit about how you initialize your tests than relying on an order just defined by the order in which base classes are called by default. In general I believe the consensus is that composition is superior to inheritance when it comes to code reuse which is why you should not put yourself in a situation where you rely on execution order between base and child classes.
Recently I was asked about a specific scenario when some code was being converted into using TAP and this was code that already used tasks. Since the existing code used the "IsFaulted" property a lot I came up with this little extension method making it easy to see if a task failed or not using the await keyword but without adding a lot of exception handling.
1: public static Task<bool> WaitAsync(this Task task)
3: var tcs = new TaskCompletionSource<bool>();
5: t => tcs.TrySetResult(!(t.IsFaulted || t.IsCanceled)));
6: return tcs.Task;
So why avoid exceptions? Well I think that is a separate topic but a few short observations; exceptions have some performance penalties so you don't want to use them for common errors and some people think exceptions make it harder to follow the flow of the code. Whatever you think about all that I think you'll find the WaitAsync method useful more or less often.
Time for my 2012 according to this blog's statistics. As last year we'll start of with the five most read posts:
For the fourth year in a row native code coverage reports is the most read article I have on my blog. I was sad to see Object calisthenics not make top five. Another interesting thing though is that Ten commandments of egoless programming was linked by some popular sites which made it into the top. It in its turn links to the Viking laws which turned out to be much more popular than the commandments post. Exactly the way I feel. The top ten search terms to land on this blog in 2011 were (2010 ranking within parenthesis):
Once in a while I need to convert one object from one type to another because they represent slightly different views of the same data but they do not share a common parent. An example would be an object used internally representing some complex state for something (let us call it FooComplex) and someting simple you just want to return in an API (let us call it FooSimple). So how do I convert between these? There are several options:
fooSimple.ToComplex() and fooComplex.ToSimple()My first option is to att a member function to each of the classes that converts to the other. The first obvious downside with this is that these classes now both need to know about eachother which is probably really bad since they might be in different assemblies. It also means that when I need to add a property in both classes I need to also change the converters in two different files.
Explicit castsYou can also implement explicit cast operators which is really just a variant of the option above. Some may argue that it is better since it uses a language feature to illustrate that you convert between two classes. While that is true I think it will be confusing since cast operators are typically used to change the type when the two types actually have an inheritance relationship. So casting between two logically related but in practice seperate types might actually be more confusing than using ToXxx methods.
Partial classesTo get around the downside of having ToComplex and ToSimple in two different code files you can always make FooSimple and FooComplex partial classes. But this might not always be possible.
fooSimple.ToComplex() and FooSimple.FromComplex(FooComplex)To get around the problem of two way dependencies and needing to implement the conversion in two different classes (and files) you can just replace one direction with a static FromXxx method. This works pretty well but now you have two different patterns for converting depedning on direction (To vs From).
Extension methods to the rescue!However if you make your ToComplex and ToSimple methods be extension methods I think you get the best of all worlds; Both directions in the same file, same pattern and not using explicit cast operators. I also like to call them AsXxx rather than ToXxx to indicate there is some transformation happening.
I couldn't resist to create a method to deal with a scenario even less common than WhenSome. The crazy scenario here is that you have N tasks of type Task<T> and you want to return when a random task completes. The easiest way to do this is to just pick a random task and wait for it like this:
1: public static Task<T> WhenRandom<T>(params Task<T> tasks)
3: var random = new Random();
4: return (from task in tasks
5: orderby random.Next()
6: select task).FirstOrDefault();
However what if you want to be able to cancel the WhenRandom call you need to be a little more creative I guess:
8: public static async Task<T> WhenRandom<T>(CancellationToken cancellationToken,
9: params Task<T> tasks)
11: var random = new Random().Next(0, tasks.Length);
12: var remainingTasks = new List<Task<T>>(tasks);
13: while (remainingTasks.Count > 0)
15: await Task.WhenAny(remainingTasks);
16: for (int i = 0; i < remainingTasks.Count; i++)
18: if (remainingTasks[i].IsCompleted)
20: if (random-- == 0)
22: return await remainingTasks[i];
32: return default(T);
In this last version I don't pick a random task and wait for it but I rather pick a random completed task, i.e. given the same random number the order in which tasks complete will affect which task is returned.