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.
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();