user1061894
user1061894

Reputation: 109

Grouping methods logically

Basically I have a class with a private method and lots of public methods that call this private method. I want to group these public methods logically (preferably to separate files) so it'll be organized, easier to use and maintain.

public class MainClass
{
    private void Process(string message)
    {
        // ...
    }

    public void MethodA1(string text)
    {
        string msg = "aaa" + text;
        Process(msg);
    }
    public void MethodA2(int no)
    {
        string msg = "aaaaa" + no;
        Process(msg);
    }

    public void MethodB(string text)
    {
        string msg = "bb" + text;
        Process(msg);
    }

    // lots of similar methods here
}

Right now I'm calling them like this:

MainClass myMainClass = new MainClass();
myMainClass.MethodA1("x");
myMainClass.MethodA2(5);
myMainClass.MethodB("y");

I want to be able to call them like this:

myMainClass.A.Method1("x");
myMainClass.A.Method2(5);
myMainClass.B.Method("y");

How can I achieve it? There is probably an easy way that I'm not aware of.

Upvotes: 0

Views: 1226

Answers (3)

Set
Set

Reputation: 49779

You may move methods to separate classes. Classes may be new classes with dependency to MainClass with public/internal Process method, nested in MainClass or inherited from MainClass. Example with inheritance:

public class MainClass
{
   protected void Process(string message)
   {
    // ...
   }
}

public class A: MainClass
{
    // methods for A go here
}

public class B: MainClass
{
    // methods for B go here
}

Upvotes: 2

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

You're looking for object composition.

In computer science, object composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones.

BTW, you shouldn't think that such refactor is grouping methods logically: it's just you need to implement your code with a clear separation of concerns:

In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern.

Practical example:

public class A
{
    // B is associated with A
    public B B { get; set; }
}

public class B
{
     public void DoStuff() 
     {
     }
}

A a = new A();
a.B = new B();
a.B.DoStuff();

Upvotes: 5

itsme86
itsme86

Reputation: 19496

You can use nested classes:

public class MainClass
{
    // private method here

    public class A
    {
        // methods for A go here
    }

    public class B
    {
        // methods for B go here
    }
}

If you want them in different files, you can use a partial class for MainClass

// file 1
public partial class MainClass
{
    public class A { }
}

// file 2
public partial class MainClass
{
    public class B { }
}

Upvotes: 1

Related Questions