im working on Smalltalk, i have "tweets" collection, each tweet have "user" and i want to count the tweets by user in a dictionary.
So i have to add a counter in each key of the dictionary, and have to add keys for the first time i get the user.
I was thinking in this code for the add, i want to know if is human redeable and efficient or is there a better way to do it
tweetCountUserFrom: tweet in: aDictionary
| user |
user := tweet user.
aDictionary at: user ifAbsentPut: 0.
aDictionary at: user put: (result at: user) + 1
Your code is clear enough (even though it likely includes a mistake as the result
variable should have been aDictionary
instead). Anyway, the intention is clear and does (or is expected to do) the same a well-known object does, which is Bag
. So, let's see how the code would have been with an instance of Bag
(it is always a good idea to become increasingly familiar with the Collection
hierarchy of Smalltalk). Here is how you could arrive at the same result
tweetCountUserFrom: tweet in: aBag
aBag add: tweet user
That's it!
When it is time for you to see how many tweets
a user
has authored, you will only need to evaluate
aBag occurrencesOf: user
Internally, aBag
will hold a Dictionary
and will maintain it the way you intended in your code. However, by using an existing object you will keep your code simpler, shorter and easier to read and maintain. You will also decrease the probability of failure as Bags
have been kicking around for more than 40 years now, so there is little chance for them to decieve you.