Use Java 8’s lambda as a method parameter to avoid redundancy

I have a class with many methods like this (very simplified):

public Record[] getRecordForXXX(String username,String param1) throws MyException {
    User user = getUser(String username); // Always the same
    MyObject myObj = getMyObject(param1); // Always the same

    // Here is the only line of code,this is different in any of thoose methods
    Record[] recs = getRecords1(user,myObject); // or getRecords2(user,myObject) ...

    // Handle those records always the same ...
    handleRecords(recs); // Always the same
    return recs; // Always the same
}

Is there any way to use Lambdas to avoid redundancy, such as:

public Record[] getRecord(String userName,String param1,XXX method) throws MyException {
        User user = getUser(String username); // Always the same
        MyObject myObj = getMyObject(param1); // Always the same

        // => Call the given 'method' using the parameters user and myObj and returning records

        // Handle those records always the same ...
        handleRecords(recs); // Always the same
        return recs;  // Always the same
   }

I know I can use some kind of interface (command mode) to do this, but I like to use more functional methods... TIA!

Solution

Try this,

public Record[] getRecord(String userName,BiFunction<User,MyObject,Record[]> method) throws MyException {
    User user = getUser(String username); // Always the same
    MyObject myObj = getMyObject(param1); // Always the same

    Record[] recs = method.apply(user,myObj);

    // Handle those records always the same ...
    handleRecords(recs); // Always the same
    return recs;  // Always the same
}

You can call new functions as follows:

yourObject.getRecord(userName,param1,(aUserName,aParam1) -> {
    // do some stuff with aUserName and aParam1
    return aRecordArray;
})
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
分享
二维码
< <上一篇
下一篇>>