Search code examples
smalltalkpharo

How to remove item from NewList in Pharo 5


I've tried to remove an item from a NewList but there is no method for this. It is safe to access the list items directly? Why there is no removeItem: method?

| m |
m := NewListModel new.
m items: (1 to: 50) asOrderedCollection.
m headerTitle: 'Fubu'.
m setSelectedIndex: 2.
m listItems remove: 3.
m openWithSpec.

The above works but if I have domain objects it will fail with message:

ShouldNotImplement: #remove:ifAbsent: should not have been implemented in Array

Solution

  • You should not remove: an item from m listItems as shown in your next to last statement above. Send the m items: message again instead. For the argument of this message let your model object provide the collection of items that no longer contains the element you want removed.

    Of course if those elements are held in an Array you will not be able to remove: anything from it, and will need to provide a new Array as a copy of the original without the removed element. However, if your model keeps the elements in an OrderedCollection, it would just be a matter of removing the element from it.

    In other words, you need an actual model object in charge of knowing which elements belong in the collection and the NewModelList instance reflecting this situation rather than the NewModelList holding and maintaining such a collection by removing or adding elements to it because that's the job of your actual model object. Both objects will point to the very same collection but with different responsibilities on it.