Skip to main content

Applying LINQ principles to business logic

This was inspired by a conversation I was having with @leeoades & @hamishdotnet at work earlier this week, we were discussing the use of Yield keyword to short-cut method execution. Lee has a great post about sequences here. I wanted to get down how my thinking about the Yield keyword has now changed.

Historically I've always thought about using the yield when I'm defining a custom enumerator method, something like GetFooEnumerator - typically I'd have placed this on some kind of model object to allow the easy iteration of some child model instances. Lee was saying why not use yield where ever you have the following usage pattern:

   1:  public IEnumerable<int> Range(int start, int end)
   2:  {
   3:      var numbers = new List<int>();
   4:      for (var i = start; i < end; i++)
   5:      {
   6:          // Do some business logic here...
   7:          numbers.Add(i);
   8:      }
  10:      return numbers;
  11:  }

When ever you have a method which internally creates & populates a collection and then returns the collection why not use yield to make it more efficient?

This got me thinking, what kind of improvement efficiency are we talking about?

Time for a quick test, first we need a couple of methods to compare, first one very similar to above and another making use of the yield keyword but both achieving the same logic - returning a collection of numbers to the caller:

   1:  public class Numbers
   2:  {
   3:      public IEnumerable<int> Range(int start, int end)
   4:      {
   5:          var numbers = new List<int>();
   6:          for (var i = start; i < end; i++)
   7:          {
   8:              numbers.Add(i);
   9:          }
  11:          return numbers;
  12:      }
  14:      public IEnumerable<int> YieldRange(int start, int end)
  15:      {
  16:          for (var i = start; i < end; i++)
  17:          {
  18:              yield return i;
  19:          }
  20:      }
  21:  }

Then a test program - use each method as part of LINQ call to validate the returned sequences contain the number 420:

   1:  static void Main(string[] args)
   2:  {
   3:      Console.WriteLine();
   5:      var numbers = new Numbers();
   7:      var sw = new Stopwatch();
   8:      sw.Start();
   9:      var found1 = numbers.Range(0, 999).Any(n => n == 420);
  10:      sw.Stop();
  12:      Console.WriteLine("Normal Loop: ticks = " + sw.ElapsedTicks);
  14:      var sw2 = new Stopwatch();
  15:      sw2.Start();
  16:      var found2 = numbers.YieldRange(0, 999).Any(n => n == 420);
  17:      sw2.Stop();
  19:      Console.WriteLine("   Yielding: ticks = " + sw2.ElapsedTicks);
  20:      Console.ReadLine();
  21:  }

Running this up I got the following output!

I wasn't expecting it to be slower, after all the YeildRange method only has to iterate 420 times before finding a match where as the Range method has to iterate over all 1000 numbers before returning...

Then @hamishdotnet pointed out the cost of yielding and I remembered the chapter in Jon Skeet's C# In Depth about iterator blocks and how a set of classes are created by the compiler when ever you use the yield keyword.

Then I had the realisation the methods didn't really have any 'business logic' - DOH!

Basically the 2 implementations don't do anything, so to simulate this I put a Thread.Sleep in to represent an I/O or processor bound call:

   1:  public class Numbers
   2:  {
   3:      public IEnumerable<int> Range(int start, int end)
   4:      {
   5:          var numbers = new List<int>();
   6:          for (var i = start; i < end; i++)
   7:          {
   8:              System.Threading.Thread.Sleep(10);
   9:              numbers.Add(i);
  10:          }
  12:          return numbers;
  13:      }
  15:      public IEnumerable<int> YieldRange(int start, int end)
  16:      {
  17:          for (var i = start; i < end; i++)
  18:          {
  19:              System.Threading.Thread.Sleep(10);
  20:              yield return i;
  21:          }
  22:      }
  23:  }

More promising results now...

So what do I mean by 'Applying LINQ principles to business logic'?

By thinking about concepts such as 'lazy evaluation' & 'materialization' when designing your methods you allow for the opportunities for your code to be more efficiently executed when used as part of any linq queries.


Popular posts from this blog

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v

Custom AuthorizationHandler for SignalR Hubs

How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0 Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub  to find the answer. Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:  I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different. Method implementation has a resource type of HubInnovationContext: I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext . For me I don't even need that, it can be removed completely  from the inheritence signature and override implementation. Only other thing to note, and this could be a biggy, is the ordering of the statements in th