I have to create a bunch of methods that look like this. The things that change will be the method name, the return type and the lines marked in the middle – the rest will be the same. Is there a clean way to refactor this so that I don’t repeat myself?
private bool CanPerform(WindowsIdentity identity, string applicationName, int operation)
{
IAzApplication3 application = null;
IAzClientContext3 context = null;
try
{
application = this.store.OpenApplication(applicationName, null) as IAzApplication3;
ulong token = (ulong)identity.Token.ToInt64();
context = application.InitializeClientContextFromToken(token, null) as IAzClientContext3;
// lines that change go here
}
catch (COMException e)
{
throw new SecurityException(string.Format("Unable to check operation '{0}'", operation), e);
}
finally
{
Marshal.FinalReleaseComObject(context);
Marshal.FinalReleaseComObject(application);
}
}
I realise this is probably basic stuff but I work alone so there’s no one else to ask.
It sounds like a delegate would be appropriate here, with a generic method to cover the return type changing:
Then you put the code for each check in a separate method, or even just use a lambda expression:
or
You may want to change the delegate type of course – it’s not clear what
operationis meant to be used for, for example.I would also strongly consider casting instead of using
as. If the application or context is returned fromOpenApplication/InitializeClientContextFromTokenas a non-null value which just isn’t the right type, do you really want to handle that the same was as a null value being returned?