Code Brain "Teaser" - but not quite

I'm just curious to see what you guys think about it. I heard that a bunch of answers went around the office, and I want to see if yours is possibly the best.

Question:

You have two functions described below:

function one()
{
    A();
    B();
    C();
}

function two()
{
    A();
    D();
    C();
}

How would you rewrite this (something counts, you can create classes, variables, other methods, whatever) to reduce code duplication?

Each of the methods called changes to variables that other functions should use. Methods A () B () and C () are already defined.

+3
source share
9 answers

Not all languages ​​support this approach, and the syntax for passing a function may vary between those that do, but the concept will be:

function one()
{
    refactored(B);
}

function two()
{
    refactored(D);
}

function refactored(middleMan)
{
    A();
    middleMan();
    C();
}
+6
source

. .

+6

, , .

.

+2

; , , , , . , , , , .

+1

one() two() , , . .

A() C() ... - X() any() { (); (); (); }

  • One, X() B()
  • 2, X() D()
+1

.

function (triggerA, triggerB, triggerC, triggerD)
{
     A(triggerA);
     B(triggerB);
     C(triggerC);
     D(triggerD);
}

, , , , / .

0

, ..,

function one()
{
    three(B)
}

function two()
{
    three(D);
}

function three(middle) 
{
    A();
    middle();
    C();
}
0

(, , ) , A() - , C() - , one() two() - , B() D() .

, , , , OOP , , .

0

In C ++, this is usually done using RAII, if the context makes sense ... this pattern is usually A () = some init function, C () = some de-init function. Usually a context is also used that is also initialized or destroyed.

   class bar
    {
        bar() {
            A();
        }

        ~bar() {
            C();
        }
    };

    void one() 
    {
        bar barvar;
        B();
    }

    void two()
    {
        bar barvar;
        D();
    }
-1
source

Source: https://habr.com/ru/post/1796381/


All Articles