DEV Community

loading...
Cover image for Code Smell 23 - Instance Type Checking

Code Smell 23 - Instance Type Checking

mcsee profile image Maxi Contieri Originally published at mcsee.hashnode.dev ・2 min read

Do you check who are you talking to?

Problems

Solutions

  1. Avoid kind, isKindOf, instance, getClass(), typeOf, etc..

  2. Don't use Reflection and Metaprogramming for Domain Objects.

  3. Replace IFs with polymorphism.

  4. Avoid checking for 'undefined'. Use complete objects, avoid nulls and setters, favor immutability and you will never have undefined and ifs.

Sample Code

Wrong

Right

Detection

Since type checking methods are well known it is very easy to set up a code policy checking the uses.

Tags

  • Metaprogramming

Conclusion

Testing for a class type couples the objects with accidental decisions and violates bijection since no such control exists on real world. It is a smell our models are not good enough.

Relations

More Info

Credits

Photo by Remy Gieling on Unsplash

Discussion (3)

pic
Editor guide
Collapse
pedrohasantiago profile image
Pedro S

The sample in the "right" section is checking the types. The wrong and right samples are inverted, no?

Collapse
mcsee profile image
Maxi Contieri Author

hmm. not

Lines 1 to 9 are commented since they should not be done at all.
The rest is not checking any type as soon as I can see

Collapse
pedrohasantiago profile image
Pedro S

Oh, it is all good now. Weird, I could swear the snippets were inverted, sorry 🤔

Congrats on the series, the posts are great!