c# - How to refactor "using" statement to avoid code duplication? -
let's suppose have following methods:
public string getschedules(string request) { using (var soapclient = new servicereference1.customdatatimetabletoolkitservicessoapclient(endpointconfigurationame, endpoint)) { return soapclient.getschedules(authenticationinfo, request); } } public string getcountrylist(string request) { using (var soapclient = new servicereference1.customdatatimetabletoolkitservicessoapclient(endpointconfigurationame, endpoint)) { return soapclient.getcountrylist(authenticationinfo, request); } } public string getcarriers(string request) { using (var soapclient = new servicereference1.customdatatimetabletoolkitservicessoapclient(endpointconfigurationame, endpoint)) { return soapclient.getcarriers(authenticationinfo, request); } }
as can see different thing name of method invoked. how refactor these methods apply "using" statement once , avoid code duplication?
to me, have fine, if want factor out can use func
, lambdas. along these lines:
public string getschedules(string request) { return worker((c) => c.getschedules(authenticationinfo, request)); } public string getcountrylist(string request) { return worker((c) => c.getcountrylist(authenticationinfo, request)); } public string getcarriers(string request) { return worker((c) => c.getcarriers(authenticationinfo, request)); } private string worker(func<soapclientclassgoeshere, string> f) { using (var soapclient = new servicereference1.customdatatimetabletoolkitservicessoapclient(endpointconfigurationame, endpoint)) { return f(soapclient); } }
func<a, r>
means "a function takes argument of type a
, returns value of type r
" (and can have func<a, b, r>
function takes two arguments, etc.).
more func<>
, lambdas in this question , this question (and many more, it's rich topic).
here's live example on ideone.com (a silly live example, demonstrates concept):
using system; using system.collections.generic; class foo { public string getschedules(string request) { return worker((c) => c[request]); } public string getcountrylist(string request) { return worker((c) => c[request].toupper()); } public string getcarriers(string request) { return worker((c) => c[request].tolower()); } private string worker(func<dictionary<string,string>, string> f) { var d = new dictionary<string, string>(); d.add("1", "one"); d.add("2", "two"); d.add("3", "three"); return f(d); } } public class test { public static void main() { var f = new foo(); console.writeline(f.getschedules("1")); console.writeline(f.getcountrylist("1")); console.writeline(f.getcarriers("1")); } }
Comments
Post a Comment