Work in C#, want to reduce if else series, entity have two property FromServiceID
and ToServiceID
,suppose my ServiceClass
instance have bellow information.How to clean up bellow code? any type of suggestion will be acceptable.
entity= new ServiceClass();
entity.FromServiceID=3
entity.ToServiceID=1
if (entity.FromServiceID == 1)
{
entity.1KWithdrawal();
}
else if (entity.FromServiceID == 2)
{
entity.10KWithdrawal();
}
else if (entity.FromServiceID == 3)
{
entity.BTWithdrawal();
}
if (entity.ToServiceID == 1)
{
entity.1KDeposit();
}
else if (entity.ToServiceID == 2)
{
entity.10KDeposit();
}
else if (entity.ToServiceID == 3)
{
entity.BTDeposit();
}
public class ServiceClass
{
public int FromServiceID { get; set; }
public int ToServiceID { get; set; }
public void 1KWithdrawal()
{ Console.WriteLine("One_KWithdrawal"); }
public void 10KWithdrawal()
{ Console.WriteLine("Ten_KWithdrawal"); }
public void BTWithdrawal()
{ Console.WriteLine("BTWithdrawal"); }
public void 1KDeposit()
{ Console.WriteLine("One_KDeposit"); }
public void 10KDeposit()
{ Console.WriteLine("Ten_KDeposit"); }
public void BTDeposit()
{ Console.WriteLine("Ten_KDeposit"); }
}
Use a
Dictionary
. Something like this:An example of how using it:
Maybe this is an overkill, but you can create a class for each one of your cases that inherits from a common interface (let's call it
ICommon
) that exposes a common method for each case (in your case a Create method) and then inject that interface in the constructor ofServiceClass
.Then when you want to use
ServiceClass
, you will have to provide an actual implementation ofICommon
(one of the classes you extracted from each case) and finally you only have to callentity.Create
.I believe this is the strategy pattern, that in summary says that you should extract an algorithm in a different class under a common interface.
Finally, this refactoring will reduce the cyclotomic complexity of your code (this mainly means that you reduce the branching on your code) which always a good thing.
You can use switch case as below:
What you could do is to put all the variations into an enum and call the enum values exactly like your methods that you would like to call. (I would suggest not to use numbers in the name, since the compiler won't allow it)
For the sake of simplicity and testability I put the enum and the methods into the same class:
This would be the method that would execute your if-condition methods. It uses reflection to access the methods that are coded in the enum. You probably have to adjust the
object
parameter in theInvoke(sc, null);
call depending on where your methods are situated. If they are in the same class as where you would callexecute
you can usethis
.And here you can test the entire code:
So you would end up with an enum and 2 lines of code.