Wednesday, June 30, 2010

Proper Use of Properties

Today we are talking about properties.  How to use them and more importantly how not to use them.

When dealing with properties like they wore written before 3.5 you should have some thing that looks like this.

private string _test;
public string Test
{
    get { return this._test; }
    set { this._test = value; }
}



I love properties like this it’s only slightly less cool then using the 3.5 version of a property. The thing I don’t like about a property like this is when a programmer decides he doesn’t need to user the property and accesses the _test variable directly inside of the class to make a change.  So like this




this._test = "some string";



I consider this bad programming.  It makes maintaining code much more difficult and adds an unnecessary level of complexity. You have to look at two things now to see how a value gets set or modified.  To do all the access through the property takes about the same amount of work and ends up in a much cleaner code file.




this.Test = "Some string";



Is actually one less key stroke and is so much easier to work with.

Tuesday, June 29, 2010

This code just rocks.

Usually I post examples of code that sucks.  Today I am posting an example of code that just rocks.  Why does it rock because it solves a problem in a very elegant way.  I have had to write code to do the same thing several times but mine never looks or works as this example. The code comes from ravenDB’s server. It handles the case where you need to run in elevated privileges but the program wasn’t started at such a state.


private static void AdminRequired(Action actionThatMayRequiresAdminPrivileges, string cmdLine)
{
    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false)
    {
        if (RunAgainAsAdmin(cmdLine))
            return;
    }
    actionThatMayRequiresAdminPrivileges();
}

private static bool RunAgainAsAdmin(string cmdLine)
{
    try
    {
        var process = Process.Start(new ProcessStartInfo
        {
            Arguments = cmdLine,
            FileName = Assembly.GetExecutingAssembly().Location,
            Verb = "runas",
        });
        if (process != null)
            process.WaitForExit();
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}