0

If we have 2 classes

class databaseGateway
class format

Lets say we make a query through databaseGateway and get 5 rows. We want to apply formatting and update the row in the database.

We can do all of this simply within 1 loop

foreach($rows as $entry => $array) {
     $update['page'] = $format->html($array['page'];
     $update['id'] = $array['id'];
     $databaseGateway->update($update);
}

But is this not against the Single Responsibility Principle? According to this principle, would we have to make one loop for formatting the rows, and another loop to update the database?

foreach($rows as $entry => $array) {
    $rows[$entry] = $format->html($array['page']);
}


foreach($rows as $entry => $array) {
    $databaseGateway->update($array);
}

This seems to be wasteful of resources, but also a duplication of code? Going against the Don't Repeat Yourself principle.

What would be the correct professional way to handle this issue? Seems very common.

Thanks

cecilli0n
  • 457
  • 2
  • 9
  • 20
  • I think, this question belongs to http://programmers.stackexchange.com/ – Sebastian Wramba Jan 31 '14 at 12:49
  • It's not against SRP since you're way too low level for that principle and the update NEEDS the formatting. Both action are actually part of the same 'service'. Btw apply SRP when designing classes and methods, not 'for' loops – MikeSW Jan 31 '14 at 12:55
  • SRP doesn't say that you can't do multiple things in a loop. – Digital Chris Jan 31 '14 at 12:56
  • @ MikeSW If the forloop was in a method, Then the method would be doing 2 things, I left out excessive code to allow for an easier understanding of the main point. However being low level seems logical, A point where the principle doesn't need to be applied. @Digital Chris With regards to not doing multiple things in a loop, The more we do in one loop, Does this not lead to tighter coupling also? – cecilli0n Jan 31 '14 at 13:05
  • Guess you can exaggerate everything. Why would you format an in-memory string and then do anything with it? MikeSW is correct, both things ARE tightly coupled because everything else does not make any sense. – Sebastian Wramba Jan 31 '14 at 13:12
  • No, their use doesn't affect what they are. This is equivalent to learning a rule like "A good English word should have only one spelling and one definition", and then claiming that based on that rule, people should only have 1-word sentences. – Digital Chris Jan 31 '14 at 14:11

0 Answers0