开发者

Whats the cleanest way to code logic for search, create if not found, search again

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);


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜