atoms atoms - 1 year ago 43
C# Question

Where to place a method that shares logic of two classes

I have two classes,

BuildingHandler
and
TestHandler
.

BuildingHandler
contains a method to
LoadBuildings
and
TestHandler
contains one to
LoadTests()


Now I would like to create a function called
LoadBuildingTests
.

I'm unsure what handler to place this in as the functionality relates to both Buildings and Tests.

I'm leaning towards having
LoadBuildingTests
in the
BuildingHandler
, then once IDs have been retrieved calling
TestHandler.LoadTests();


Does this seem reasonable, or am I approaching it the wrong way? Should I be looking into interfaces, or another approach?

Answer Source

I'd leave LoadBuildingTests inside BuildingHandler and pass in the TestHandler as an argument:

public class BuildingHandler
{
    public static void LoadBuildingTests(TestHandler testHandler)
    {
        if (testHandler == null) throw ....

        var building = LoadBuilding();
        var tests = testHandler.LoadTests(building.Id);
        //....
    }

    //..
}

Equally valid would be to implement the method in TestHandler and pass in the BuildingHandler as the argument but I have insufficient context to decide which is better. At first glance, I like the first option more.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download