3 ms·
I would say the imperative version is easier to read in this article. The functional version doesn't really illustrate the benefits of functional programming ve
by ebingdom 5y ago
I would say the imperative version is easier to read in this article. The functional version doesn't really illustrate the benefits of functional programming very well, IMHO. I think there are two issues that reduce the effectiveness of the example:
1. Both examples contain a bunch of extra logic that has nothing to do with the difference between the two styles. For example, the code that converts users to that `UserLevelPoints` struct takes up a lot of space in both examples and is essentially the same in both. I think it would have been better (for pedagogical purposes) to just return the users (or perhaps a simpler struct containing a level and a user).
2. Both examples still have all the verbosity that is typical of imperative code, since it's still Go after all.
If one were to write the same function in a syntax which was designed for functional programming, the result might look something like this:
topUser = head . sortBy points
topUserPerLevel = topUser . values . groupBy level
I find this vastly quicker to read and understand than either of the examples in the article. But that relies on me knowing the functional-optimized syntax (e.g., that the `.` operator is just function composition), and for most imperative programmers that is the main hurdle. Since I am familiar with both styles, I can tell you that this would take me about 6 seconds to understand, whereas understanding each of the examples in the article took me at least a minute to even read the code, let alone understand it—and if there were bugs I wouldn't have noticed.
In contrast, with the simple functional version I provided, I can read it in seconds and be reasonably confident that it is correct (assuming all the pieces fit together in a valid way, which a type checker can check for me).
If the unfamiliar syntax prevents you from grokking the example I provided, it's reasonable to assume it's just some clever code golf that should be discouraged in production code. But please resist that temptation; this is actually what good code looks like. It's simple, not repetitive, and there aren't many places for bugs to hide.