Why shouldn't I store into literal arrays in Smalltalk?

后端 未结 2 2067
自闭症患者
自闭症患者 2020-12-11 05:34

Some style-guides and idioms suggest that you should not mutate literal arrays, like in this case:

MyClass>>incrementedNumbers

    | numbers |
    num         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 05:57

    It has been a source of quite some confusion in the past, when some method handed out a literal array (or string) to someone who modified it by accident. Hard to find, because the source code does not reflect the contents of the literal array.

    Therefore, some Smalltalks (VisualWorks, Smalltalk/X and maybe others) make literals immutable and will raise an exception, when the literal is written to (Smalltalk/X allows for this to be switched off at compilation time, in case you really really need that feature for backward compatibility).

    We have been working at our company for years with both schemes, and we really do not miss or need mutable arrays. I would bet that in a not so future version of Squeak, this will be also the case (if not already in the queue or in some changefile).

提交回复
热议问题