I often see (in many mocking libraries, for example) methods where instead of an argument of type System.Type , an argument of a universal type is used. I specifically talk about cases when the generic type is used only in the typeof(T) operation (i.e., no instance of type T is used anywhere in the method, and T is not used for the return type or for other arguments).
For example, consider the following method:
public string GetTypeName(System.Type type) { return type.FullName; }
this method is often accompanied by a general version:
public string GetTypeName<T>() { return GetTypeName(typeof(T)); }
Questions is bad practice or good practice?
Is it syntactic sugar or is there more?
I see this as a misuse of a language function to reduce the invocation of a method that takes an argument of type System.Type
Would you consider this smell? Should this be avoided? or it’s really good practice (provide a generic method as a shortcut to avoid typing typeof() ).
Here are some practical problems using this pattern that I can think of:
- If an argument of type non System.Type is added - the method may need to be rewritten (if the order of the arguments is semantically significant) for the non-general version (otherwise some arguments will be arguments of a general type, and some will be regular arguments).
- this requires two methods (common and not common for cases when the type is unknown at compile time). Consequently, it adds unit tests, which are basically pointless.
On the other hand, this is common practice (and most are always right, right?), But more importantly, ReSharper prefers this signature when I refactor the Extract Method on code that requires a single argument of the System.Type type known during compilation ( and I learned to take their recommendations, although not by faith, but seriously).
c # coding-style code-smell
THX-1138 Aug 15 '13 at 16:21 2013-08-15 16:21
source share