I have been writing code like the following enough a lot lately.
I don't like the duplicate code in the else block.
Is there some obvious thing I'm missing? I pondered 'goto' but abandoned it when I saw an infinite loop possibility.
I know the obvious thing to do is create a separate function. The reason I hesitate is because, like I said, I've been running into this scenario a lot, so that's quite a few functions. It seems like too much complexity for what I get in exchange (i.e. no duplication of code).
Logger.Log("Finding parent.",
System.Diagnostics.TraceEventType.Start);
query = string.Format(
"Select Id, a " +
"From Parent__c " +
"Where a ='{1}' limit 1", childId);
queryResult = DoSOQLQuery(queryResult, query);
string parentId;
if (queryResult != null && queryResult.size > 0)
{
parentId = ((Parent__c)queryResult.records[0]).Id;
Logger.Log(string.Format("Parent__c.Id={0}",
parentId),
System.Diagnostics.TraceEventType.Verbose);
}
else
{
Logger.Log("Parent not found.",
System.Diagnostics.TraceEventType.Error);
Logger.Log("Creating parent.",
System.Diagnostics.TraceEventType.Start);
string apexToExecute = string.Format(
"Utility.CreateParent('{0}');",
childId);
this.webServices.execute(apexToExecute);
queryResult = DoSOQLQuery(queryResult, query);
if (queryResult != null && queryResult.size > 0)
{
parentId = ((Parent__c)queryResult.records[0]).Id;
Logger.Log(string.Format("Parent__c.Id={0}",
parentId),
System.Diagnostics.TraceEventType.Verbose);
}
}
Logger.Log("Done finding parent",
System.Diagnostics.TraceEventType.Stop);