Pipe to pipe, policy to policy (IF-ELSERemoval plan)

sequence

In 0202, the if-else module of the code Empire grew larger and larger, which seriously affected the operation of the empire and overwhelmed the system. Therefore, the Empire launched the if-else elimination plan. Suddenly, a storm of blood swept the whole empire. An organization called the Magic Conch came up with its own insights, and with the emergence of this organization, the wheels of history began to roll up, the years opened a new chapter

The real order

But as a Crud-boy, I think the strategy mode is actually limited in adapting to the situation, mainly for the following reasons

  1. The strategy mode is heavy on the following points
  • Each if-else requires a separate processing strategy that implements a separate class (even the inner class is expensive)

  • Method clusters (all policy methods) require the logic handled by the hook method hooks themselves, mainly in these ways

    • Map<String,Handler>Exposed hook
    • annotationsPortable exposed hook
    • Based on theSpringBeanNameIntrusive exposed hook
    • . other
  • Nested callbacks between policy methods can be disastrous when it comes to policy layering

  1. The policy mode has high maintenance costs in the scenario of severe service fluctuation
  • Strategies.Fixed input and output, adding a parameter requires modifying all method clusters
  • Discarded policies and new policiesMixed together, dare not modify and delete casually
  • A lot ofDuplicate codeAlthough the policy is layered, the actual business will have a lot of duplicate code, which is not enoughcohesion, don’t draw IDEATake a yellow
  1. As aCRUD-BOYI am theDissStrategic mode (ok, this is the bastardManual funny)
  • CRUDThe scene strategy mode was not written and felt unnecessary
  • If I take the policy pattern code, before I understand the hook, method cluster distributionI dare not moveAlthough it would be nice to change the back
  • The person who is being chased by the BUG is not worthy to write strategy. Sorry, I am not worthy of 5555

Makes the

Pipe mode is a great way to clean up if-else in simple scenarios. When you’re studying pipes, you might feel like a chain of responsibility, but I think there’s a difference, so let’s sort it out for you

  • In pipe mode, each section has inputs and outputs, whereas the classical chain of responsibility of a Filter primarily handles data flows in context
  • The sequence of pipes is reflected after the splicing of each pipe section, and cannot be modified after the splicing of pipes
  • Complex piping patterns have valves, or valves, that control not to flow down

Preliminary study — Minimalist pipe

Pipeline, Context, Status, Valve, etc. (“▔□▔ “) I don’t need to be a Crud-boy, so hang on, let’s do some simple plumbing to make it easier to use

Union logic

public interface Step<IN.OUT> {

    /** * handle logic **@paramInput Pipe input *@returnOUT Output */
    OUT process(IN input);
}
Copy the code

Pipeline logic

public class Pipeline<IN.OUT> {
    /** ** */
    private Step<IN, OUT> current;

    /** * This constructor is used only to initialize the first header section **@paramCurrent Current management segment */
    public Pipeline(Step<IN, OUT> current) {
        this.current = current;
    }


    /** * Concatenate the pipe section and return the new pipe * note that the complete pipe is returned * i.e. the input of the topmost pipe section and the output of the bottom pipe section *@paramNext Next section *@param<NEXT> Output of the NEXT section *@returnThe pipe that joins the next section */
    public <NEXT> Pipeline<IN, NEXT> pipe(Step<OUT, NEXT> next) {
        return new Pipeline<>(input -> next.process(current.process(input)));
    }
    
    /** * true execution *@paramThe input input *@returnO * /
    public OUT execute(IN input) {
        return this.current.process(input); }}Copy the code

Take a chestnut

// Head section
Pipeline<Integer, String> start = new Pipeline<>(input -> String.valueOf(input));
// Continue to add pipe section
Pipeline<Integer, String> pipeline = start
                .pipe(input -> Integer.parseInt(input) + 1)
                .pipe(input -> Collections.singletonList(String.valueOf(input + 1)))
                .pipe(input -> input.get(0));
// True execution
String execute = pipeline.execute(1);
Copy the code

advantages

Does this pipe implementation make everyone’s eyes shine? Yes, this is the way the very simple, no implementation class, no context, no switch, no state, only simple processing logic, everything is so simple, for me, is me to write the CRUD, IF – ELSE less, then there are no complicated strategy class needs to manage, usually write about CRUD is very happy, No more complicated code

Exploring again — functional programming

If the above code is opened in IDEA, you will be prompted to change to Lambda format, oh?? Then when you open the ** function

** interface under the Java8 function package, that’s the magic moment, bing~~~~
,>

 R apply(T t);
Copy the code

This is like a pipe section, and then you’ll find the following code

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
Copy the code

(“▔□▔), this is the way to take over the festival, I am indeed a Crud-boy, they have already achieved, you are still building the wheel, the key to create no others show, is really a sadness for no reason, then, let’s try how to use it

Take a sad chestnut

// Head section
Function<Integer, String> start = input -> String.valueOf(input);
// Continue to add pipe section
Function<Integer, String> pipeline = start
                .andThen(input -> Integer.parseInt(input) + 1)
                .andThen(input -> Collections.singletonList(String.valueOf(input + 1)))
                .andThen(input -> input.get(0));
// True execution
String execute = pipeline.apply(1);
Copy the code

PPT type summary

How, see this code is not heart pounding, I wish to open IDEA immediately lapped a wave of code, feel the dripping dripping pipe mode, also is lapped – pipe mode, brother, not dirty, to be pure, pure programmers can write touch the heart of the code… Don’t say, please write happily

Programmer summary

IF you’re not misinformed, we’re talking about if-else cleanup, but we haven’t talked about how to clean if-else up until now, so this is kind of a prequel to cleanup, and I’ll do it in the next article, Welcome to visit us next time. Thank you for your visit. Wish you a happy Dragon Boat Festival and a happy family!