Extension Methods and inheritance

Remember that extension methods are static methods !

Since their introduction in the Framework, extension methods have been a very simple mean to add functionality into class or on top of interfaces. Without extension methods, there would be no LINQ-style syntax allowing us to chain easily calls such as :

words
    .Where(w => w.StartsWith("M"))
    .Select(w => w.ToUpper());

The key to this pattern has been described many times and is built on the principle that the extension methods “Where” and “Select” take an IEnumerable<T> (T is string here) as their first input parameter, and return an other IEnumerable<T>. This way, the next call in the chain will use the previous output as its input.

But when implementing an using extension methods, when it comes to inheritance you have to remember that these methods are static ! What I mean here is that the method resolution will occur at compile time and not at runtime. This leads to extension methods having quite the same behaviour as instance methods written using the “new” keyword (as opposed to “overrides”).

Let me explain that with an example. I first define here two interfaces, the second being a specialization of the first.

public interface ISoundMaker
{
    string MakeSound(bool loud);
}

public interface ITalker : ISoundMaker
{
    string[] MakeSentence(int wordCount);
}

I then define a class Baby which implements the interface ITalker :

public class Baby : ITalker
{
    /* Hidden implementation */

    public string MakeSound(bool loud)
    {
        string sound = InfiniteSoundsSequence.First();
        return loud ? sound.ToUpper() : sound.ToLower();
    }

    public string[] MakeSentence(int wordCount)
    {
        return InfiniteWordsSequence.Take(wordCount).ToArray();
    }
}

In the hidden implementation, two (statefull) infinite sequences are defined, in order to yield sounds or words as needed. These sequences are independent and yield different values.

I now define two “Sing” extension methods, respectively on top of the ISoundMaker and ITalker interfaces :

public static class SoundTalkExtensions
{
    public static string Sing(this ISoundMaker soundMaker,
                                int wordCount)
    {
        IEnumerable<string> words = Enumerable
            .Range(0, wordCount)
            .Select(i => soundMaker.MakeSound(i % 2 == 0));

        return String.Join(" ", words);
    }

    public static string Sing(this ITalker talker,
                                int wordCount)
    {
        IEnumerable<string> words = talker
            .MakeSentence(wordCount)
            .Select((w, i) => i % 2 == 0 ? w.ToUpper() : w);

        return String.Join(" ", words);
    }
}

Basically, the two methods do the same work : they take either sounds or words and alternate lowercase and uppercase items.

And now if we write the following unit test…

ISoundMaker soundMaker = new Baby();
ITalker talker = new Baby();

string soundSong = soundMaker.Sing(15);
string talkSong = talker.Sing(15);

?? Assert.AreEqual(soundSong, talkSong) ??

It fails !

The two instances of the Baby class are identical, but the extension methods calls are resolved based on the type of the declared variables into which theses instances are stored. One of these instances is a ISoundMaker, and the other one is a ITalker.

Even if the Baby class implements ITalker, when an instance is stored in a variable of type ISoundMaker, the extension method will be the ISoundMaker’s one.

So here for instance the variables soundSong and talkSong have the following values :

soundSong = “MAMA dada AAA gaga BUBU mamma DADA aaa GAGA bubu MAMA dada AAA gaga BUBU

talkSong = “MAMA life HAD just BEGUN But NOW I’ve GONE and THROWN it ALL away MAMA

In the next post, we will see why you must understand that clearly before using LINQ Providers (LINQ to something) or PLINQ (Parallel LINQ to objects).

Posted in LINQ | Tagged , , | Comments Off

Functional Inspiration – Revisiting the With extension method

Return to the very first post for improvement

This is the fourth entry of a blog series about how functional programming, and the F# training I recently went to, gives me inspiration in my day-to-day work in C#. It is going to propose an other implementation of the “With” method, which this time deals with immutable data structures.

No long explanation today, here is a very simple immutable class representing the same Person as in the first post :

public class Person
{
    public readonly string Name;
    public readonly string Town;
    public readonly string Country;
    public readonly int Age;

    public Person(string name, string town,
                    string country, int age)
    {
        this.Name = name;
        this.Town = town;
        this.Country = country;
        this.Age = age;
    }
}

We can this time see that all the fields are defined “readonly”, making that data structure immutable. As the value of the fields can only be modified inside the constructor, we will not be able to use a delegate parameter as previously. We will have to find a way to modify the values in the constructor.

To do so, we define a second (private) constructor. Surprise ! The Irrelevantable construct shows up :

private Person(
    Person source,
    Irrelevantable<string> name,
    Irrelevantable<string> town,
    Irrelevantable<string> country,
    Irrelevantable<int> age)
{
    this.Name = name.IsRelevant ? name.Value : source.Name;
    this.Town = town.IsRelevant ? town.Value : source.Town;
    this.Country = country.IsRelevant ? country.Value
                                        : source.Country;
    this.Age = age.IsRelevant ? age.Value : source.Age;
}

When this constructor is called, it populates the properties using either the source Person’s properties, either the following arguments, depending on whether they are “relevant”. If this constructor is called with a single “relevant” value, it acts quite as out original “With” method.

And using the C#4.0 default values capabilities, we can make things even better :

public Person With(
    Irrelevantable<string> name
        = default(Irrelevantable<string>),
    Irrelevantable<string> town
        = default(Irrelevantable<string>),
    Irrelevantable<string> country
        = default(Irrelevantable<string>),
    Irrelevantable<int> age
        = default(Irrelevantable<int>))
{
    return new Person(
        this,
        name: name,
        town: town,
        country: country,
        age: age);
}

This public “With” method defines default values for all properties, allowing us to give only the values of the properties that we want to change.

Person someone = new Person(
    name: "Luc",
    town: "Paris",
    country: "France",
    age: 29);

Person someoneElse = someone.With(age: 30);
Person someAmerican = someone.With(
                            name: "Luke",
                            country: "United States");

You can notice here that this time the syntax allows us to define multiple changes in a concise form, and works nicely with immutable data structures !

Posted in Functional Inspiration | Tagged , | Comments Off

Functional Inspiration – Irrelevantable, part 2

Trying to express something more than Nullable<T>

Friday evening, the girls are in bed, the wife is out with friends… It seems that it is the perfect time to finish this post !

This is the third entry of a blog series about how functional programming, and the F# training I recently went to, gives me inspiration in my day-to-day work in C#. This post will show how you can build in F# the Irrelevantable type previously built in C#.

Let’s go straight to the code, here is the structure :

type Irrelevantable<'a> =
    | Relevant of 'a
    | Absent
    | Irrelevant

Using a very simple discriminated union type, we can easily express the three distinct cases needed.

Let’s now see how this type can be used. I first define a Product Type and a sample products list :

type Product =
  { Name: string;
    ProductType: string;
    Strike: Irrelevantable<decimal>;
    Premium: Irrelevantable<decimal>;
    TradedPrice: Irrelevantable<decimal>
    SwapPrice: Irrelevantable<decimal>; }

let products =
  [ { Name = "568745";
      ProductType = "Option";
      Strike = Relevant(176m);
      Premium = Relevant(3.72m);
      TradedPrice = Irrelevant;
      SwapPrice = Irrelevant } ;
    { Name = "568746";
      ProductType = "Option";
      Strike = Relevant(176m);
      Premium = Absent;
      TradedPrice = Irrelevant;
      SwapPrice = Irrelevant } ;
    { Name = "568747";
      ProductType = "Swap  ";
      Strike = Irrelevant;
      Premium = Irrelevant;
      TradedPrice = Relevant(15.3m);
      SwapPrice = Relevant(15.6m) } ]

The goal is now to print a report based on the products. I then define a few utility / formatting functions :

let formatValue formatter value =
    match value with
    | Relevant(data) -> (formatter data)
    | Absent -> ""
    | Irrelevant -> "-"

let padLeft (value:string) =
    value.PadLeft(7)

let formatPrice =
    formatValue (fun (d:decimal) -> d.ToString("N2"))
    
let getLine vals =
    System.String.Join(" | ", vals |> Seq.map padLeft)

let getValues p = 
    p.Name ::
    p.ProductType ::
    (formatPrice p.Strike) ::
    (formatPrice p.Premium) ::
    (formatPrice p.TradedPrice) ::
    (formatPrice p.SwapPrice) :: []

let getProductLine =
    getValues >> getLine

And I use these functions to generate the lines to print, beginning with a header line :

let headerLine =
  ( "Ref." ::
    "Type" ::
    "Strike" ::
    "Premium" ::
    "Price" ::
    "Swap price" :: [])
  |> getLine

let productLines =
  products |> List.map getProductLine

let allLines =
    headerLine :: productLines

Finally, I can print the report :

let test = allLines |> List.iter (printfn "%s")

And the output is the following :

   Ref. |    Type |  Strike | Premium |   Price | Swap price
 568745 |  Option |  176,00 |    3,72 |       - |       -
 568746 |  Option |  176,00 |         |       - |       -
 568747 |  Swap   |       - |       - |   15,30 |   15,60

You can then notice the distinction between the the absent value (the Premium column for the second product) and the values that have no meaning.

Posted in Functional Inspiration | Tagged , | Comments Off

Functional Inspiration – Irrelevantable, part 1

Trying to express something more than Nullable<T>

This is the second entry of a blog series about how functional programming, and the F# training I recently went to, gives me inspiration in my day-to-day work in C#. This post will show how you can build an Irrelevantable<T> generic type in C#, and how you could do the same in F#.

I had recently to cope with a situation where a value, let’s say a price for instance, could have 3 different states :

  1. It could simply be a valid known price,
  2. It could be absent,
  3. It could be irrelevant : for a given situation, that price could have neither a value nor none, this price has simply no possible meaning.

To handle the present / absent cases, if the value is a reference type then the null value is sufficient, if it is a value type we can use a Nullable<T>. But how do you store the “relevant / irrelevant” status ? As I had to handle that for several properties, I wanted to build a structured object that I could reuse. As I had several different types of data, I also wanted it to be generic. My answer was simply to build an Irrelevantable<T> structure with the same behavior as the Nullable<T> structure.

public struct Irrelevantable<T>

As for Nullable<T>, a structure is appropriate, because it will be copied by value, and not by reference. Then comes the members, properties and the constructor :

private bool isRelevant;
public bool IsRelevant { get { return isRelevant; } }

private T value;
public T Value
{
    get
    {
        if (!this.IsRelevant)
            throw new InvalidOperationException(
                "This Irrelevantable<T> instance" +
                "is irrelevent.");
        return this.value;
    }
}

public Irrelevantable(bool isRelevant, T value)
{
    this.isRelevant = isRelevant;
    this.value = value;
}

The next step was to override the base methods for object comparison :

public override int GetHashCode()
{
    return this.IsRelevant
        ? this.value.GetHashCode()
        : -1;
}

public override bool Equals(object other)
{
    if (!this.IsRelevant)
    {
        if (other is Irrelevantable<T>)
        {
            return !((Irrelevantable<T>)other).IsRelevant;
        }

        return false;
    }
    else
    {
        if (other is Irrelevantable<T>)
        {
            return this.value.Equals(
                ((Irrelevantable<T>)other).value);
        }

        return this.value.Equals(other);
    }
}

This way, two Irrelevant objects are equal if they have the same type, and two relevant objects are equal if they hold equal values.

Next, we define implicit and explicit cast operators in order to ease the use of the type :

public static implicit operator Irrelevantable<T>(T value)
{
    return new Irrelevantable<T>(true, value);
}

public static explicit operator T(Irrelevantable<T> value)
{
    return value.Value;
}

Finally, we add a static property to represent the Irrelevant value :

public static Irrelevantable<T> Irrelevant
{
    get
    {
        return new Irrelevantable<T>(false, default(T));
    }
}

The code can now be used to write such expressions :

Irrelevantable<string> someString = "Some data";
Irrelevantable<string> irrelevantString =
    Irrelevantable<string>.Irrelevant;

Irrelevantable<int?> noInt = null;
Irrelevantable<int?> someInt = 10;
Irrelevantable<int?> irrelevantInt =
    Irrelevantable<int?>.Irrelevant;

As I chose to make the cast from the standard type to Irrelevantable implicit, and the opposite cast explicit (as the Nullable type does), we have the same feeling casting from and to Nullable, Irrelevantable and object :

object obj = 1;
int? nullable = 2;
Irrelevantable<int> irrelevantable = 3;

int fromObj = (int)obj;
int fromNullable = (int)nullable;
int fromIrrelevantable = (int)irrelevantable;

To be honest, the C# code sample upon which this post is written had been coded before I could do the same in F#. But when I saw this code again a couple days ago I had this immediate thought : “That would be ways simpler in F# !”

The F# implementation a the same functionality will be covered in the next post, but don’t expect it to be very long !

Posted in Functional Inspiration | Tagged , | Comments Off

Functional Inspiration – The With extension method

Adding a “With” extension method mimicking F#

This is the first entry of a blog series about how functional programming, and the F# training I recently went to, gives me inspiration in my day-to-day work in C#. The first one will show how you can build a “with”-like feature in C#.

One of the many features of F# that stroke me during Robert Pickering’s “Beginning F#” course, was the Record Type and its ease of use. For those of you that don’t know F#, a record type can be compared with a Tuple whose properties would be named.

For instance, this F# snippet defines a Record Type Person with two properties Name and Age.

type Person =
    { Name: string;
      Town: string;
      Country: string;
      Age: int }

With this type defined, it is now possible to define an instance of that type :

let someone =
    { Name = "Luc";
      Town = "Paris";
      Country = "France";
      Age = 29 }

A very handy feature of F# lets us now write this :

let someoneElse =
    { someone with
        Age = 30 }

The “with” keyword allow us to define “someoneElse” as a copy of “someone”, stating only the values of the properties to change.

In a project I have been working on recently, I had exactly the same need of defining a new instance with very little changes, but in C#. In order to do this, I wrote a simple extension method, base on the ICloneable interface :

public static class ClonableExtensions
{
    public static T With<T>(this T original,
                            Action<T> withAction)
        where T : ICloneable
    {
        T copy = (T)original.Clone();
        withAction(copy);
        return copy;
    }
}

With this extension method, if we define a class Person that implements the ICloneable interface, like this :

public class Person : ICloneable
{
    public string Name { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
    public int Age { get; set; }

    public object Clone()
    {
        return new Person()
        {
            Name = this.Name,
            Town = this.Town,
            Country = this.Country,
            Age = this.Age
        };
    }
}

It is now possible to use the generic With extension method to write the following code :

Person someone = new Person()
{
    Name = "Luc",
    Town = "Paris",
    Country = "France",
    Age = 29
};

Person someoneElse = someone.With(p => p.Age = 30);

I find this construct quite expressive and readable, but please note that there are several drawbacks :

  1. The C# objet has to be mutable. Its “Age” property is set after the object is created by the Clone method. Even though the Clone method could have used a copy constructor instead of setting properties, the generic With method must overwrite the properties values. Addendum : this problem is now solved in “Revisiting the With extension method”.
  2. The syntax to use in order to modify more than one property is less readable, because a lambda expression with multiple instructions has to be written between accolades.
  3. In the end, whatever you do, someoneElse will be 30, and his name is Luc.
Posted in Functional Inspiration | Tagged , | Comments Off