Assembly assembly = null;
if(assemblyCache.Contains(name))
assembly = assemblyCache[name];
if(assembly == null)
{
string fullPath = GetFullAssemblyPath(name);
if(File.Exists(fullPath))
assembly = LoadAssemblyFromFile(fullPath);
}
if(assembly == null)
{
assembly = CompileAssembly(name);
}
if(!assemblyCache.Contains(name))
assemblyCache.Add(name, assembly);
Refactorings
No refactoring yet !
Ants
December 8, 2010, December 08, 2010 21:18, permalink
Look for chain of responsibility pattern. http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
Wolfbyte
December 14, 2010, December 14, 2010 04:03, permalink
Lots of small methods and the coalescing operator allows you to concisely show this sort of logic when dealling with null values. Lazy evaluation means that as soon as a value is found the chain will stop. You can quickly change the orders of the cases or add new cases and each one can be tested independently.
Assembly GetFromCache(string name) {
if(!assemblyCache.Contains(name)) return null;
return assemblyCache[name];
}
Assembly GetFromFileSystem(string name) {
var fullPath = GetFullAssemblyPath(name);
if(!File.Exists(fullPath)) return null;
return LoadAssemblyFromFile(fullPath);
}
void Cache(string name, Assembly assembly)
{
if(assemblyCache.Contains(name)) return;
assemblyCache.Add(name, assembly);
}
//...
assembly = GetFromCache(name) ?? GetFromFileSystem(name) ?? CompileAssembly(name);
Cache(name, assembly)
return assembly;
Hello,
I've faced this several times, I'm not happy with code like the following. The point here is to try to get some data from a source. If it's not there, try another source. If it's not there, try another one and so on. The priority is important. The example I give here is simplified, so it might not look that bad, but I hope you get the point.
Is there any pattern for this?
Thanks in advance.