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.
Advertisements

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.

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.

Reference Semantics and Code Readability

One of the features Microsoft packed with C# 7.2 is Reference Semantics with Value Types. Though designed with the intention to improve performance by eliminating the need for copying (and thereby allocating memory) value types , I do have my reservations on the complexity it adds to readability of code for a programmer. Let’s consider the case of “in” keyword.

 

The “in” allows the programmer to pass a parameter by reference, but on the condition that the method cannot modifying the value.  For example
void IncrementAndPrint(in int Counter)
{
    Counter++;   // this will throw error.
    Console.WriteLine(Counter);
}

void Print(in int Counter)
{
    Console.WriteLine(Counter);
}

We could delve into details of “in” on a later post, however, for this post, we will focus on the readability factor. One of the features of “in”, which separates it out from “ref” and “out” is that, you don’t necessarily (yeah…keyword is optional during invocation) use the keyword before using it. For example, for the above method Print , both following method invocation is valid.

int counterValue = 3;
Print(in counterValue);
Print(counterValue);

However, the framework restricts you from passing an expression or direct value with the “in” parameter. This restriction is not valid if you are not using the optional “in” keyword.

Print(in 3); // Invalid code
Print(3);      // This is valid.

Another scenario worth consideration is when there is an overloaded method of Print which doesn’t use the pass by reference. Consider the following two overloaded methods.

void Print(in int Counter)
{
     Console.WriteLine($"Pass By Reference :{Counter}");
}
void Print(int Counter)
{
     Console.WriteLine($"Pass By Value :{Counter}");
}

Understandably, the first method uses “in” keyword to pass the parameter by reference, while the second passes the parameter by value. Considering the “in” parameter is optional, what would be the output of following method invocations.

int num = 3;
Print(in num);
Print(num);

Output

Pass By Reference : 3
Pass By Value : 3

It is on expected lines as Microsoft would have wanted, however, the question is, does the ability of “optional in” do justice to readability of code ?

Regular Expression – Compiled vs Interpreted

Regular Expression gives the developer a clean and efficient method to parse strings. However, it comes at a cost – there is a inherent performance hit associated with regular expressions, especially if you are running some kind of long loops and parsing the string inside it. One way to tackle it is using compiled regular expressions, which .Net provides by using the RegexOptions.Compiled property. Let’s examine the performance of the Interpreted version of regular expression and the compiled version in a long loop.

We will consider a simple regular expression that is intended to parse a valid date.

void Main()
{
	string regex = @"^[0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}$";
	var countArray = new int[]{100,1_000,10_000,1_00_000,10_00_000, Int32.MaxValue};
	foreach(var count in countArray)
	{
		RunLoop(regex,count,false);
		RunLoop(regex,count,true);
	}
}

void RunLoop(string regexStr,int maxCount,bool isCompiled)
{
	Stopwatch watch = new Stopwatch();
    watch.Start();
    for (int i = 0; i < maxCount; i++)
    {
		if(isCompiled)
        	Regex.IsMatch("23/2/2018", regexStr,RegexOptions.Compiled);
		else
			Regex.IsMatch("23/2/2018", regexStr);
				
	}

    watch.Stop();
    Console.WriteLine($"Time Ellapsed : {watch.Elapsed.Minutes}:{watch.Elapsed.Seconds}:{watch.Elapsed.Milliseconds}");
            
}

I ran the above code on different values for maxCount. You can view the comparison of Compiled Version Vs Interpreted Version below.

Iterations
Interpreted
Compiled
Int.MaxValue
26:13:629
15:44:589
10,00,000
00:00:793
00:00:450
1,00,000
00:00:79
00:00:57
10,000
00:00:09
00:00:07
1,000
00:00:01
00:00:02
100
00:00:00
00:00:02
As you can see, the more you need to use the same regular expression, Compiled Version is better. However, if the usage is very less, the compiler version turns expensive.

 

 

Design Patterns : Strategy Pattern

Strategy Pattern lets you create a family of strategies (algorithm) encapsulated into separate interchangeable classes. In our example, we will consider a Client class which needs to invoke different sorting algorithm.

 

Let’s first create the contract interface for different Sorting algorithm.

public interface ISortStrategy
{
   void Sort(int[] ArrayToSort);
}

Now that we have our interface ready, let’s go ahead and implement different sorting algorithms based on it.[/code]

public class QuickSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Quick Sort");
  }
}

public class BubbleSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Bubble Sort");
  }
}

public class MergeSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Merge Sort");
  }
}

public class HeapSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
   Console.WriteLine("Executing Heap Sort");
  }
}

Now let’s head to our Client Class and Inject the Strategy, which would be used to sort the Array.

internal class Client
{

  private int[] _IntArray;

  public Client(int[] IntArray)
  {
    _IntArray = IntArray;
  }

  public void Sort(ISortStrategy Strategy)
  {
   Strategy.Sort(_IntArray);
  }
}

As you can see , the Client Class is devoid of any direct dependencies as well as any nasty conditional statements. Yes, its a good idea to do away with Conditional Statements , especially those long if-else or switch cases as it can increase the cyclomatic complexity of the code. The Strategy is injected directly in the client, which invokes it.

Complete collection of articles on Design Patterns can be found here

Caliburn Micro #02 : BindableCollection & Events

In the previous part of this series, we looked into some of the basics of using Caliburn Micro. In this part, we will continue with few more examples, how to invoke a method on an event.

But before we do that, let’s expand our application a bit. Currently the application has two Text controls , wired up to a property (FirstName) in the View Model. Let’s expand it further and have 2 more properties, LastName and FullName.

Our expanded ViewModel Looks like following now.


private string _FirstName = "Jia Anu";

public string FirstName
 {
 get { return _FirstName; }
 set
 {
 _FirstName = value;
 NotifyOfPropertyChange(nameof(FirstName));
 NotifyOfPropertyChange(nameof(FullName));
 }
 }

private string _LastName;

public string LastName
 {
 get { return _LastName; }
 set {
 _LastName = value;
 NotifyOfPropertyChange(nameof(LastName));
 NotifyOfPropertyChange(nameof(FullName));
 }
 }

We will add additional controls to our View, and add the necessary binding.

        <!--Row 1 Starts here -->
        <Label Grid.Column="0" Grid.Row="0">Full Name</Label>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2"></TextBlock>
        <!--Row 1 Ends here -->

        <!--Row 2 Starts here -->
        <Label Grid.Column="0" Grid.Row="1">First Name</Label>
        <TextBox x:Name="FirstName" Grid.Row="1" Grid.Column="1"></TextBox>
        <!--Row 2 Ends here -->

        <!--Row 3 Starts here -->
        <Label Grid.Column="0" Grid.Row="2">Last Name</Label>
        <TextBox x:Name="LastName" Grid.Row="2" Grid.Column="1"></TextBox>
        <!--Row 3 Ends here -->

Bindable Collections

Let’s expand it futher, let’s introduce a model now. We will add a model in our Model Folder.

public class DeparmentModel
{
public string DepartmentName { get; set; }
public string Supervisor { get; set; }

}

And introduce two new properties for our View Model.

private BindableCollection _DepartmentCollection = new BindableCollection();

public BindableCollection DepartmentCollection
{
get { return _DepartmentCollection; }
set
{
_DepartmentCollection = value;

}
}

private DeparmentModel _SelectedDepartment;

public DeparmentModel SelectedDepartment
{
get { return _SelectedDepartment; }
set
{
_SelectedDepartment = value;
NotifyOfPropertyChange(nameof(SelectedDepartment));
}
}

We will delve more into BindableCollection later, but for now, let’s think of it as a means for binding to a combo box. Since we are not using any Db for this example, lets hard code some values in the constructor.

public ShellViewModel()
{
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Finance", Supervisor = "John Tommothy" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Development", Supervisor = "Alex Brown" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Human Resource", Supervisor = "Dennis Burton" });
}

We will add a Combo box and another Text Area in our XAML to accodomate the changes. The XAML looks like following now.

        <!--Row 4 Starts here -->
        <Label Grid.Column="0" Grid.Row="3">Department</Label>
        <ComboBox Grid.Column="1" Grid.Row="3" ItemsSource="{Binding DepartmentCollection}" DisplayMemberPath="DepartmentName"
                 SelectedItem="{Binding SelectedDepartment,Mode=OneWayToSource}" ></ComboBox>
                <!--Row 4 Ends here -->

        <!--Row 5 Starts here -->
        <Label Grid.Column="0" Grid.Row="4">Supervisor</Label>
        <TextBlock Grid.Column="1" Grid.Row="4" x:Name="SelectedDepartment_Supervisor"></TextBlock>
        <!--Row 5 Ends here -->

Run our application and you can now see the combo box in action. Everytime you change the Department, the corresponding Supervisor is displayed the TextArea.

Events and EventGuards

Now then, lets head to adding a button to clear the selected values. We will first introduce a method.

public void ClearTextMethod(string firstName,string lastName)
{
FirstName = string.Empty;
LastName = string.Empty;
}

We are passing two parameters, however we are not quite using it. However, the sigificance of the parameters come into light when we add our second method, CanClearTextMethod

public bool CanClearTextMethod(string firstName, string lastName)
{
return !string.IsNullOrEmpty(firstName);
}

Notice the naming patterns used for the methods and parameters. The ‘Can’ Method is named in such a way that it prepends ‘Can’ to the ClearTextMethod. This aids Caliburn Micro to recognize this method needs to be evaluated to enable CanClearTextMethod.

Also the parameters. They are named as similiar as the FirstName and LastName Properties. These are the properties which dictate whether to enable the method or not, which is being passed as paramers. Ensure the naming is correct and Caliburn Micro does the magic for you.

Lets add the necessary XAML for adding a button and wiring it up with the method.

        <Button Grid.Column="0" Grid.Row="5" x:Name="ClearTextMethod">Clear</Button>

The entire code sample for this examples can be found here. 

Complete List of Tutorials on Caliburn.Micro can be found here