I’m having a little trouble deciding the best way to refactor a method which contains LINQ queries which are very similar but not identical.
Consider a method which is something along these lines:
public SomeObject GetTheObject(IMyObject genericObject) {
Type t = genericObject.GetType();
SomeObject so = null;
switch(t.Name) {
case "Type1":
var object1 = (from o in object1s where o.object1id == genericObject.id).FirstOrDefault();
so = (SomeObject)object1;
break;
case "Type2":
var object2 = (from o in object2s where o.object2id == genericObject.id).FirstOrDefault();
so = (SomeObject)object2;
break;
default:
break;
}
return so;
}
This is just an illustration, but imagine I’m needing to execute a different query (different in that it uses a different ObjectSet, uses slightly different fields (object1id vs object2id) and returns a different type.
Other than that, the queries are the same.
Is there a sensible way to refactor this kind of method? It feels like I’ve missed something obvious. Perhaps I have to use the exact method and I can’t avoid re-writing the query, it just seems like I SHOULD be able to somehow!
Any pointers greatly appreciated
Maybe you have just oversimplified your scenario, but the smelly part of your function is the cast to SomeObject. Couldn’t you just work with interfaces and (if needed) cast the result at the call site? You could have your Type1 and Type2 implement a common interface where id1 and id2 are exposed as id, for example (or decorate them if you don’t control Type1 and Type2)
I.e.
For instance, if you have:
you can do:
And cast the objects after you call the function, if you have to.
EDIT:
if you’re stuck with concrete objects and casts, the best refactoring I could come up with is: