Posts

A data flow helper class

One problem I encounter when processing lists is exception handling. I prefer to write code that "chains" calls transforming the data: var results = list .Select(DoThing1) .Select(DoThing2) // ... .Select(DoThingN) .ToList(); The problem with something like this is that, if any of the calls throws an exception, processing stops for the whole list. Handling that requires that I move the "chain" to a new method and handle exceptions there: var results = list.Select(InnerMethod).ToList(); // ... private ResultN InnerMethod(Input input) { try { var r1 = DoThing1(input); var r2 = DoThing2(r1); // ... var rn = DoThingN(rn_1); return rn; } catch(Exception ex) { // do something with ex, like logging return ?? // can't throw, I want to continue processing the rest of the list } } Now I have two problems :) One is that the code just looks uglier, so maybe most p...

Retry algorithm

Retry with exponential back-off Update on July 24, 2016: I just discovered Polly , which does this and more a lot better. I think this is an useful class so I'm just going to leave it here. (I'm annoyed by the duplication between Retry and RetryAsync but I haven't been able to remove it.) public interface RetryPolicy { T Retry<T>(Func<T> func); void Retry(Action action); Task<T> RetryAsync<T>(Func<Task<T>> func); Task RetryAsync(Func<Task> action); } public class RetryPolicyWithExponentialDelay : RetryPolicy { // ReSharper disable once InconsistentNaming public Func<double> GetRandom = () => RND.NextDouble(); // ReSharper disable once InconsistentNaming public Action<int> Sleep = timeout => Thread.Sleep(timeout); public RetryPolicyWithExponentialDelay(int maxCount, TimeSpan initialDelay, TimeSpan maxDelay) { this.maxCount = maxCount; this.i...

Stupid code fragments, part two

Probabilities are hard. As an example, there's a known puzzle: a family has two children; if one of them is a girl, what is the probability that the other one is also a girl? The answer, un-intuitively, is not 1/2 but 1/3. There are various explanations but – as with the Monty Python puzzle years ago – I wanted to write code to check it out, so I wrote the following using LinqPad: void Main() { var rnd = new Random(); // Generate a random set of families with two children; true means girl, false means boy var all = Enumerable.Range(1, 10000).Select(_ => new Pair(rnd.Next(2) == 0, rnd.Next(2) == 0)).ToList(); // Extract only the families with at least one girl var oneGirl = all.Where(it => it.First || it.Second).ToList(); // Out of those families, how many have two girls? The result should be 1/3rd var otherGirl = oneGirl.Where(it => it.First && it.Second).ToList(); Console.Wri...

Stupid code fragments, part one

I just discovered a surprisingly simple (and obvious in hindsight) algorithm for calculating the week index of a given date. For example, April 15th is in the 3rd week (or the 3rd Tuesday of the month). I was going to do the usual thing and just Google for it but then I realized that the solution is extremely simple: private static int GetWeekPosition(DateTime date) { // the position of the given date is how many times I can subtract 7 days (go back one week) and still be in the same month // in other words, it's the integer part of (day / 7) return date.Day / 7; } (I am returning a base-zero result, but you can of course add 1 if you need it.) I realize this is not the answer to the Universe or anything but I thought it's interesting.

Science

I've long used the expression "real science, so called because it can only be found in books and movies". From a talk at Pycon 2014 : The ideals reality of science: The pursuit of verifiable answers highly cited papers for your c.v. The validation of our results by reproduction convincing referees who did not see your code or data An altruistic, collective enterprise A race to outrun your colleagues in front of the giant bear of grant funding H.T to Daniel Lemire .

Telerik components

I am working on some projects where I am forced to use the Telerik components. They are, without a doubt, the most overpriced junk I've ever had to work with. It pains me that people pay a lot of money for them just because they look pretty. (I am trying to remember ONE issue where the Telerik components were involved and I haven't had to fight them. It's just not coming to mind.)

Avoid boolean parameters

Here's an example of a method in a sim. This started out as a simple method: all days are the same in our simulation, so the method just prints out some activities: void SimulateDay() { Console.WriteLine("Wake up."); Console.WriteLine("Eat breakfast."); Console.WriteLine("Watch TV."); Console.WriteLine("Eat lunch."); Console.WriteLine("Watch TV."); Console.WriteLine("Eat dinner."); Console.WriteLine("Go to sleep."); } Ok, so not much of a life, but this article is supposed to be about programming. :) A new requirement comes up: Sunday should be different. Well, almost; it's actually the same as the other days with a single difference: instead of watching TV, the sim goes to church on Sunday mornings. No big deal, we can augment the method with a boolean parameter: void SimulateDay(int isSunday) { Console.WriteLine("Wake up."); Console.WriteLine(...