I am trying to refactor a given piece of code as mentioned below:
ORIGINAL CODE:
Method(URL link)
{
if(ConditionA(link))
{
MehodA(link);
}else if(ConditionB(link))
{
MehodB(link);
}else if(ConditionC(link))
{
MehodC(link);
}else if(ConditionD(link))
{
MehodD(link);
}
}
the above code may grow as new condition may come in future. After refactoring I am able to divide the code into multiple classes each focused with single responsibility hence reducing the initial complexity as follows:
AFTER REFACTORING:
METHOD(URL link)
{
ConditionalHandlerClass obj = new ConditionalHandlerClass(link);
ConditionalHandlerClass.HandleLinkProcessing();
}
Class ConditionalHandlerClass
{
URL link;
IConditionalProcess process;
public ConditionalHandlerClass(URL _link)
{
link = _link;
}
public void HandleLinkProcessing()
{
if(ConditionA(link))
{
process = new ProcessA(link);
}else if(ConditionB(link))
{
process = new ProcessB(link);
}else if(ConditionC(link))
{
process = new ProcessC(link);
}else if(ConditionD(link))
{
process = new ProcessD(link);
}
process.Handle();
}
}
interface IConditionalProcess
{
void handle();
}
class ProcessA() : IConditionalProcess
{
void handle()
{
// Business Logic here
}
}
class ProcessB() : IConditionalProcess
{
void handle()
{
// Business Logic here
}
}
class ProcessC() : IConditionalProcess
{
void handle()
{
// Business Logic here
}
}
class ProcessD() : IConditionalProcess
{
void handle()
{
// Business Logic here
}
}
But i see that HandleLinkProcessing() method in class ConditionalHandlerClass will still keep on increasing as new condition keeps getting added.
Can you suggest how can i make this implementation better such that class like ConditionalHandlerClass should not be changed on addition of new flow of ConditionE() and MethodE() calls. Hence reducing complexity in once class even though the new conditions get added.
I am writing this code in objective c.
Aucun commentaire:
Enregistrer un commentaire