Think Before Coding

To content | To menu | To search

Thursday, October 22, 2009

C# Static interfaces - Take 2

As Romain was pointing in the comments, I totally missed to tell where I wanted to go with this static interface things. Need more sleep these days…

So here it is.

No I don’t want to do this

The point was not to enable something like this :

   int value = ICountable.Count;

Static interfaces have no implementation exactly like interfaces.

With interfaces, you need an instance (usually in a variable or member) to find the actual implementation and call it. With static interfaces, you need a type.

There are two ways to specify a type:

  • with its type name (Sample4.Count)
  • with a generic type parameter (T.Count)

I was also proposing a way to specify a type for extension methods.

Where it would be useful - operators

The reason why everybody is asking for static members in interfaces is ultimately to have operators in interfaces.

Imagine :

    public static interface IArithmetic<T>

    {

        static T operator +(T x, T y);

        static T operator -(T x, T y);

        static T operator *(T x, T y);

        static T operator /(T x, T y);

    }

Now you can write generic code like :

        public static T Power<T>(this T value, int count) where T : IArithmetic<T>

        {

            var result = T.Identity;

 

            for (int i=0;i<count;i++)

                result = result*value;

 

            return result;

        }

Cool !

This way, no need for the 20 overloads of Enumerable.Sum, it would work for any type presenting the expected static interface.

Wednesday, October 21, 2009

C# Static interfaces

Read the latest post on the subject:

C# Static Interfaces - Take 3

No DDD today, let’s talk a bit about our favorite language after a short night (I should really tell my neighbors that 3am is not the good time to move their furniture all around the flat).

You can find requests for static methods in interfaces all over the internet..

But there are good reasons not to.

According to Eric Lippert, the main reasons is the difference in inheritance between static methods and instance method du to the absence of shared slots between static methods.

Mixing both static methods and instance methods in interfaces would lead to a real nightmare when you try to understand what really happens.

But why does this question arise so often then ? What’s really needed ?

Static classes as type instances

Let’s take a simple class with both static and instance members :

    class Sample

    {

        // static part

        private static int count;

        public static int Count { get { return count; } }

 

        // instance part

 

        private readonly string name;

 

        public Sample(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

Here, Count is a static Property. Static part is different from instance part in that static part exist only once per type.

But we could see static part as being an object with reference is type name.

Why would these object not have interfaces ?

Let refactor this a bit :

 

    public class Sample2

    {

        public sealed class Sample2Class

        {

            internal int count;

            public int Count { get { return count; } }

        }

        public static readonly Sample2Class Class = new Sample2Class();

 

        private readonly string name;

 

        public Sample2(string name)

        {

            this.name = name;

        }

 

        public void Method()

        {

            Class.count++;

            Console.WriteLine("Total count {0} incremented by {1}", Class.count, name);

        }

    }

Here, the only static member is Class, that acts as a singleton for the type. Note that I had to change the count modifier to internal. The behavior is not the same, but it’s conceptually equivalent.

We can make something less extreme :

 

    public class Sample3

    {

        private static int count;

        public static int Count { get { return count; } }

 

        private readonly string name;

 

        public static readonly Sample3Class Class = new Sample3Class();

 

        public sealed class Sample3Class

        {

            public int Count { get { return Sample3.Count; } }

        }

 

        public Sample3(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

 

Here, we added only a proxy of public methods and properties on the singleton class.

We could define an interface that would be implemented by Sample3Class that would provide the missing slot concept that Eric Lipperts talk about.

We can also see here that there is no point mixing static and instance method in interface since inheritance rules differs.

Static Interface

Imagination at work. Let’s define static interface as we can define static classes :

    public static interface ICountable

    {

        static int Count { get; }

    }

and implement it on our sample :

    public class Sample4 : ICountable

    {

        private static int count;

        public static int Count { get { return count; } }

 

        private readonly string name;

 

        public Sample4(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

The C# compiler would be responsible for creating a singleton stub in the class. Since the goal is to provide a function table, this could also be handled at a lower level by the CLI.

Now, we can have interesting language extensions.

Static member access in generics

Let see it in action :

        public static bool IsInstanciated<T>() where T: ICountable

        {

            return T.Count != 0;

        }

There is no ambiguity when using this method since values of parameter T are known at compilation time. The C# compiler could replace the static call with a interface call on the proxy. On a CLI version, the JIT compiler could resolve it once and for all and emit a static call. Use of a child type whose parent type implements the interface should not be allowed, the compiler could report this.

This could be combined with an extension method syntax to provide extension methods on types :

        public static bool IsInstanciated(static ICountable type)

        {

            return type.Count != 0;

        }

This one is a bit twisted, and I would gracefully admit changes in the syntax, but the point is that it would enable on type/classes the same kind of thing that Linq offers with interfaces : put the minimum set of methods in interface, then add lots of features around interface with extension methods.

Back to reality

Ok, I should sleep at night, but who knows, it’s perhaps useful.

If anyone sees other applications… just drop a comment.

Tuesday, May 19, 2009

IOC Container, Go Hide (part 2)

Ok, there seem to be some misunderstanding with the suggestion from my previous post.

A framework manipulates two kind of objects :

  • its objects
  • your objects

You don’t care about its object, you care about yours.

So you want to be able to take part in your objects instantiation so that you can do your own stuff (inject dependencies, handle differently based on runtime behavior…).

Without container

Look at Asp.net, when it needs to create an Http Handler, it calls a IHttpHandlerFactory.

You can provide your own IHttpHandlerFactory, just implement its two methods (the second one can even be left empty in most cases) :

public interface IHttpHandlerFactory
{
// Methods
IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
void ReleaseHandler(IHttpHandler handler);
}

In the GetHandler method, you’re free to use the container you want ! But you can also do this :

return new CustomHttpHandler(theDependency);

Or make a call to another factory, or… or…

With container

The framework ask to provide a container so that the it can simply run. Ok there is also a builtin container so I don’t have to care.

But if I want to do a custom instantiation I have now to implement the following interface :

public interface IServiceLocator : IServiceProvider
{
// Methods
IEnumerable<TService> GetAllInstances<TService>();
IEnumerable<object> GetAllInstances(Type serviceType);
TService GetInstance<TService>();
TService GetInstance<TService>(string key);
object GetInstance(Type serviceType);
object GetInstance(Type serviceType, string key);
}

This interface will be used when any instantiation will occur. If I mess internal framework instantiation. Wooch !

And there is no clear meaning with this interface. It should be able to instantiate any object requested.

It doesn’t give a clean and clear API in my personal opinion !

Using an IOC container as an extension point is clearly an over abstraction !

Provide clear, focused extensibility points

The framework doesn’t need to be extended on every instantiation, especially when instantiation its own internal stuff. There are clear extension points, and a specific interface should be created for each.

This is just a framework design good practice.

Then, there is no need to show the container you use to the outside, and it resolves potential version conflicts.

Thursday, May 7, 2009

Decimal, what are those trailing zeros ?

Yesterday, I stumbled on something I didn’t expect at all…

An exception appeared while testing my code that I had been carefully writing following Design By Example..

Looking in my debugger my decimal two variables had value 4M.

But calling ToString on it led to different results : “4” and “4.00”…

What the heck ?! How come ?

 

I should have known this

Yes, the MSDN state it explicitly :

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

And I did not know that, did you ?

 

Try it yourself

you can try it yourself :

Console.WriteLine(1m);      // 1
Console.WriteLine(1.0m);    // 1.0
Console.WriteLine(1.00m);   // 1.00

Console.WriteLine(1m == 1.0m); // true
Console.WriteLine(1m.ToString() == 1.0m.ToString()); // false

The decimal.Parse function also preserve trailing zeros :

Console.WriteLine(decimal.Parse("1.0", CultureInfo.InvariantCulture)); // 1.0
Console.WriteLine(decimal.Parse("1.000", CultureInfo.InvariantCulture)); // 1.000

 

The explanation

The decimal type internally represents values using an 96 bit integer and a negative power of 10 (between 0 and 28).

Those values are simply internally stored like this :

1.0 –> 10 * 10^-1
1.000 –> 1000 * 10^-3

You can check it using the decimal.GetBits method.

The trailing zeros are even maintained in arithmetical operations :


Console.WriteLine(2.0m * 3.00m);  // 6.000

But are handled correctly by the equality and comparison methods :

Console.WriteLine(1m == 1.0m);  // true
Console.WriteLine(1m.GetHashCode() == 1.0m.GetHashCode()); // true

 

Do you know other secrets like this ?

Of course, my unit tests did not test case I didn’t expect to happen !

But, Hey ! If you knew it, you should have told me before !

What secret feature/behavior in the .Net framework or in the C# language do you know ?