views:

104

answers:

3

I recently began to start using functions to make casting easier on my fingers for one instance I had something like this

((Dictionary<string,string>)value).Add(foo);

and converted it to a tiny little helper function so I can do this

ToDictionary(value).Add(foo);

Is this a code smell?

Also, what about simpler examples? For example in my scripting engine I've considered making things like this

((StringVariable)arg).Value="foo";

be

ToStringVar(arg).Value="foo";

I really just dislike how inorder to cast a value and instantly get a property from it you must enclose it in double parentheses. I have a feeling the last one is much worse than the first one though

(also I've marked this language agnostic even though my example is C#)

+1  A: 

I don't think so. You've also done something nice in that it's a bit easier to read and see what's going on. Glib (in C) provides casting macros for their classes, so this isn't a new concept. Just don't go overkill trying to save your fingers.

SB
A: 

In general, I would consider this to be code smell. In most situations where the type of casting you describe is necessary, you could get the same behavior by proper use of interfaces (Java) or virtual inheritance (C++) in addition to generics/templates. It is much safer to leave that responsibility of managing types to the compiler than attempting to manage it yourself.

Without additional context, it is hard to say about the example you have included. There are certainly situations in which the type of casting you describe is unavoidable; but they're the exception rather than the rule. For example, the type of casting (and the associated helper functions/macros) you're describing extremely common-place in generic C libraries.

Mike Koval
+4  A: 

Ignoring for a moment that you may actually need to do this casting - which I personally doubt - if you really just want to "save your fingers", you can use a using statement to shorten the name of your generic types.

At the top of your file, with all the other usings:

using ShorterType = Dictionary<string, Dictionary<int, List<Dictionary<OtherType, ThisIsRidiculous>>>>;
Tesserex
I really have had 3 level deep nested generics before. And that is amazing had no idea `using` could be used for that!
Earlz
This is a solid solution, though not language agnostic as the OP was hoping for.
SB
If you want language agnostic, you might investigate using nominal typing here. That's where you make a new class that exactly reuses the implementation of the base class, but differs only in semantics. And if I'm passing such a complex map everywhere, it's probably an integral part of my data model. Who's to blame if I don't give it a name? I'll give you a hint: It's not the guy who came up with the generic methods in the first place.
Jason