0

How can I validate a parameter as a class object? For example, if I want to validate aparameter as string I could write param1 isString. Is there something like isClass?

Benjamin Pollack
  • 27,594
  • 16
  • 81
  • 105
gigman
  • 213
  • 2
  • 9

2 Answers2

3

As others have pointed out, isKindOf: and isMemberOf: are your friends when you're trying to figure this kind of thing out, but calling those methods is usually a kind of code smell. There are almost always better ways to do this, which I'll break into two categories:

  1. Implement the method on all relevant classes, doing the right thing on each. For example, if I were writing a video game, then, rather than testing what kind of object I'm getting it and telling it what to do next, I can instead just implement a performNextStep function on all game objects, then leave it to each object to figure out what it ought to do.
  2. Test for functionality, not class membership. Rather than checking whether something isKindOf: a class, instead check whether it respondsTo: aMethod, and call it if it does. This also means that classes that have acquired a valid method, but are not in the initial hierarchy you were anticipating, can still be passed around—doubly important if you're using Traits, where there may not be a single class hierarchy to test with.
Benjamin Pollack
  • 27,594
  • 16
  • 81
  • 105
2

You can test whether your parameter inherits from Class or Metaclass:

String isKindOf: Class orOf: Metaclass => true
"If you don't want Metaclasses, simply use isKindOf: Class"
String class isKindOf: Class orOf: Metaclass => true
'foo' isKindOf: Class orOf: Metaclass => false

However, it might be preferable to implement the operation you want to perform on Class (and any other relevant objects) itself, so you can just perform someOp without actually validating your inputs.


If your input is a String and you want to get the Class with the according name (if it exists), you can use:

Smalltalk classNamed: 'String'
Leo
  • 37,640
  • 8
  • 75
  • 100
  • 2
    If you want to cover case of Class, Metaclass and Trait, you also have message #isBehavior in Squeak.
    – aka.nice Dec 16 '12 at 21:59