Architecture of some reusable code

I am writing several small simple applications that have a common structure and should do the same things the same way (for example, logging, setting up a database connection, setting up an environment), and I'm looking for some tips on structuring reusable components. The code is written in a strictly and statically typed language (for example, Java or C #, I had to solve this problem in both cases). At the moment I have this:

abstract class EmptyApp //this is the reusable bit
{
   //various useful fields: loggers, db connections

   abstract function body()
   function run()
   {
        //do setup
        this.body()
        //do cleanup
   }
}

class theApp extends EmptyApp //this is a given app
{
   function body()
   {
        //do stuff using some fields from EmptyApp
   }

   function main()
   {
        theApp app = new theApp()
        app.run()
   }
 }

Is there a better way? Perhaps as follows? I have problems weighing compromises ...

abstract class EmptyApp
{
     //various fields
}

class ReusableBits
{
    static function doSetup(EmptyApp theApp)

    static function doCleanup(EmptyApp theApp)
}

class theApp extends EmptyApp
{
    function main()
    {
         ReusableBits.doSetup(this);
         //do stuff using some fields from EmptyApp
         ReusableBits.doCleanup(this);
    }
}

One obvious trade-off is that with option 2, the framework cannot wrap the application in a try-catch block ...

+2
3

( ), ( ).

, , .

, ReusableBits, 1 , .

, , , . , - , , .

, , , .

+4

? , - . , setup() .., . ( ) cleanup() .

, , ( Java)

public interface ClientCode {

    void runClientStuff(); // for the sake of argument
}

runClientStuff(), .

, , , . (, ), , .

, , (, / ), : -)

0

, , , . , . , , , , , / .

#.

abstract class BaseClass
{
    string field1 = "Hello World";
    string field2 = "Goodbye World";

    public void Start()
    {
        Console.WriteLine("Starting.");
        Setup();
        CustomWork();
        Cleanup();
    }

    public virtual void Setup()
    {Console.WriteLine("Doing Base Setup.");}

    public virtual void Cleanup()
    {Console.WriteLine("Doing Base Cleanup.");}

    public abstract void CustomWork();
}

class MyClass : BaseClass
{
    public override void CustomWork()
    {Console.WriteLine("Doing Custome work.");}

    public override void Cleanup()
    {
        Console.WriteLine("Doing Custom Cleanup");
        //You can skip the next line if you want to replace the
        //cleanup code rather than extending it
        base.Cleanup();
    }

}

void Main()
{
    MyClass worker = new MyClass();
    worker.Start();
}
0

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


All Articles