why would the following code:
| list types |
list := Heap new.
types := #('a' 'b' 'c').
types do:[ :t |
1 to:9 do:[ :i |
list add:(t, i asString).
].
].
^ list
issue the String concatenation instead of streams
warning in a method in Pharo?
Clicking the [?] button shows:
String concatenation instead of streams
Check for code using string concatenation inside some iteration message.
Am I doing something that can be done easier with streams? What I want to achieve is to create a list of all values a1 to a9, b1 to b9 and c1 to c9.
It complains because of the part t, i asString
that is inside a collection loop (you can look at the actual implementation of the rule in the class RBStringConcatenationRule
.
Normally string concatenation is discouraged because it's slower and more memory intense (IIRC about the memory).
So if you are doing some heavy concatenation (connecting a lots of parts into a single string), stream is preferable: you can look at most printOn:
methods in the system to see it in action.
However in trivial cases concatenation with ,
is just fine, the warning rule is just too broad. Warnings are just that... warnings that something might be wrong, or that something might be written better.
Speaking of better writing, in Smalltalk it is preferable to use specialized collection methods (select:
,collect:
,...) over the overly-generic do:
, e.g.
| list types |
types := #('a' 'b' 'c').
list := types flatCollect: [ :t | (1 to: 9) collect: [ :i | t , i asString ].
^ Heap withAll: list
(and if you don't need Heap
you can just return the third line directly and not have the list
tempvar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With