If I have complex a task to solve I sometimes end up in a situation where I have one method that controls the execution. Because of null checks, if statements, calling methods that map between types and so on, this method can become really long and I struggle to make it simpler.
Example 1
public class A
public string MethodA(string stringA)
{
var fooResult = _fooService.fooMethod(stringA);
if(fooResult)
var barResult = _barService.barMethod(fooResult);
if(barResult)
// And so on..
return someResult;
}
I could chain the method calls which makes the first method simpler. But this makes the fooMethod dependant on the _barService, and the barMethod dependant on the _someService and so on.
Example 2 (same as above but with chained method calls)
public class B
public string MethodB(string stringB)
{
return _fooService.fooMethod(stringB);
}
public class Foo
public string fooMethod(string stringB)
{
return _barService.barMethod(stringB);
}
public class Bar
public string barMethod(string fooString)
{
return _someService.someMethod(fooString);
// And so on...
}
How should I structure my code? And how should I think when it comes to which method that is responsible for calling another method?
In other words, should I do like this:
class A
{
Execute()
{
A();
B();
C();
}
method A()
{
...
}
method B()
{
...
}
method C()
{
...
}
}
Or like this:
class B
{
Execute()
{
A();
}
method A()
{
B();
}
method B()
{
C();
}
method C()
{
...
}
}