Showing posts from January, 2018

Break Down Code to Make It DRYer

We are always looking to make our code DRYer. Code that is not repeated is easier to maintain. We can make a change in just one place rather than hunting for different incarnations in many different places. Making code DRYer is not always easy, and sometimes how to remove the duplication is not apparent.

Let's say we have the following two functions:

public List<Stats> processLines(File file) { List<Stats> stats = new ArrayList<>(); for (String line : lines(file)) { Data data = extractDataFrom(line); Stats dataStats = calculateStatsFor(data); stats.add(dataStats); } return stats; } public List<Stats> processLines(List<File> files) { List<Stats> stats = new ArrayList<>(); int fileNumber = 0; for (File file : files) { for (String line : lines(file)) { Data data = extractDataFrom(line, fileNumber); Stats dataStats = calculateStatsFor(data); st…