Java – can this loop code be simplified in some way?

I have a problem... Basically my code is ugly and I don't like it I wonder if there is a way to simplify it (I use Java 8)

I have these "code blocks" that follow this pattern. I have about 5 or 6 in a method, so this method looks very repetitive and ugly

Loops are the same, but the code changes inside

Is there any way to simplify this?

Code block example

String id = null;
            for (int i=0; i< NUM_CHECKS; i++) {

                // BEGIN VARIABLE CODE
                id = getPrice();
                if (id != null) break;
                // END VARIABLE CODE 

                // sleep between checks
                if (i < NUM_CHECKS -1) Thread.sleep(DELAY);
            }

example

String id = null;
            for (int i=0; i< NUM_CHECKS; i++) {

                // BEGIN VARIABLE CODE
                id = getPrice();
                if (id != null) break;
                // END VARIABLE CODE 

                // sleep between checks
                if (i < NUM_CHECKS -1) Thread.sleep(DELAY);
            }

            for (int i=0; i< NUM_CHECKS; i++) {

                // BEGIN VARIABLE CODE
                x=x*2;
                if (x>25) break;
                // END VARIABLE CODE 

                // sleep between checks
                if (i < NUM_CHECKS -1) Thread.sleep(DELAY);
            } etc... a couple more blocks

Solution

How about coding abstractions to include all template files?

class MyLoop
{
    private int numChecks;

    private int delay;

    public MyLoop(int numChecks,int delay) {...}

    public void loopAndSleep(MyTask task)
    throws InterruptedException
    {
        // Update: It is important to set properly the order of the looping conditions,// to stop invoking hasEnded() as soon as i<numChecks==false (Thaks to Simon Eismann).
        for (int i=0; i<numChecks && !task.hasEnded(); i++)
        {
            if (i < numChecks -1)
            {
                Thread.sleep(DELAY);
            }
        }
    }
}

interface MyTask
{
    public boolean hasEnded();
}

Therefore, you can replace each of the 5-6 locations in the program by:

new MyLoop(NUM_CHECKS,DELAY).loopAndSleep(new MyTask(){...});

By properly extending mytask, you can provide them with specific state variables

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>