6 ms·
This is my engineering org's philosophy as well. New engineers who have a java background tend to have some difficulty getting used to it, but all it takes is
by rockostrich 7y ago
This is my engineering org's philosophy as well. New engineers who have a java background tend to have some difficulty getting used to it, but all it takes is a light switch in their head.
For example, the other day there was a PR for creating a simple csv report and they wrote something like
val buffer = new StringBuffer()
buffer.add(header)
buffer.add("\n")
someList.forEach { item =>
val values: List[String] = someTransformation(item)
buffer.add(values.mkString(","))
buffer.add("\n")
}
buffer.toString
which is fine and readable, but it doesn't really seem like having side-effects (even though the scope was contained in the function and there weren't any worries about thread safety) aren't worth it over doing something like
val rows: List[String] = someList.map { item =>
val values: List[String] = someTransformation(item)
values.mkString(",")
}
(header :: rows).mkString("\n") + "\n" // I forgot whether they appended the string with a line break or not...
- Matthias247 7y agoThe above version might be more efficient (less allocations, less GC), which certainly matters for some applications. I actually also find it more readable, but that’s a personal preference
- gridlockd 7y agoI like that version A 1) is more readable (fight me) 2) doesn't rely on internal optimizations for string concatenation, in order to be as efficient 3) doesn't create extra garbage (linked lists) In fact, the only thing I would change is make it a for loop instead.
- rbonvall 7y agoYou can have the line break appended at the end by using the three-arg version of mkString: (header :: rows).mkString("", "\n", "\n") My two cents: I prefer the second solution. Maybe it's because I have never programmed in Java.
- zaphirplane 7y agoI love how when a person posts a good snippet someone will always chime in with an improvement
- deleted 7y ago[deleted]