Design patterns: many methods share the same first step

Is there a design pattern that can help me avoid repetition DoThisStepFirst()in many methods?

class Program
{
    static void Main(string[] args)
    {
        Method1();
        Method2();
        MethodN();
    }

    private static void DoThisStepFirst()
    {
        // Implementation
    }

    private static void Method1()
    {
        DoThisStepFirst();
        // Implementation
    }

    private static void Method2()
    {
        DoThisStepFirst();
        // Implementation
    }

    // {...}

    private static void MethodN()
    {
        DoThisStepFirst();
        // Implementation
    }
}

EDIT 1: Suffice it to say that this is a contrived example.
My actual implementation includes method signatures with parameters and nontrivial operations in each method.

EDIT 2:

  • @Marc Gravell proposed aspect-oriented programming. Yes, it can help me here.
  • I also think that the Chain-of-Responsibility template can also help me here.

@ Charlie Martin wanted to know more about the program. So here is what I'm actually trying to do.

  • ASP.NET MVC 2 "m" "n" .
  • MVC SessionState. SessionState.
    • DoThisStepFirst() SessionState.
    • SessionState, ( , " " ).
+3
6

, Unit Test TestFixtureSetup, :

NUnit:

[TestFixtureSetUp]
public void Setup()
{

}

MSTest:

[TestInitialize()]
public void Startup()
{
    //Do setup here
}
+4

, , DoThisStepFirst(), :

    private static void DoSomething(Action doSomethingElse)
    {
        DoThisStepFirst();
        doSomethingElse();
    }
+3
private static void MethodCommon(Func f)
{
    DoThisStepFirst();
    f();
}

private static void Method1()
{
    MethodCommon(() => 
        doSomething();
    );
}
+3

, , . , "DoThisStepFirst" - ;

  DoThisStepFirst();
  Method1(); // and so on

.., , . , : " , ?"

, , , , , .

+1

How to leave code in DoThisStepFirst () in the constructor. If they all need him to start, to start there, there are good chances that he can get there. If it does not reset the states / behavior, which must be reset before your methods will do anything.

0
source

No, usually not. Maybe you could provide some details about what you are trying to accomplish?

0
source

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


All Articles