tags:

views:

21

answers:

1

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);
+3  A: 

So if I were to summarize your code as

SEARCH

IF (FOUND) THEN
    RETRIEVE
ELSE
    CREATE
    RETRIEVE

could you not do it like

SEARCH

IF (NOT FOUND) THEN
    CREATE

RETRIEVE
CyberDude
Doh! I'm confused :) I'll come back to this later...
Gabriel
LOL, what I'm saying is you should test for the negative scenario first. This way you can create the entity to make sure that when the execution reaches the retrieval step you can be sure you find what you search.
CyberDude
Yes, I'm seeing your point now. Thanks!
Gabriel
Great! Good luck!
CyberDude