I do not write this code to begin with (unless it is a script for one-time use or playback in REPL).
If I can explain what the code does in one comment and reads fine, I save it as one liner:
// Find all real-valued square roots and group them in integer bins ds.filter(_ >= 0).map(math.sqrt).groupBy(_.toInt).map(_._2)
If I do not understand this, having carefully read the command chain, I must break it down into functionally different units. For example, if I expected someone to not understand that the square root of a negative number is not real, I would say:
// Only non-negative numbers have a real-valued square root val nonneg = ds.filter(_ >= 0) // Find square roots and group them in integer bins nonneg.map(math.sqrt).groupBy(_.toInt).map(_._2)
In particular, if someone does not know the Scala collection library well and does not have the patience to spend from five to ten minutes understanding one line of code, then they should not work on my code (nor on anything else that does something it’s nontrivial that they don’t understand and don’t have the patience to understand), or I should know in advance what I provide, for example, to the language and mathematics in addition to writing working code, either by writing a paragraph explaining how the next line works, or by breaking team by command, or including comment A stage at the beginning of each anonymous function, explaining what happens (as needed).
In any case, if you cannot understand what it is doing, you will probably need some intermediate values. They are very useful for a mental reset ("I don’t see how to get from A to C! ... but ... okay, I can understand from A to B. And I can understand from B to C.")
source share