Functional Aspects: They Say Stay Away From Ternary

I remember myself working on a project where ternary operators were used very actively in various situations. The more I read that code, the less comfortable I felt with it, and eventually caught myself on these questions:

  • Why are there so many cases of this syntax construct.
  • Should I (am I expected to) use the ternaries as well for the consistency reasons?
  • Is this code good or not generally speaking?
  • And more importantly, whether I should use ternaries a lot or stay away from them?

The more developers I spoke with, the more diverse perspective I heard. Eventually, I got very confused and made a decision to not use the weird thing (due to the absence of a good framework or a “mental model”). The decision has been followed almost to a degree it becomes a mantra but…

Continue reading →

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 →