Edit: Warning - I now realize that the following technique is generally regarded as a bad idea because it creates hidden dependencies for the sake of looking neat.
I recently discovered that you can use the StackTrace to infer information about the caller of a method.
This enables you to create a seemingly "cool" API whereby you simply invoke a method without bothering to pass any explicit parameters to it, and the method works out what to do based on the StackTrace.
Is this a bad thing to do, and if so, why?
Example:
public class Cache {
public Object CheckCache()
{
Object valueToReturn = null;
string key = GenerateCacheKeyFromMethodPrototype(new StackTrace().GetFrame(1).GetMethod()); //frame 1 contains caller
if(key is in cache) valueToReturn = itemFromCache;
return valueToReturn;
}
}
public class Foo {
private static Cache cache = new Cache();
public Blah MethodFoo(param1, param2...)
{
Blah valueToReturn = cache.CheckCache(); //seems cool!
if(valueToReturn == null)
{
valueToReturn = result of some calculation;
//populate cache
}
return valueToReturn;
}
}
I'm sure there are errors in the above pseudocode, but you get my drift.
Edit: thanks for everyone's responses.