A friend recently sent me a piece of code and asked me to help improve it. The file had more than 3,000 lines, and most of the logic was heavily duplicated.

I noticed a recurring pattern throughout the code:


testA() {
	// preparing for the test
	while(true){
		try{
			Thread.sleep(SLEEP_FOR);
		}catch(Exception ex){

		}

		Response response = request.getA();
		// lots of response parsing
		// lots of logs and assertions based on response
	}

}

To reduce lines of code and avoid repetition, I refactored the logic using a Higher-Order Function to encapsulate the repetitive while retry loop.

Here is my solution:

package com.pragmatists.blog.events.application;


import java.util.Random;
import java.util.function.Function;
import java.util.function.Supplier;


public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");
        testLikeAPro();

    }

    private static void testLikeAPro(){
        String searchName = "toro dep trai 10-11";
        Supplier<Response> lazySearchName = () -> {
            SearchApi searchAPI = new SearchApi();
            return searchAPI.searchConKet(searchName);
        };

        Response response = requestWithTry().apply(lazySearchName);
        System.out.println("status: "+ response.status + "; data:"+response.data);
    }

    private  static Function<Supplier<Response>, Response> requestWithTry(){
        return (request) ->{
            int count = 0;
            while(true){
                System.out.println("tried:  "+ ++count);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Response response =  request.get();
                if(response.status == 200){
                    return response;
                }
            }

        };
    }

    static class RequestAPI{
        Response get(String url){
            int[] statuses = new int[]{200, 400, 500};
            Random random = new Random();
            return new Response(statuses[random.nextInt(statuses.length)], "response of: " + url);
        }
    }

    static class SearchApi extends  RequestAPI {
        Response searchConKet(String name) {
            System.out.println("Search conket: "+ name);
            return get("?conket=where&name="+name);
        }
    }

    static class Response {
        int status;
        String data;

        public Response(int status, String data) {
            this.status = status;
            this.data = data;
        }
    }

}

References:

  1. https://medium.com/@knoldus/functional-java-lets-understand-the-higher-order-function-1a4d4e4f02af

  2. https://www.baeldung.com/java-8-functional-interfaces