Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern should I use for this?

I have a piece of logic that I need to execute either once or multiple times (in a loop) based on the type. Does a strategy pattern make sense here? In essence:

if (type == 1)
{
   ProcessReport("");
}
else if (type == 2)
{
   for (int i = 0; i < numUsers; i++)
   {
     ProcessReport(userId);
   }
}

public void ProcessReport(string id)
{
   if (id == "")
   {
     //Send full report
   }

   else
   {
     GetReportFragment();

     //Send report
   }
}
like image 220
DotnetDude Avatar asked Jan 19 '26 23:01

DotnetDude


1 Answers

Well, since you obviously use a "type code" to distinguish different behaviors, you could start by replacing it with subclasses (polymorphism). That's usually the first thing to do when there is a type code based branching.

For simple problems, however, this might be an overkill. What's more objectionable with your code is:

  • the use of magic numbers for your types: you should at least change them to enums to improve readability
  • passing empty parameters ("") to indicate specific behavior: at least create a separate method for a "full report", if you don't have an ID to specify
like image 153
Groo Avatar answered Jan 22 '26 11:01

Groo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!