8d59e92055a2fb33932467d81fad1f35

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.

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 !

F9a9ba6663645458aa8630157ed5e71e

Ants

December 8, 2010, December 08, 2010 21:18, permalink

2 ratings. Login to rate!

Look for chain of responsibility pattern. http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

861f311cc4a077c439099d0e5d251e73

Wolfbyte

December 14, 2010, December 14, 2010 04:03, permalink

2 ratings. Login to rate!

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;

Your refactoring





Format Copy from initial code

or Cancel