Functional Aspects: Why Chaining Is Good

This is a short note about one of those things that annoy me quite often during code reviews. I am talking about primitive obsession used instead of some nicer alternatives. So let’s look at the code.

Here’s a simplified model class that stores amount of earned money and number of worked hours for a given day in an employee’s timesheet:

export class TimesheetDay {
  workDate: string;
  amount: number;
  hours: number;
  // ...
}

If we need to calculate the total amount of money earned by an employee within a given timeframe, the naive implementation would look like this:

public sumTimeSheetAmounts(weekDays: TimesheetDay[]): number {
  var sum = 0;
  for (let dayIndex = 0; dayIndex < days.length; dayIndex++) {
    const day = days[dayIndex];
    sum += day.amount;
  }
  return sum;
}

I see this kind of imperative bit-by-bit code in most of the pull requests. Does this code works? Yes, now it does. Is it easy to understand, maintain, extent? Definitely No, however even today in year 2017 many programmers would still disagree!

Continue reading →