Article 5B14X CodeSOD: To Coalesce a Null

CodeSOD: To Coalesce a Null

by
Remy Porter
from The Daily WTF on (#5B14X)

As we all know, managing null values is its own challenge, especially when you're working in a functional style. So as languages like .NET add functional approaches like LINQ extension methods, they also add null coalescing operators and nullable types, making it easy to pass values around without getting surprised by an unexpected null.

Unless you're whoever wrote the code that Abbie found, because they've managed to keep some surprises.

List<SomeObjects> someObjects;using (var session = dataStore.OpenSession()){ someObjects = session.Query<SomeObjects>().OrderBy(s => s.PrimaryKey).ThenBy(s => s.EventDateLocal).ThenBy(s => s.SystemTransactionDateTimeUtc).ToList();}return someOtherCollectionOfObjects .GroupJoin(someObjects, o => o.EventDates.PrimaryKey, s => s.PrimaryKey, (o, s) => { var sList = s as IList<SomeObjects> ?? s.ToList(); return new { //omitted }; })

The submitter anonymized the class names and variable names a bit, so it's hard to see exactly what the intent is, but we can still spot the "odd" choices. The goal is to take our someOtherCollectionOfObjects as the "outer" side of a join, and someObjects is the "inner". Each "outer" element will get matched with all of the "inner" elements based on primary keys.

So the first "odd" choice is that when we fetch our inner objects, we sort them. someObjects is sorted first by primary key, then by event date, then by the transaction datetime. That first sort absolutely doesn't matter: since we're joining by primary key, the GroupJoin function preserves the order of the outer elements- the someOtherCollectionOfObjects.

But the line that shows a real fundamental misunderstanding of what's going on is this one:

var sList = s as IList<SomeObjects> ?? s.ToList();

s here, is our "inner" side of the join- the someObjects. They are passed to the lambda as an IEnumerable, which for some reason we choose to cast as an IList... but note the ?? operator. If s is null, we will call s.ToList(). In no case could s ever be null, but if it were, calling a ToList function on it wouldn't work.

Not only is this line unnecessary, but if it were, it wouldn't work anyway.

proget-icon.png [Advertisement] ProGet's got you covered with security and access controls on your NuGet feeds. Learn more. TheDailyWtf?d=yIl2AUoC8zAyRrqxOcoPfc
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