Hacker News new | ask | show | jobs
by greiskul 613 days ago
> I can even claim that this "old" style forces you to name the outcome of each step.

Yeah, but that does not necessarily make something easier to understand. Which function do you think is easier to understand?

func quadraticFormula(a int, b int, c int) {

  return (-b+sqrt(b*b-4*a*c))/2*a;
}

Or naming intermediate steps (since we only get to apply one function at a time, and math operators are just functions, why should they be special)?

func quadraticFormula(a int, b int, c int) {

  minus_b := -b

  squared_b := b*b

  four_times_a := 4*a

  four_times_a_times_c := four_times_a*c

  inside_of_sqrt := squared_b - four_times_a_times_c

  sqrt_result := sqrt(inside_of_sqrt)

  numerator := minus_b + sqrt_result

  denominator := 2*a

  return numerator/denominator;
}

Sometimes naming intermediate steps makes code easier to read. Sometimes it doens't. It depends a lot if the intermediate step has a semantic meaning or not, if you want the reader to pause and do a mental checkpoint or if it makes more sense to keep going. Kind of like when you are writing English, and you decide to stop a sentence, or keep going, you don't want your sentences to be too long, but also not too large. That's why good code should follow guidelines, but not hard rules. The programmer should write it in a way that is easier for the reader to understand, and that depends on the context of what is being done.

1 comments

Since you asked, I find the terse version to be completely unreadable*. If I wanted to understand it, I’d end up writing out all the steps for myself anyway.

There’s an asterisk here because you cherrypicked a function that is already widely known and understood. All we really need to understand that function is its name. If you chose complex niche business logic, or The Wave Function, it would have made for a more fair and instructive example.