Stairway Pattern

How do you feel when you invite your friend for a private family function and he brings along a dozen strangers (his friends) ?

 

Entourage Anti-Pattern

This is similar to the scenario when you want to add a library as reference and in turn ends up referring a different set of libraries which you are not directly dependent. This scenario is perfectly defined by the Entourage Anti-Pattern. The Entourage pattern also describes the (avoidable) practice of packaging the abstraction and implementation in the same assembly.

The Stairway Pattern

The stairway pattern describes a better alternative by organizing your abstractions and implementations in separate assemblies, which in turn allows both to evolve and vary independently.

It also means the references now doesn’t bring an entire entourage of assemblies along. One of the thumb rules you can adhere too is to ensure the abstraction assembly doesn’t depend on any external references.

CLSCompliant Attribute

While developing a library in .Net which could be used by another programming language than it was originally designed in, it is important to remember that the .Net Languages offers a subset of CLR/CTS while offering a superset of CLS. And, if you want to develop a library that could be used by any programming language supported by .Net, you have additional responsibility to ensure that your code doesn’t take of care of any features outside the CLS.

Thankfully, .Net provides us an easier way to check the same using the CLSCompliant Attribute.

[assembly: CLSCompliant(true)]
namespace ConsoleApp3
{
    public class TestClass
    {
        public int Method1() => 1;
        public int method1() => 2;
        private int mEthod1() => 3;
    }
}

The above code would raise warning “Warning CS3005 Identifier ‘TestClass.method1()’ differing only in case is not CLS-compliant” to help us identify the non-compliance. Do note that mEthod1 doesn’t raise a warning as it is a private method and is not exposed outside the assembly.

Type Casting using Span<T>

In an earlier post, we explored the possibilities of Span and performance benefits of the feature was clearly visible in our benchmark tests. We will continue exploring the Span further in this post, as attempt to cast between types using Span.

The cast functionality is not that hard, thanks to the extension methods that comes along with Span<byte> under the System.MemoryExtensions namespace. The NonPortableCast method converts a Span<byte> to the specified Type.  As seen in the code below, the first step however is to convert the original type to a byte array. The implicit conversion between byte array and Span<byte> would allow you to convert it to Span<byte>.

 

long originalPrimitiveType = 25;
Span byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span intSpan = byteSpan.NonPortableCast();
int castPrimitiveType = intSpan[0];
The key point to note here is the first 4 bytes of Span<byte> maps to the zeroth element of Span<int>. The code samples described in this post is available in my Github.

Deconstructing Non-Tuples

The ‘Tuple evolution‘ in C# 7x has created increased possibilities of C# like never before, both in terms of performance as well as readability. One of the nicest feature that came along has been the Deconstruction of tuples.

Deconstructing Tuples

The tuple data structure allows us to bundle together a finite number of values without having to go through the pain of creating a dedicated Data structure for it. This is often useful when we need to return more than one values from a method. Consider the following method.

private Tuple GetPerson()  =>  new Tuple("Jia", 2);

Prior to C# 7, this is where the fun ended. While it was easier to return multiple values from a method, it was a tedious task to read those data.

var person = GetPerson();
Console.WriteLine(person.Item1);
Console.WriteLine(person.Item2);

As you can see, this resulted in the code readability hitting rock bottom. But C# 7.0 has changed the picture completely and has made the Tuples not just more powerful, but extremely easy to use. Let’s rewrite the method as well as the caller access in C# 7.x.

private (string,int) GetPerson() => ("Jia",2);
var (name,age) = GetPerson();
Console.WriteLine(name);
Console.WriteLine(age);

As evident from the code, the readability and ease to use has increased, and that is not limited to just the caller. Even the way we return the method signature and return statement has become far more simpler.

Deconstructing Non-Tuples

The whole deconstruction process has made usage of tuple so flexible. What if we could leverage the same functionality in the non-tuples data structures ? Consider the following class.

class Person
{
  public string Name { get; set; }
  public int Age { get; set; }

  public Person(string name,int age)
  {
    Name = name;
    Age = age;
  }
}

private Person GetPerson() => new Person("Jia",2);
var person = GetPerson();

Of course it is easy to access the Name/Age Properties using the person.Name, person.Age syntax. But there could be situation when the Person class has many other properties and you are interested only in just a couple. Or there could be another situation when you want to assign the Name and Age properties directly to existing variables in the caller method. In such scenarios, we would have to write the following code.

// where 'name' and 'age' are variables in caller method.
var person = GetPerson();
name =  person.Name;
age  = person.Age;

C# 7.0 has made life things easier with the Deconstruct for non-tuples. All we need to do is add a simple Deconstruct method to the Person class.

public void Deconstruct(out string name, out int age)
{
  name = Name;
  age = Age;
}

The parameters of the Deconstruct method needs to be out parameters. That’s all you need to do for deconstruction of non-tuples to be effective. The code in question could be now rewritten as following.

(name,age) = GetPerson();

C# 7.x is turning out to be an interesting evolution of C# language. Eagerly waiting to see what is in store for C# 8.0.

Git stash

Git is arguably the most versatile version control system around and one cannot resist falling in love with this awesome piece of code every time you use it.

One of the lesser known features in Git, especially for individual developers/teams who have recently migrated from other tools is the “stash” command.

You might often find yourself in situation when you aren’t yet ready to commit your code, you would like to view the last commit without trashing the existing code. You could also be in situation when you want keep your local changes without committing and then swap to do something else.

This is where the stash comes into the picture. Stash creates a backup of your current staged and unstaged changes, and returns your branch to the last commit. To stash your changes, you use the stash command.

git stash

When you are ready to go back to your stashed changes, you can use the ‘git stash apply‘ command. This would take your latest stashed changes and apply it to the branch.

git stash apply.

Finally you could delete your stashed changes by using the git stash drop command.

git stash drop.

This would remove your last set of stashed changes.

Looking back at DRY

Continuing with our series to bring together the common design patterns and principles, we will, in this particular post, look into arguably the most famous design principle known to programmers – DRY. Don’t Repeat Yourselves – or DRY, is possibly the easiest to practice, at the same time, one that could go wrong in the ‘rush hours’ of project deadlines.  The principle, as you would be aware of, aims in reducing/eliminating duplicate software patterns in the system.  The Pragmatic Programmer describes DRY principle as follows

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system – Andrew Hunt, Dave Thomas

The evils of a non-DRY system is obvious.If you have same functionality defined in two places, and you forget to change in one of the place when the functionality changes, you are left with a system that is self-contradicting. The principle doesn’t exclusively apply to code, but rather it applies to documentation, comments in code as well. Consider a scenario when the developer changes the code, but forgets to change the comments associated with the code, the result could be a future developer banging his head to understand what is now an obsolete comment.

The duplication could be broadly categorized into four categories (again thanks to Pragmatic Programmer).

Imposed Duplication
There could be scenario’s when the Project Specifications or the technology limitations imposes duplication on the development team. Such scenarios are hard to tackle and the near perfect solution would be localize the impact of violation.

Inadvertent Duplication
This kind of duplication involves scenario when the developer doesn’t realize they are guilty of duplication. This could be resultant of a rather imperfect design.

Impatient Duplication
This is the most avoidable of the four categories of duplication and describes the scenarios when the developers are lazy or pressurized with deadlines, and end up finding shortcuts via duplicating. However, the develop team as a whole needs to remember that this tiny shortcut could lead to catastrophic impacts in latter stages of project

Interdeveloper Duplication
Most commonly seen in large disconnected teams and possibly the hardest to detect. The developer in one sub team could duplicate a functionality which was already developed.

DRY, as seen from above, is possibly the most easiest of Design Principles to master, if you are always on your toes. The key lies in keeping an eye on the bigger picture of project, refactor your code regularly.

A Closer look at DateTime Operations

There are many ways you could round off a DateTime to the nearest Hour. You could create a new Instance of DateTime, ignoring the current instance’s Minute/Seconds parts. You could also use the Add Minute method as seen in the following code.

Constructor Vs Add Method

private DateTime testData = DateTime.Now;
public DateTime FloorWithConstructor() => new DateTime(testData.Year,  testData.Month, testData.Day, testData.Hour, 0, 0);
public DateTime FloorWithAddOperator() =>  testData.AddMinute(-testData.Hour).AddSeconds(-testData.Second);

But which of the two is more efficient ? Let’s attempt to benchmark them with BenchmarkDotNet.

Method Mean Error StdDev
FloorWithConstructor 203.92 ns 4.057 ns 6.435 ns
FloorWithAddOperator 97.28 ns 2.319 ns 3.326 ns

 

Since I was under the impression that since each call to AddMinute/AddSeconds, methods would create a new instance of DateTime, I was very curious why the Add Method approach performed marginally better. But thanks to Daisy Shipton @Stackoverflow, I was able to understand why the difference in a much better way. This is also visible if you happen to refer the DateTime Source at ReferenceSource.

The Constructor : From Reference Source

public DateTime(int year, int month, int day, int hour, int minute, int second)
{
   this.dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second));
}
private static long DateToTicks(int year, int month, int day)
{
  if (year >= 1 && year = 1 && month = 1 && day = 0 && hour = 0 && minute =0 && second = 0? 0.5: -0.5));
  if (millis = MaxMillis)
                throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
  return AddTicks(millis * TicksPerMillisecond);
}

public DateTime AddTicks(long value)
{
  long ticks = InternalTicks;
  if (value > MaxTicks - ticks || value < MinTicks - ticks)
  {
    throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
  }
  return new DateTime((UInt64)(ticks + value) | InternalKind);
}

 

The difference is obvious. The significant more arthimatic/conditional operations happening the particular constructor makes it rather more slower, compared to Add Methods.

The Ticks Approach

So what would be a more efficient approach ? How about if we manually work with the Ticks ? Let’s write a method and run it against the other methods.

public class DateTimeMethods
{

private DateTime testData = DateTime.Now;

[Benchmark]
public DateTime FloorWithConstructor() => new DateTime(testData.Year,  testData.Month, testData.Day, testData.Hour, 0, 0);

[Benchmark]
public DateTime FloorWithAddOperator() =>  testData.AddMinutes(-testData.Minute).AddSeconds(-testData.Second);

[Benchmark]
public DateTime FloorWithTicks()
{
  var originalTicks = testData.Ticks;
  var hoursSinceEpoch = originalTicks / TimeSpan.TicksPerHour;
  var newTicks = hoursSinceEpoch * TimeSpan.TicksPerHour;
  return new DateTime(newTicks);
}
}

 

Method Mean Error StdDev
FloorWithConstructor 206.37 ns 4.1382 ns 5.2335 ns
FloorWithAddOperator 97.81 ns 2.3568 ns 2.0892 ns
FloorWithTicks 24.47 ns 0.1492 ns 0.1246 ns

As you can see it has made a significant improvement now.No prizes for guessing how the Constructor that accepts Ticks looks like.

public DateTime(long ticks)
{
  if (ticks  MaxTicks)
    throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
  Contract.EndContractBlock();
  dateData = (UInt64)ticks;
}

The sample code for this demo can be found in my GitHub.

Zero Bug Bounce (ZBB)

ZBB or Zero Bug Bounce is a defect management technique originating from Microsoft that represents the moment (would prefer to call it a milestone) in time when the developers has managed to fix (or triaged) all the bugs reported by the QA team. The bounce refers to the fact the QA team might (and surely will) find bugs again increasing the count of bugs. The rate of discovery of bugs gradually tend to decrease as the application gets ready for release.

zbb

So what is the significance of ZBB ? It surely doesn’t mean the application is ready for release as there is a bounce expected. But the ripple or the bounce, gives the team a good indication of how stable the application is and how closer are we nearer to a release.  Surely, that is an useful indication which the development team and Managers would like.

Unit Testing Asynchronous Code

Unit Testing Asynchronous methods in older days were pretty tough, but thanks to the advances made in the Unit Testing Frameworks, this is now all the more easier.

We will begin by writing an async method, which we could use for writing our Unit Tests against.

public async Task ReadFileAsync(string fileName)
{
  using(var file = File.OpenText(fileName))
     return await file.ReadToEndAsync();
}

The advancements in Unit Testing Framework has made it possible for us to write Unit Tests against async methods easier.

private string _ValidPath = "DummyText.txt";
private string _InvalidPath = "";
private FileReaderAsync _fileReaderAsync;

[TestInitialize]
public void Init()
{
  _ValidPath = @"DemoFile/LargeText.txt";
  _InvalidPath = @"DemoFile/DoNotExist.txt";
  _fileReaderAsync = new FileReaderAsync();
}

[TestMethod]
public async Task FileRead_ValidPath_NoErrors()
{
  var data = await _fileReaderAsync.ReadFileAsync(_ValidPath);
  Assert.IsNotNull(data);
  Assert.IsTrue(data.Length > 0);
}

Handling Exceptions

Let’s add one more Test Case, that would ensure a FileNotFoundException is raised when an invalid path is passed to the method.

[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public async Task FileRead_InvalidPath_FileNotFoundException()
{
  var data = await _fileReaderAsync.ReadFileAsync(_InvalidPath);
  Assert.IsNotNull(data);
  Assert.IsTrue(data.Length > 0);
}

This method would, as expected, would succeed with ExpectedException specified. So far, so good. That’s because we expected the exception to be raised from ReadFileAsync method and it did raise an exception when an invalid path was passed.

But what if we had an exception raised from the Arrange Part. For example, we had an exception raised by the Constructor of the class. Let us rewrite Constructor of our Class and the Test Method to demonstrate the issue.

Class under Test

public class FileReaderAsync
{
  public FileReaderAsync(bool throwError=false)
  {
    if (throwError)
       throw new InvalidOperationException();
  }
  public async Task ReadFileAsync(string fileName)
  {
    using(var file = File.OpenText(fileName))
      return await file.ReadToEndAsync();
  }}

Test Method

[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public async Task  FileRead_ConstructorOperationNotValidAndFileNotFoundException_NotFound()
{
  _fileReaderAsync = new FileReaderAsync(true);
  var data = await _fileReaderAsync.ReadFileAsync(_InvalidPath);
  Assert.IsNotNull(data);
  Assert.IsTrue(data.Length > 0);
}

This Test method would fail as one would expect. The Expected Exception specified is FileNotFoundException, however, the call to the class Constructor would raise an InvalidOperationException.

Handling Exceptions : Better Approach

What we need is mechanism to specify the expected exception for each specified line of code. NUnit was probably the first framework to make that possible, but MS Test was quick to catch up. Let’s write the Test Method with the new approach.

[TestMethod]
public async Task  FileRead_ConstructorOperationNotValidAndFileNotFoundException_Found()
{
  Assert.ThrowsException(()=>_fileReaderAsync  = new FileReaderAsync(true));
  // Reinitialize as constructor has failed
  _fileReaderAsync = new FileReaderAsync();
  await Assert.ThrowsExceptionAsync(async () =>  await _fileReaderAsync.ReadFileAsync(_InvalidPath));
}

This approach would ensure that the Test Method would pass. As you might have already noticed the Assert.ThrowException has a async counterpart, to take care of the async methods.

This approach is far better than the ExpectedException method as we have already seen. Code samples described in this post is available in my Github.

Design Patterns : Bridge Pattern

The essence of Bridge Pattern lies in the fact that it not just decouples the abstraction from implementation, but in doing so, allows both to evolve independently. Let’s consider the examples of smartphones.

The underlying OS (for sake of example, let’s assume its Android) improving every year. The Android has seen atleast 7 versions in past decade. At the same time, the hardware has also evolved, giving way to new age smartphones. The Abstraction and Implementation has evolved independently here. Let’s mock the scenario using Bridge Pattern.

public interface IAndroid
{
  void Call(string name);
  void Recieve();
  void SendMessage(string name);
  void RecieveMessage();
}
public class KitKat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  KitKat");
  public void Recieve() => Console.WriteLine("Recieve using KitKat");
  public void RecieveMessage()=> Console.WriteLine("Recieve Message using  KitKat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using KitKat");
}
public class Lollipop : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Lollipop");
  public void Recieve() => Console.WriteLine("Recieve using Lollipop");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Lollipop");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Lollipop");
}
public class Nougat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Nougat");
  public void Recieve() => Console.WriteLine("Recieve using Nougat");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Nougat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Nougat");
}

Evolution of Abstraction which Customer/Client sees, the Phone , can be seen in following code.

public class SmartPhone
{
  protected IAndroid _android;
  public SmartPhone(IAndroid android) => _android = android;
  public virtual void Phone(string name) => _android.Call(name);
  public virtual void SendMessage(string name) =>  _android.SendMessage(name);
}
public class NewAgeSmartPhone : SmartPhone
{
  public NewAgeSmartPhone(IAndroid android) : base(android) { }
  public override void Phone(string name)
  {
    Console.WriteLine("New Age Phone Call, Optimization started");
    base._android.Call(name);
  }
  public override void SendMessage(string name)
  {
    Console.WriteLine("New Age Message");
    _android.SendMessage(name);
  }
}

 

Client Code can be shown as following

static void Main(string[] args)
{
  var phone = new SmartPhone(new KitKat());
  var newAgePhone = new NewAgeSmartPhone(new KitKat());
  phone.Phone("Wife");
  newAgePhone.Phone("Wife");
}

 

As seen in the code above, the Bridge Pattern allows the Abstraction and Implementation to vary and evolve independently. Complete Code Sample in this example can found in my GitHub