Help me clean up this crazy lambda with the out keyword

Posted by Sarah Vessels on Stack Overflow See other posts from Stack Overflow or by Sarah Vessels
Published on 2011-01-05T18:00:59Z Indexed on 2011/01/05 18:54 UTC
Read the original article Hit count: 267

My code looks ugly, and I know there's got to be a better way of doing what I'm doing:

private delegate string doStuff(
    PasswordEncrypter encrypter, RSAPublicKey publicKey,
    string privateKey, out string salt
);

private bool tryEncryptPassword(
    doStuff encryptPassword,
    out string errorMessage
)
{
    ...get some variables...
    string encryptedPassword = encryptPassword(encrypter, publicKey,
        privateKey, out salt);
    ...
}

This stuff so far doesn't bother me. It's how I'm calling tryEncryptPassword that looks so ugly, and has duplication because I call it from two methods:

public bool method1(out string errorMessage)
{
    string rawPassword = "foo";
    return tryEncryptPassword(
        (PasswordEncrypter encrypter, RSAPublicKey publicKey,
            string privateKey, out string salt) =>
            encrypter.EncryptPasswordAndDoStuff( // Overload 1
                rawPassword, publicKey, privateKey, out salt
            ),
        out errorMessage
    );
}

public bool method2(SecureString unencryptedPassword,
    out string errorMessage)
{
    return tryEncryptPassword(
       (PasswordEncrypter encrypter, RSAPublicKey publicKey,
           string privateKey, out string salt) =>
           encrypter.EncryptPasswordAndDoStuff( // Overload 2
               unencryptedPassword, publicKey, privateKey, out salt
           ),
       out errorMessage
   );
}

Two parts to the ugliness:

  • I have to explicitly list all the parameter types in the lambda expression because of the single out parameter.
  • The two overloads of EncryptPasswordAndDoStuff take all the same parameters except for the first parameter, which can either be a string or a SecureString. So method1 and method2 are pretty much identical, they just call different overloads of EncryptPasswordAndDoStuff.

Any suggestions?

Edit: if I apply Jeff's suggestions, I do the following call in method1:

return tryEncryptPassword(
    (encrypter, publicKey, privateKey) =>
    {
        var result = new EncryptionResult();
        string salt;
        result.EncryptedValue =
            encrypter.EncryptPasswordAndDoStuff(
                rawPassword, publicKey, privateKey, out salt
            );
        result.Salt = salt;
        return result;
    },
    out errorMessage
);

Much the same call is made in method2, just with a different first value to EncryptPasswordAndDoStuff. This is an improvement, but it still seems like a lot of duplicated code.

© Stack Overflow or respective owner

Related posts about c#

Related posts about lambda