“This is the 18th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”

How did you think about the problem above? Have you left your thoughts or code in the comments section?

Here’s how I think about it: If we want to extract the common parts and find that they are scattered, we should not extract them, but it is not my style to not extract the code and have a lot of duplicate code. So I went for the Consumer interface.

Pseudocode after the change

B b = this.baseMapper.selectOne(queryWrapper);
if(b ! =null) {
	String status = b.getStatus();
	if (Objects.equals(Constants.STATUS_ING, status)){
		return "In process";
	} else if (Objects.equals(Constants.STATUS_SUCCESS, status)){
		return "Processed successfully";
	}
	// Failed operation
	getResponse(dto, response, s -> mapper.updateById(s));
} else {
	getResponse(dto, response, s -> mapper.updateById(s));
}

public void getResponse(DTO dto, Response response, Consumer<B> consumer){
	// Request a third-party interface and parse the response.if (ReturnInfoEnum.SUCCESS.getCode().equals(parse.getCode())) {
        ......
		bb.setStatus(Constants.STATUS_ING);
	
		consumer.accept(bb);

		// Update the status of table Aa.setStatus(Constants.STATUS_ING); aMapper.updateById(a); }}Copy the code

So if you’ve already seen this, congratulations, you’ve got everything you need to know about Consumer. If you’re still in a bit of doubt, read on to introduce four common functional interfaces.

Functional interface

So what is a functional interface? A functional interface is an interface that has only one abstract method (except Object methods), but can have multiple non-abstract methods. It expresses a logical single function.

@FunctionalInterface

The @functionalInterface annotation is used to indicate that the interface is functional. It facilitates early detection of inappropriate method declarations that occur in functional interfaces or that the interface inherits.

If the interface is annotated with this annotation but is not actually a functional interface, an error will be reported at compile time.

Supplier

We generally call it a “producer”, which has no parameters but can return the result. It is the provider of the result.

@FunctionalInterface
public interface Supplier<T> {

    /** * get a result */
    T get(a);
}
Copy the code

Here’s a simple example:

Optional<Double> optional = Optional.empty();
optional.orElseGet(()->Math.random() );

//orElseGet method source, inside the use of get method
public T orElseGet(Supplier<? extends T> other) {   
    returnvalue ! =null ? value : other.get();
}
Copy the code

After seeing my solution, are there any friends who have realized the same as me? Let’s take a look at functional interfaces in the comments section. If you have different opinions or better idea, welcome to contact AH Q, add AH Q can join the technical exchange group to participate in the discussion!