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
outparameter. - The two overloads of
EncryptPasswordAndDoStufftake all the same parameters except for the first parameter, which can either be astringor aSecureString. Somethod1andmethod2are pretty much identical, they just call different overloads ofEncryptPasswordAndDoStuff.
Any suggestions?
Edit (solution): I ended up using Jeff’s suggestion and altering the overloads of EncryptPasswordAndDoStuff to return an instance of EncryptionResult. Then I didn’t need an explicitly defined delegate, and I used the following code:
private bool tryEncryptPassword(KeysAndEncrypter keys,
Func<EncryptionResult> encryptPassword,
out string errorMessage
) { ... }
private class KeysAndEncrypter
{
public RSAPublicKey PublicKey { get; set; }
public string PrivateKey { get; set; }
public PasswordEncrypter Encrypter { get; set; }
}
And here was the contents of method1, with method2 being very similar:
string rawPassword = "foo";
KeysAndEncrypter keys = getEncryptionKeys();
return tryEncryptPassword(keys, () =>
keys.Encrypter.EncryptPasswordAndDoStuff(
rawPassword, keys.PublicKey, keys.PrivateKey
),
out errorMessage
);
You could introduce a new type to represent the delegate’s return value:
… and change the delegate to something like this: