Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 10 | Comments: 37

filter by tags archive

ChallengeStrongly typing weakly typed code

time to read 1 min | 69 words

How would you make the following code work?

public static class Security
{
	public static string GetDescription(Type entityType, Guid securityKey)
	{
		Guard.Against<ArgumentException>(securityKey == Guid.Empty, "Security Key cannot be empty");
		IEntityInformationExtractor<TEntity> extractor = IoC.Resolve<IEntityInformationExtractor<TEntity>>();
		return extractor.GetDescription(securityKey);
	}
}

You can't change the entity type parameter to a generic parameter, because you only know about it at runtime. This is usually called with:

Security.GetDescription(Type.GetType(permission.EntityTypeName), permission.EntitySecurityKey.Value);

More posts in "Challenge" series:

  1. (28 Apr 2015) What is the meaning of this change?
  2. (26 Sep 2013) Spot the bug
  3. (27 May 2013) The problem of locking down tasks…
  4. (17 Oct 2011) Minimum number of round trips
  5. (23 Aug 2011) Recent Comments with Future Posts
  6. (02 Aug 2011) Modifying execution approaches
  7. (29 Apr 2011) Stop the leaks
  8. (23 Dec 2010) This code should never hit production
  9. (17 Dec 2010) Your own ThreadLocal
  10. (03 Dec 2010) Querying relative information with RavenDB
  11. (29 Jun 2010) Find the bug
  12. (23 Jun 2010) Dynamically dynamic
  13. (28 Apr 2010) What killed the application?
  14. (19 Mar 2010) What does this code do?
  15. (04 Mar 2010) Robust enumeration over external code
  16. (16 Feb 2010) Premature optimization, and all of that…
  17. (12 Feb 2010) Efficient querying
  18. (10 Feb 2010) Find the resource leak
  19. (21 Oct 2009) Can you spot the bug?
  20. (18 Oct 2009) Why is this wrong?
  21. (17 Oct 2009) Write the check in comment
  22. (15 Sep 2009) NH Prof Exporting Reports
  23. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  24. (01 Sep 2009) Why isn’t select broken?
  25. (06 Aug 2009) Find the bug fixes
  26. (26 May 2009) Find the bug
  27. (14 May 2009) multi threaded test failure
  28. (11 May 2009) The regex that doesn’t match
  29. (24 Mar 2009) probability based selection
  30. (13 Mar 2009) C# Rewriting
  31. (18 Feb 2009) write a self extracting program
  32. (04 Sep 2008) Don't stop with the first DSL abstraction
  33. (02 Aug 2008) What is the problem?
  34. (28 Jul 2008) What does this code do?
  35. (26 Jul 2008) Find the bug fix
  36. (05 Jul 2008) Find the deadlock
  37. (03 Jul 2008) Find the bug
  38. (02 Jul 2008) What is wrong with this code
  39. (05 Jun 2008) why did the tests fail?
  40. (27 May 2008) Striving for better syntax
  41. (13 Apr 2008) calling generics without the generic type
  42. (12 Apr 2008) The directory tree
  43. (24 Mar 2008) Find the version
  44. (21 Jan 2008) Strongly typing weakly typed code
  45. (28 Jun 2007) Windsor Null Object Dependency Facility

Comments

Jon Skeet

It's not entirely clear to me what you're trying to make strongly typed. Is the issue just that IEntityInformationExtractor is only strongly typed, and ditto IoC.Resolve?

You're not actually using any extra information about the entity type as far as I can see (it's effectively just a lookup key), so I'm not sure where we're going...

I suspect reflection will be involved somewhere though - you could create a generic overload containing the body of your code above, and then call it with reflection given a Type. It's not pretty, but assuming you can't change IEntityInformationExtractor (e.g. to add a nongeneric base interface) and IoC.Resolve, that's probably the most immediate option.

Mind you, it's Monday morning and I suspect I'm missing the point by quite a long way.

Jon

Ayende Rahien

Yes, IEntityInformationExtractor is only strongly typed, and I am using that as a way to separate functionalities.

Sasha Goldshtein

Use Type.MakeGenericType to construct the generic type in runtime and do your magic with reflection. You could also cache the generic types constructed to save a little performance if it's important.

Jon Skeet

MakeGenericType wouldn't help here, as it's a generic method within a nongeneric type. MethodInfo.MakeGenericMethod is the call you need, I believe.

Reflection around generics is somewhat evil in a few ways, unfortunately - particularly around generic methods - but I don't think there should be any problems in this particular case.

I'd say it's worth caching the generic method definition (i.e. the one you'll call MakeGenericMethod on) - but I'm not sure it's worth caching the closed constructed definition unless you're really likely to call it often for the same type.

I'm not sure whether Ayende already has the solution and is merely testing his readership, or whether working code would be appreciated. I'm happy to provide a sample if it would help...

Jon

Ayende Rahien

Oh, I have a solution already, and it is based on MakeGenericMethod indeed.

Check near the end of this file:

https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/rhino-security/Rhino.Security/Security.cs

I predict a good chance for using this more than once per type, so it is worth caching it, I took it one step further and removed the use of reflection on the second iteration.

Reshef Mann

Maybe refactor it to have something like:

IEntityInformationExtractorFactory extractorFactory = IoC.Resolve();

IEntityInformationExtractor extractor = extractorFactory.Resolve(entityType);

return extractor.GetDescription(securityKey);

It probably isn't strongly typed as u would like it, but it will work.

Ayende Rahien

I want to keep the IEntityInformationExtractor as a generic type, and I am willing to exchange complexity in my code for simplicity in the implementation of it, since those are going to be more common

Francois Tanguay

I always wished we could have a "generic scope operator" that transforms a Type argument into a generic scope:

generic(with entityType)

{

return IoC.Resolve<IEntityInformation>().GetDescription().

}

Max
Max

The direct solution would be to make Permission generic, if possible..

Ted Elliott

I'll second the wish for a "generic scope operator", working with generics using reflection is really nasty code. You wouldn't have compile time type safety though, since there would be no way to verify any constraints that the generic might have, which I guess you don't really have anyway if you're doing it through reflection.

Ayende Rahien

Max,

Permission is an entity. I try really hard never to make my entities generic.

Ayende Rahien

Ted,

Constraints are enforced even when you are using generics.

Mike Moore

Oren, this isn't an example of weak typing. Your code is strongly typed. Your code is also statically typed. You do not change the type system of the language by simply refering to your objects by an interface. One could argue that casting an object to a specific class is a form of dynamic typing, but even then your code has a static type check at compile time.

http://en.wikipedia.org/wiki/Strong_typing

http://en.wikipedia.org/wiki/Weak_typing

http://en.wikipedia.org/wiki/Typesystem#Statictyping

http://en.wikipedia.org/wiki/Typesystem#Dynamictyping

http://en.wikipedia.org/wiki/Typesystem#Strongandweaktyping

Ayende Rahien

Mike, you seem to have missed the part where I have Type entityType and I need to get from there to TEntityType.

Mike Moore

No, I read the article and I get that. My point is that problem isn't strong vs. weak typing. You can't just take an established terms like "strongly typed" and "weakly typed" and use them to mean something else. The problem you want to solve here isn't overcoming weak typing. (I'd argue that you are trying to overcome static typing, but I think I've been pretty clear on the subject to this point and there is no need to beat that dead horse.)

Jon Skeet

'Strongly typed' and 'weakly typed' aren't terribly well established though. Everyone uses them to mean different things. From the first Wikipedia link:

However, these terms have been given such a wide variety of meanings over the short history of computing that it is often difficult to know, out of context, what an individual writer means when using them.

and

I spent a few weeks... trying to sort out the terminology of 'strongly typed,' 'statically typed' 'safe,' etc., and found it amazingly difficult.... The usage of these terms is so various as to render them almost useless.

Or, to use someone else's words: "For practical purposes, 'strong' means 'a type system which I like' and 'weak means 'a type system which I dislike' and therefore they are of little utility."

I'm not sure I'd go quite that far myself, but certainly there's a lot of ambiguity about the terms.

Mats Helander

Jon,

I agree that the concept of "strong" vs "weak" typing is somewhat ill defined...but I would still argue that the concept of "static" vs "dynamic" typing has managed to maintain a more coherent and useful meaning.

And so when something is seemingly a fairly clearcut example of static vs dynamic typing it is better to use those terms rather than strong vs weak (which I agree ever so often reveals more about the preferences of the person using the term than the type systems they want to describe).

Jon Skeet

Yes, I'd agree about static and dynamic being reasonably well defined.

I'd say in this case that Ayende as a statically and generically typed UI, but wishes to use it in a dynamic way - i.e. some of the type information is only known at execution time. The call to MakeGenericMethod is the bridge from dynamic to static.

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

  1. Production postmortem: The case of the memory eater and high load - 8 hours from now
  2. Production postmortem: The case of the lying configuration file - about one day from now
  3. Production postmortem: The industry at large - 2 days from now
  4. The insidious cost of allocations - 3 days from now
  5. Find the bug: The concurrent memory buster - 4 days from now

And 4 more posts are pending...

There are posts all the way to Sep 10, 2015

RECENT SERIES

  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    14 Aug 2015 - The case of the man in the middle
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats