ChallengeStrongly typing weakly typed code
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:
- (01 Jul 2024) Efficient snapshotable state
- (13 Oct 2023) Fastest node selection metastable error state–answer
- (12 Oct 2023) Fastest node selection metastable error state
- (19 Sep 2023) Spot the bug
- (04 Jan 2023) what does this code print?
- (14 Dec 2022) What does this code print?
- (01 Jul 2022) Find the stack smash bug… – answer
- (30 Jun 2022) Find the stack smash bug…
- (03 Jun 2022) Spot the data corruption
- (06 May 2022) Spot the optimization–solution
- (05 May 2022) Spot the optimization
- (06 Apr 2022) Why is this code broken?
- (16 Dec 2021) Find the slow down–answer
- (15 Dec 2021) Find the slow down
- (03 Nov 2021) The code review bug that gives me nightmares–The fix
- (02 Nov 2021) The code review bug that gives me nightmares–the issue
- (01 Nov 2021) The code review bug that gives me nightmares
- (16 Jun 2021) Detecting livelihood in a distributed cluster
- (21 Apr 2020) Generate matching shard id–answer
- (20 Apr 2020) Generate matching shard id
- (02 Jan 2020) Spot the bug in the stream
- (28 Sep 2018) The loop that leaks–Answer
- (27 Sep 2018) The loop that leaks
- (03 Apr 2018) The invisible concurrency bug–Answer
- (02 Apr 2018) The invisible concurrency bug
- (31 Jan 2018) Find the bug in the fix–answer
- (30 Jan 2018) Find the bug in the fix
- (19 Jan 2017) What does this code do?
- (26 Jul 2016) The race condition in the TCP stack, answer
- (25 Jul 2016) The race condition in the TCP stack
- (28 Apr 2015) What is the meaning of this change?
- (26 Sep 2013) Spot the bug
- (27 May 2013) The problem of locking down tasks…
- (17 Oct 2011) Minimum number of round trips
- (23 Aug 2011) Recent Comments with Future Posts
- (02 Aug 2011) Modifying execution approaches
- (29 Apr 2011) Stop the leaks
- (23 Dec 2010) This code should never hit production
- (17 Dec 2010) Your own ThreadLocal
- (03 Dec 2010) Querying relative information with RavenDB
- (29 Jun 2010) Find the bug
- (23 Jun 2010) Dynamically dynamic
- (28 Apr 2010) What killed the application?
- (19 Mar 2010) What does this code do?
- (04 Mar 2010) Robust enumeration over external code
- (16 Feb 2010) Premature optimization, and all of that…
- (12 Feb 2010) Efficient querying
- (10 Feb 2010) Find the resource leak
- (21 Oct 2009) Can you spot the bug?
- (18 Oct 2009) Why is this wrong?
- (17 Oct 2009) Write the check in comment
- (15 Sep 2009) NH Prof Exporting Reports
- (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
- (01 Sep 2009) Why isn’t select broken?
- (06 Aug 2009) Find the bug fixes
- (26 May 2009) Find the bug
- (14 May 2009) multi threaded test failure
- (11 May 2009) The regex that doesn’t match
- (24 Mar 2009) probability based selection
- (13 Mar 2009) C# Rewriting
- (18 Feb 2009) write a self extracting program
- (04 Sep 2008) Don't stop with the first DSL abstraction
- (02 Aug 2008) What is the problem?
- (28 Jul 2008) What does this code do?
- (26 Jul 2008) Find the bug fix
- (05 Jul 2008) Find the deadlock
- (03 Jul 2008) Find the bug
- (02 Jul 2008) What is wrong with this code
- (05 Jun 2008) why did the tests fail?
- (27 May 2008) Striving for better syntax
- (13 Apr 2008) calling generics without the generic type
- (12 Apr 2008) The directory tree
- (24 Mar 2008) Find the version
- (21 Jan 2008) Strongly typing weakly typed code
- (28 Jun 2007) Windsor Null Object Dependency Facility
Comments
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
Yes, IEntityInformationExtractor <T> is only strongly typed, and I am using that as a way to separate functionalities.
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.
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
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.
Maybe refactor it to have something like:
IEntityInformationExtractorFactory extractorFactory = IoC.Resolve<IEntityInformationExtractorFactory>();
IEntityInformationExtractor extractor = extractorFactory.Resolve(entityType);
return extractor.GetDescription(securityKey);
It probably isn't strongly typed as u would like it, but it will work.
I want to keep the IEntityInformationExtractor<T> 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
I always wished we could have a "generic scope operator" that transforms a Type argument into a generic scope:
generic<T>(with entityType)
{
return IoC.Resolve<IEntityInformation<T>>().GetDescription().
}
The direct solution would be to make Permission generic, if possible..
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.
Max,
Permission is an entity. I try really hard never to make my entities generic.
Ted,
Constraints are enforced even when you are using generics.
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/Type_system#Static_typing
http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
http://en.wikipedia.org/wiki/Type_system#Strong_and_weak_typing
Mike, you seem to have missed the part where I have Type entityType and I need to get from there to TEntityType.
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.)
'Strongly typed' and 'weakly typed' aren't terribly well established though. Everyone uses them to mean different things. From the first Wikipedia link:
<quote>
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.
</quote>
and
<quote>
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.
</quote>
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.
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).
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