Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

similar function refactoring pattern

I have about 20 functions with almost the same pattern, i run on array of Sites, create SiteOperation with Site object and perform some operation ( in this case with one param but sometimes there are none or more)

int wantedBandwidthInLBps = 2048 / 8;
foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.LimitBandwidth(wantedBandwidthInLBps);
}

foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.KillJames();
}

foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.FlyToMoon(2012, new TaskIdentifier(10,20));
}

Is it possible to wrap this code, so i will just send action to lets say _sitesManagement which will run this action on all Sites ?

like image 255
eugeneK Avatar asked Jun 05 '12 12:06

eugeneK


1 Answers

Try this:

void PerformOperationOnAllSites(Action<SiteOperation> doIt) {
    foreach (Sites site in _sitesManagement.GetAll()) {
        SiteOperation siteOperation = new SiteOperation(site);
        doIt(siteOperation);
    }
}

...

_sitesManagement.PerformOperationOnAllSites(op => op.LimitBandwidth(wantedBandwidthInLBps));
_sitesManagement.PerformOperationOnAllSites(op => op.KillJames());
_sitesManagement.PerformOperationOnAllSites(op => op.FlyToMoon(2012, new TaskIdentifier(10,20));
like image 119
Sergey Kalinichenko Avatar answered Sep 28 '22 06:09

Sergey Kalinichenko