Article 6VDFC CodeSOD: Every Day

CodeSOD: Every Day

by
Remy Porter
from The Daily WTF on (#6VDFC)

There are real advantages to taking a functional programming approach to expressing problems. Well, some problems, anyway.

Kevin sends us this example of elegant, beautiful functional code in C#:

//create a range of datesList<DateTime> dates = Enumerable.Range (0, 1 + settings.EndDate.Subtract (settings.BeginDate).Days).Select (offset => settings.BeginDate.AddDays(offset)).ToList();foreach (DateTime procDate in dates){/*.snip.*/}

If you're not sure what this code does, it's okay- Kevin rewrote it and "ruined" it:

DateTime procDate = settings.BeginDate;while(procDate <= settings.EndDate){/*.snip.*/procDate= procDate.AddDays(1);}

The goal of this code is simply to do something for every day within a range of dates. These two approaches vary a bit in terms of readability though.

I guess the loop in the functional version isn't mutating anything, I suppose. But honestly, I'm surprised that this didn't take the extra step of using the .ForEach function (which takes a lambda and applies it to each parameter). Heck, with that approach, they could have done this whole thing in a single statement.

proget-icon.png [Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments