1

I wanted to get the list of methods of a class if their implementation has at least two occurrences of a word 'assert' in Smalltalk.

Can somebody help me with this? Thanks in advance!

Harika Putta
  • 63
  • 1
  • 8

1 Answers1

4

I'm not sure about the details of gnu-Smalltalk, but in Pharo, you can do something like this:

YourClass methods select: [ :method |
    method sourceCode matchesRegex: '.*assert.*assert.*'. ]

Here I use a trivial regex to see if I can match two "assert" words in the source code.

However, with Smalltalk, it's easy to do more precise searches. Image, you want to see if a method sends at least two assert: messages. You can find such methods this way:

YourClass methods select: [ :method |
    | numAsserts |
    numAsserts := method ast allChildren count: [ :node |
        node isMessage and: [ node selector = #assert: ] ].
    numAsserts >= 2
]

In the example above, for each method, we simply count the number of AST nodes that are message sends, and have the assert: selector. Then we check if the number of these nodes is greater or equal to 2.

Uko
  • 13,134
  • 6
  • 58
  • 106
  • Thanks for the reply. Let me be more clear. I wanted to 'find every method with #isVariable set to true that contains an assertion statement at least two times'. can you help me with this... – Harika Putta Nov 09 '20 at 09:42
  • @HarikaPutta what is #isVariable ? Is that a temp var? Also, if you're talking about dynamic value (this true is set somewhere else, or comes from some other computation) it's going to be hard and not precise (although not impossible). If you want to find methods that have a code like `isVariable := true`, then I can give you a hand – Uko Nov 09 '20 at 12:59