Gathering all data in single iteration vs using functions for readable code
Posted
by
user828584
on Programmers
See other posts from Programmers
or by user828584
Published on 2013-06-21T05:28:53Z
Indexed on
2013/06/25
16:28 UTC
Read the original article
Hit count: 399
Say I have an array of runners with which I need to find the tallest runner, the fastest runner, and the lightest runner. It seems like the most readable solution would be:
runners = getRunners();
tallestRunner = getTallestRunner(runners);
fastestRunner = getFastestRunner(runners);
lightestRunner = getLightestRunner(runners);
..where each function iterates over the runners and keeps track of the largest height, greatest speed, and lowest weight. Iterating over the array three times, however, doesn't seem like a very good idea. It would instead be better to do:
int greatestHeght, greatestSpeed, leastWeight;
Runner tallestRunner, fastestRunner, lightestRunner;
for(runner in runners){
if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
if(runner.speed > ...
}
While this isn't too unreadable, it can get messy when there is more logic for each piece of information being extracted in the iteration.
What's the middle ground here? How can I use only a single iteration while still keeping the code divided into logical units?
© Programmers or respective owner