Ayende's Design Guidelines: Rule #1

When creating a generic method, strongly prefer to supply an overload that is not generic, can accept the types manually, and is externally visible.

Reasoning: The generic version often looks significantly better than the non generic version, but it comes with a cost. It assumes that you know, up front, what the types are. When you are writing any type of generic code, this is almost always not the case and your generic method is useless in that scenario.

Example: myContainer.RegisterComponent<IService, ServiceImpl>(); is a good syntax to have, but the problem with that is that it cannot be used with this code:

foreach(Type type in GetComponentTypes())
{
    myContainer.RegisterComponent<type.GetInterfaces()[0], type>();
}

Since we cannot use the generic overload, we need to resort to trickery such as MakeGenericMethod and friends. This is costly at runtime, obscure and generally make life harder all around.

Print | posted on Saturday, February 23, 2008 2:15 AM

Feedback


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/23/2008 12:15 PM Symon Rottem

I completely agree - this is something I've run into a few times and providing an API without non-generic alternatives just generates friction for the consumer.


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/23/2008 4:25 PM Christopher Bennage

I guess the context here is when you are publishing an API?
In a project where I control and consume the code base, it's YAGNI.


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/23/2008 5:02 PM Ayende Rahien

Yes, this is for published API.
If you control the code, it doesn't really matter, since you can always change that.
Nevertheless, you need to carefully consider what you believe a published API is


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/24/2008 1:43 AM Andrey Shchekin

Exactly. http://api.castleproject.org/html/M_Castle_MicroKernel_DefaultKernel_ResolveServices__1.htm immediatelly comes to mind.


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/24/2008 1:43 AM Andrey Shchekin

Exactly. http://api.castleproject.org/html/M_Castle_MicroKernel_DefaultKernel_ResolveServices__1.htm immediatelly comes to mind.


Gravatar

# re: Ayende's Design Guidelines: Rule #1 2/26/2008 7:51 PM Francois Tanguay

That's why I wished there was a way to promote a type object into a generic scope:

foreach(Type type in GetComponentTypes())
{
// New using scope keyword!
using<TInterface with type.GetInterfaces()[0], T with type>()
{
myContainer.RegisterComponent<TInterface, T>();
}
}

Comments have been closed on this topic.