Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smalltalk Pharo String concatenation instead of streams

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.

like image 534
Adrian Castravete Avatar asked Jan 05 '23 02:01

Adrian Castravete


1 Answers

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.

like image 107
Peter Uhnak Avatar answered Jan 31 '23 20:01

Peter Uhnak