Code encapsulation simplifies maintenance. The more abstracted and isolated a routine is from a larger code base, the easier it will be to adjust, test, and if needed, replace later.
This came to mind recently when I wrote a short routine that determines if a mapped drive is a local drive:
[DllImport("mpr.dll")]
static extern uint WNetGetConnection(string lpLocalName, StringBuilder lpRemoteName, ref int lpnLength);
// returns whether the current drive is local
internal static bool IsLocalDrive(String driveName)
{
bool isLocal = true; // assume local until disproved
// strip trailing backslashes from driveName
driveName = driveName.Substring(0, 2);
int length = 256; // to be on safe side
StringBuilder networkShare = new StringBuilder(length);
uint status = WNetGetConnection(driveName, networkShare, ref length);
// does a network share exist for this drive?
if (networkShare.Length != 0)
{
// now networkShare contains a UNC path in format \\MachineName\ShareName
// retrieve the MachineName portion
String shareName = networkShare.ToString();
string[] splitShares = shareName.Split('\\');
// the 3rd array element now contains the machine name
if (Environment.MachineName == splitShares[2])
isLocal = true;
else
isLocal = false;
}
return isLocal;
}
There is a post on stackoverflow asking how to do this, and, like many others, it has several answers showing several ways to do this. So, is my method correct? This code seems to work, but I’ve been programming long enough to know that code that “seems to work” doesn’t necessarily work in every circumstance and could have other negatives, such as performance issues.
So, knowing that this code I may have to tweak or replace at some future point in time, I will try to encapsulate it as much as possible to make it easier to work with in an isolated manner later. By keeping the code in a separate method, I can easily use a unit test to try it in various test scenarios without affecting any other code.
Of course, this is a very simple scenario, which made it perfect for this post. It can be much tougher to abstract and isolate more complex code, but that doesn’t mean we shouldn’t strive to do so whenever possible.