WaitForFirstN Tasks Method

There is a definite gap between TAP Utilities Task.WaitAny and Task.WaitAll. How do we wait for the first ‘N’ tasks from an array of tasks. That is one utility that is missing from TAP’s rich repository. It might not be hard to implement one by yourself though.

public static int[] WaitForFirstN(this System.Threading.Tasks.Task[] tasks,int numberOfTasks)
{
   if (numberOfTasks > tasks.Length) throw new ArgumentOutOfRangeException();

   var _taskDictionary = Enumerable.Range(0, tasks.Length).ToDictionary(x => tasks[x]);
   List<int> completedTaskIndices = new List<int>();

   while (completedTaskIndices.Count < numberOfTasks) 
   { 
      var index = System.Threading.Tasks.Task.WaitAny(tasks);
      completedTaskIndices.Add(_taskDictionary[tasks[index]]); 
      tasks = tasks.Where(x => x.Id != tasks[index].Id).ToArray();
    }
    return completedTaskIndices.ToArray();
}

The above code uses existing Task Collaborators Task.WaitAny to wait for ‘N’ tasks specified by numberOfTasks parameter. Let’s try the following in code.

 
System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[5];

[TestInitialize]
public void Init()
{
  for (int ctr = 0; ctr <= 4; ctr++)
  {
    int factor = ctr;
    tasks[ctr] = System.Threading.Tasks.Task.Run(() => Thread.Sleep(factor * 250 + 50));
   }
}
[TestMethod]
public void WaitForFirstN_ValidResult_EqualsExpected()
{
   var completedTaskList = tasks.WaitForFirstN(3);
   CollectionAssert.AreEqual(new int[] { 0, 1, 2 }, completedTaskList);
}

Code shown in this sample can also be on my GitHub.

One interesting though. Curious why Framework doesn’t allow us to create Static Extension Methods for types.

Why avoid Conversion Operators

No doubt that the Conversation Operators makes developers life easier by bring in a kind of substitutability, but it comes with a price. If not properly designed/used, it could result in subtle errors that can be easily ignored.
Consider the following code.
public class Car
{
  public string MakerName { get; set; }
  public Car(string Maker) => MakerName = Maker;
}
public class ElectricCar
{
  public string BrandName { get; set; }
  public ElectricCar(string Brand) => BrandName = Brand;
}
We have a class called Car, which exposes a single property – MakerName. We have another class ElectricCar, which exposes a property called BrandName. As seen, both classes are inherently incompatible, and you cannot implicitly/explicitly convert one to other. In order to solve this problem, we would be tempted to introduce an implicit conversion operator between the two classes.

We will modify ElectricCar as the following.

public class ElectricCar
{
  public string BrandName { get; set; }
  public ElectricCar(string Brand) => BrandName = Brand;
  public static implicit operator Car(ElectricCar car) => new  Car(car.BrandName);
}

We have added an implicit operator that supports conversion between ElectricCar and Car Classes. This works fine and you can now convert between the two classes. Let’s now create a method which updates the BrandName for the class Car.
public static void UpdateMarkerName(Car car, string MakerName) => car.MakerName =  MakerName;
By virtue of our implicit operator, we should be able to pass instances of both Car and Electric Car to this method. Let’s attempt to do so.
class Program
{
        
  static void Main(string[] args)
  {
     var _car = new Car("Toyota");
     var _electricCar = new ElectricCar("Toyota");

     UpdateMarkerName(_car, "Tesla");
     UpdateMarkerName(_electricCar, "Tesla");

     Console.WriteLine($"Car : {_car.MakerName}");
     Console.WriteLine($"Electric Car : {_electricCar.BrandName}");

     Console.ReadLine();
}
   public static void UpdateMarkerName(Car car, string MakerName) =>  car.MakerName = MakerName;
}
The output of above code would be curiously different, despite the implicit conversion.

Car : Tesla
Electric Car : Toyota

Of course, it is not hard to understand why. The instance of ElectricCar, thanks to the implicit operator implementation, would be converted to an instance of Car when passed to the UpdateMarkerName method. However, the scope of converted object is within the UpdateMarkerName class. The Method, updates the MakerName, but eventually throws away the instance. It has no reflection on the original instance. This is in stark contrast to when an instance of Car is being passed.

This kind of error can be easily overlooked by the developer and can lead to issues that are hard to trace. This is one of the reasons why we need to keep away from the Conversion Operators.

Nominal Vs Structural Type System

Anonymous Types and Tuples might look very similar, but there is one significant difference which separates them. As always, nothing can be more explanatory than writing code.
var anonymous1 = new { x = 1, y = 1 };
var anonymous2 = new { y = 1, x = 1 };

var tuple1 = (x : 1, y : 1);
var tuple2 = (y: 1, x: 1);

Console.WriteLine($"Anonymous Type :  {anonymous1.Equals(anonymous2)}");
Console.WriteLine($"Tuple Type : {tuple1.Equals(tuple2)}");
Consider the above code. What could be the output ? Are both false or are both true ? Interestingly, the output is as follows.
Anonymous Type : False
Tuple Type : True
Though syntactically similar, both Anonymous Types and Tuples vary in a significant factor – the associated type system.  While Anonymous Types is based on Nominal Type System, Tuple is based on Structural Type System. This results in the behavior seen in the above code, with both tuples being equal despite the obvious naming pattern difference.
That brings us to another scenario, what if the sub types for tuples are differently named. For example, consider following code.
var tuple1 = (x : 1, y : 1);
var tuple3 = (a: 1, b: 1);
Console.WriteLine($"Tuple Type : {tuple1.Equals(tuple3)}");
As you would have rightly guessed, the output would be “true” as the tuple is only interested in the types and not the names.

Evil Code #006 : Build Configurations

This one is courtesy Wouter de Kort, from his famous book. Okay, so what’s the evil code here. Consider the following code and predict the output in Debug as well as Release modes.

static int count = 10;
static void Main(string[] args)
{
  Timer timer = new Timer(CallBackMethod, null, 0, 2000);
  Console.ReadLine();
}

private static void CallBackMethod(object state)
{
  if (--count == 0)
  Environment.Exit(0);

  Console.Write(count);
  GC.Collect();
}

Output of the code under different configurations

// Debug Mode
987654321
// Release Mode
9

Isn’t that weird that the output has varied in Debug and Release modes ? Well, the key player in charge of this different output is the Garbage Collector and code optimization. When in the Release mode, the compiler optimizes the code realizing that timer object is not used again. This results in the CallBackMethod being executed only once.

Design Patterns : State Pattern

State Pattern is share a lot of similarities with Strategy Pattern, but has its own fundamental differences as well. The State pattern allows to change the behavior of a method, depending on the state of an object, in other words it encapsulates the behavior dependent on the state (the What). This is different from the Strategy Pattern which encapsulates the algorithm (the How).

As always, let’s begin by writing a code that showcases the issues faced when we are not using State Pattern.
public enum eState
{
  CardNotInserted,
  NotValidated,
  Validated
}
public class ATMWithoutState
{
  public eState CurrentState { get; set; }


  public void DoOperation()
  {
    switch (CurrentState)
    {
     case eState.CardNotInserted:
        Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
        break;
     case eState.NotValidated:
        Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
        break;
case eState.Validated:
       Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
       break;
    }
  }
}

The switch case exposes the most obvious flaw of this approach, we need to alter the class to add a new state, which is a clear violation of the Open Closed Principle. This is where the State Pattern comes into play, which gives a separate behavior for DoOperation method for different states of Object.

public interface IAtmState
{
  void DoOperation();
}

public class ATMWithState
{
  public IAtmState CurrentState { get; set; }

  public void DoOperation()
  {
    CurrentState.DoOperation();
  }
}

public class CardNotInsertedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
  }
}

public class NotValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
  }
}

public class ValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
  }
}

The complete code described in this post in available in my GitHub.

Design Patterns : Null Object Pattern

Null Pattern is probably one of the most underestimated and often most ignored among the design Patterns., though it turns out to be one of the easiest to implement. The intend of the pattern is to ensure we won’t end up with NullReference Exceptions, while avoiding the long list of repeated preconditions that checks of null values. Instead, we provide identify and define the behavior when null object is encountered , encapsulate it in a object, and use it as you would normally use any other valid instance of the object.

Consider the following code.

public class Person :IPerson
{
public long ID {get;set;}
public List GetEmployementHistory()
{
   // Do some operations from Db
}
}

// Client Code 

void Main()
{
   var Employee = EmployeeCollection.GetEmployee();
   var details = Employee.GetEmployementHistory();
}

The above code would throw an exception if the Employee Parameter is null. The obvious solution would be to use preconditions to ensure we handle null values in appropriate manner. We would have to rewrite the code as follows.

void Main()
{
   var Employee = EmployeeCollection.GetEmployee();
   if(Employee == null)
   {
      // Do appropriate action
   }
   var details = Employee.GetEmployementHistory ();
}

However, this approach would mean that the client that invoke the GetDetails method needs to be ensure the object isn’t null. This is an unnecessary burden on the client, and on a longer run, and the chances of a client forgetting to validate the object is higher.

Null Object Pattern

As mentioned earlier, the Null Object Pattern aims to provide a default behavior ( or no behavior at all) when a null instance is encountered by encapsulating the behavior within an instance. We would do so by providing special implementation of the type, which encapsulate the behavior associated with null object.

For example, for the above code, the null object pattern could be defined as

public class NullPerson: IPerson
{
  public long ID {get;set;} = -1;
  public List GetEmployementHistory()
  {
    return new List();
  }
}

Now we could rewrite the Client Code sans any preconditions without worrying about the null exceptions. However, here is a word of caution. We shouldn’t use the Null Object Pattern to swallow the exception unless that’s a behavior we really want. Another scenario one needs to avoid while using the Null Object Pattern is the usage of “IsNull” Properties/Method. At times , we do come across Null Object Implementation that includes a property/method which states where the object is null. For example, consider the following code.

public class NullPerson: IPerson
{
  public bool IsNull {get;set;} => false;
  public long ID {get;set;} = -1;
  public List GetEmployementHistory()
  {
    return new List();
  }
}

This is NOT Null Object Pattern as it defeats the purpose of the pattern.It causes the logic to be spilled outside the object.

Sample code for Null Object Pattern can be found in my GitHub

Evil Code #005 : Readonly Value Types

Time to review another of Evil Code Series and this time, we are dealing with read-only value types. Review the below code and predict the output.

 

struct DummyStruct
{
    public int MyValue {get; set;}
    public int Increment() => ++MyValue;
    public DummyStruct(int myValue)=> MyValue = myValue;
}
public class DemoClass
{
    private readonly DummyStruct _readOnlyStruct;
    public DemoClass() => _readOnlyStruct = new DummyStruct(2);
    public void IncrementAndDisplayValue() => Console.WriteLine($"({_readOnlyStruct.Increment()},{_readOnlyStruct.MyValue})");
}
var myClass = new DemoClass();
myClass.IncrementAndDisplayValue();

 

Strangely enough, the output is {3,2}. Yes, it means the Increment Method return a value of 3 for MyValue, but a follow-up statement to display MyValue explicitly, ends up with a value 2. Isn’t that bizarre ? Well not quite if one think a bit deeper.

Being a value type, whenever we are accessing it, we only get a copy of the value. The original _readOnlyStruct.MyValue is immutable and doesn’t change. But, the copy isn’t quite immutable and gets altered, which is returned by the Increment method. And when you are calling the _readOnlyStruct.MyValue property in the later part of program, another copy of the immutable value type is created which has the original value. This is the reason we are seeing the output. A more detailed explanation has been provided by Eric Lippert in his blog .
Happy Coding !!

Benchmarking Span<T> Performance

Span<T> is yet another addition to C# 7.x and is particularly useful in developing memory intensive applications.  So what is Span all about ?

 

As Microsoft describes it, Span<T> is a new value Type which enables the representation of contiguous regions of arbitrary memory, regardless of whether the memory is associated with a managed object, is provided by native code  or is on the stack, with a performance characteristics like that of an array.

 

It feels like you can use pointers, but without entering ‘unsafe’ code. That definitely is interesting. We will be looking into Span<T> closely in upcoming posts, but for this post, we will compare Span with Strings when parsing sub strings.  We will begin by how sub strings work. We will keep it simple for sake of the example. Consider the following code.
public void DummyMethod(string data) { }

string keyString = "234567";
DummyMethod(keyString.Substring(0, 2));
DummyMethod(keyString.Substring(2, 2));
DummyMethod(keyString.Substring(4, 2));

Remember string is immutable, and each time we are invoking the Substring method, we are allocating a new memory location is allocated with the substring. Now that isn’t a scenario you wouldn’t want to be if you are working on a memory intensive application and you want to parse a really long string. But what is we could parse the string right from the memory location allocated for keyString. That would be extremely efficient right ?

That’s where Span<T> comes in. It would allow us to point to a contiguous region of memory, and allow us to parse through it without needing a different memory allocation. Let’s rewrite the above code using Span<T>.

public void DummyMethod(ReadOnlySpan data) { }

ReadOnlySpan keyString = "234567".AsReadOnlySpan();
DummyMethod(keyString.Slice(0, 2));
DummyMethod(keyString.Slice(2, 2));
DummyMethod(keyString.Slice(4, 2));

Notice that the string has a nice little extension method to create a ReadOnlySpan. We are also using the Slice method (instead of Substring) to access the specific part of memory location. We will do a bit of bench marking to understand the performance implication. Let’s create a BenchmarkDemo Class for our demonstrative purpose. Complete source code is available at my Github.

[Benchmark]
public void UsingSubString()
{
    string keyString = "long string";
    for (int i = 0; i < IterationLimit; i++)
        DummyStringMethod(keyString.Substring(0, i));
}
void DummyStringMethod(string _) { }

[Benchmark]
public void UsingSpan()
{
    ReadOnlySpan keyString = "long string".AsReadOnlySpan();
    for (int i = 0; i < IterationLimit; i++)
        DummySpanMethod(keyString.Slice(0, i));
}

void DummySpanMethod(ReadOnlySpan _) { }

The above code is for demonstrative purpose, hence we are using a dummy string "long string". In the example in Github, you can find the same replaced with lorem ipsum.

Alright, now lets run the Benchmark code and analyse the memory allocation against iteration loops of 10,100, and 400. We are using BenchmarkDotNet for example.

Benchmark Span

As you can see the “UsingSubString” method uses a huge amount of memory as the calls to substring increases. On other hand, Span based method hardly uses any and doesn’t have any different as the number of calls increases.

That’s it for now, we will investigate more on Span<T> in upcoming posts.

Ref Value Type

In an earlier post, we discussed the readability factor of the reference semantics, mentioning how it kind of makes the code less readable. However, that doesn’t take away the big door of opportunities the new features add. Consider the following scenario.

As a developer, you want to develop a extension method called Increment
for Type "int", which increments the value by 1.
The extension method should have a void return type.
We would ideally would like to do the following.

int testValue = 1;
testValue.Increment();
Console.WriteLine(testValue);   // This should print a value 2;

Now, prior to C# 7, this was difficult. There was no way we could pass a reference of a value type to an extension method. Which means that every time we call the extension method, we would be passing a copy of the value, rather than the reference, increment the copied value and then just throw away the value. The above code would print a value “1”.

This is where the new reference type comes in play. We could now use reference type in extension methods. Let’s write the code using C# 7 now.
public static int Increment(this ref int Val) => ++Val;
Now if we were to run our code, testValue would show a value “2” as desired. That’s interesting right ?.  Of course, there are other befits too. Consider the scenario where you have a gigantic struct (it is another question whether it is ideal to use a value type when the type is expected to be huge, but for sake of the demonstration we will use struct here) which gets passed to different methods. Each type you are calling the method, you are creating a copy of the gigantic struct (allocating memory).  This is going to be troublesome if you are working on a memory critical environment and the struct is going to be passed around.
With C# 7.0, you can not just pass the value type as reference, but we can also return a value type as ref. That is just brilliant by the language developers right. Let’s go ahead and look into the syntax of the same by modifying our extension method so that it returns a reference as well.
public static ref int Increment(this ref int data)
{
++data;
return ref data;
}

int testValue = 1;
ref int pointsToTestValue = ref testValue.Increment();
Console.WriteLine(testValue);
pointsToTestValue++;
Console.WriteLine(testValue);

The Increment method increments the value as it did earlier. Furthermore it now returns the same value as reference. Do note the changes in syntax for invoking as well as defining a method that return ref.

The output of above code would be

2
3

There might be scenarios where you might have to pass a data as reference, but ensure it doesn’t change. Here is where the new ‘in’ parameter comes in. The “in” keywords accepts the data by reference, but ensure that a developer who works on in future doesn’t change the value accidentally. “in” can be used in interface as well, to ensure that the implementing classes doesn’t change the value in the method.

public int Increment(in int data)
{
++data; // this is not allowed
return data;
}
Update : 
You could also make a returned reference read only, though we would go back to using the readonly keyword rather than “in”. (makes sense too). The syntax would be as follows.

 

static public ref readonly int Increment(ref int data) => ref data;

ref readonly int readonlyReference = ref Increment(ref h);
readonlyReference++; // This is not allowed.

One obvious question of having a reference return type would be , what happens to the scope ? Does that mean GC needs to be aware of references outside scope of a method ? Not exactly, the Language team has thought well about it and has implemented certain safety constrains. The method can only return a ref that either came as a parameter or are in same heap. You cannot return a reference that is created within the method.

We will cover some more features of C# 7.x in coming posts, especially the ones that has to do with reference semantics.

Technical Debt Quadrant

In a practical corporate software development scenario, there are times when you have (willingly or otherwise) to give up to trade-offs and compromises  especially when the deadlines looms over you or, in worst case, you are LAZY !!. You might be prompted to choose a less than optimal solution due to situational constraints, which might lead to technical debts. But how would one convince the stakeholders (or may be himself) that you are not entirely wrong in opting for the selected solution ? How do you categorize technical debts

Martin Fowler had suggested a Technical Debt Quadrant which comes pretty useful in vindicating the trade offs by categorizing the situations or the intention with which we opt for debt.

5f06ca78-d831-4da1-b97a-ce8bc39d5382.png

The technical debt quadrant is quite easy to use and is especially useful when addressing a non-technical audience (stakeholders) about the trade-offs chosen. It can also act as guidelines for team (and product owner) when the deadlines are looming and trade-offs are required.

A Prudent-Deliberate Quadrant is a ideal situation wherein the team/developer has evaluated the alternatives and picked the choice completely conscious of the implications to achieve a specific business goal.They are aware that they would need to repay the debt at some point and has a plan of action for the same. This is where the team would ideally like to be when encountered with a technical debt. At the opposite end of the spectrum is a Reckless-Deliberate quadrant, which should be avoided at all cost. It implies that the developer/team understands the implications of the actions, but choose to opt for same citing avoidable reasons/excuses.

The Prudent-Inadvertent quadrant belongs to the class of hard working team who had the best intentions, but choose a different solution when a better one was available. Considering their keen interest for improvement and intention, these men represent a team who will improve over time. The last of the quadrant, the Reckless-Inadvertent group usually consists of who are inexperienced and doesn’t know the best practices. It was their ignorance which caused the debt, which is, to an extend acceptable.

On any day, a Prudent-Deliberate Quadrant is a scenario that the stake holders might not mind. However, all other types of scenarios needs to avoided.