Tuesday, March 22, 2016

null-coalescing and caching playing nicely together

I thought I was gonna have a nosebleed when I first saw this thing. The second half of the one line of code that really matters below is an assignment, so how is the null-coalescing operator picking out the second half of the assignment (the second half of the second half that is) as worthwhile?

public List<Foo> GoGetIt()
{
   return _cacheThing.Bar ?? (_cacheThing.Bar = _dataThing.Bar().ToList());
}

 
 

Well, if you think about it, this would return the thing getting assigned on the spot.

public List<Foo> GoGetIt()
{
   return _cacheThing.Bar = _dataThing.Bar().ToList();
}

 
 

_dataThing.Bar().ToList() gets assigned to _cacheThing.Bar and then _cacheThing.Bar gets returned, all on one line of code. You may make an assignment and return the thing you just assigned to all at once. If you're like me you probably don't see this so much in code, so it looks strange. So, that makes the null-coalescing magic a little easier to understand, huh? The magic itself doesn't really have anything to do with the null-coalescing operator. Also, you would need to managing the caching elsewhere like so:

public List<Foo> Bar
{
   get
   {
      return (List<Foo>)HttpContext.Current.Cache["Qux"];
   }
   set
   {
      Cache("Qux", value);
   }
}

No comments:

Post a Comment