Archive for the ‘Consulting’ Category

Breaking encapsulation with C# 2.0 partial classes

Wednesday, May 3rd, 2006

For good or bad partial classes in C# 2.0 allows breaking of encapsulation as this example will show.

In a consulting job I recently ran into an interesting case involving a webservice with several different service methods f1, f2, fn (sample names, not actual names) all taking the same string argument and all returning a string. The user would select an operation name after which my code had to call the named operation on a web service using a standard parameter. Trivial really, if one would do accept bad code like this below, but I don’t:

String operationName = …
String arg = …
Webserviceproxy webserviceproxy = …
// Warning: Badly coupled code begins here (need to update each time we add/rename/delete operations).
switch (operationName) {
case “f1″: return webserviceproxy.f1(arg); break;
case “f2″: return webserviceproxy.f2(arg); break;
}

What is really needed is a method to invoke a webservice method by name, while still using the generated .NET proxy to do the hard soap/http stuff (no time to reinvent a better wheel here).

Let’s look at an extract of the generated proxy:

(more…)


Bad Behavior has blocked 131 access attempts in the last 7 days.