Instanceof considered harmful?

I am looking at some code that heavily uses Java instanceof . I will struggle with the temptation to delve into the details, as this is a common question. instanceof reminds me of C ++ dynamic casting, and the advice I read about it is a long time ago that if you think you need it, your model may be disabled. Is this generally accepted wisdom? Does this apply to Java instanceof ?

+4
source share
2 answers

Yes, you are on the right track. While instanceof has its uses, heavy use usually indicates that the design of your class is insufficient.

+11
source

In Java, generic files can / should be used to reduce instanceof keywords. Thus, only those few that are unknown at compile time need to be checked. However, instanceof not like goto - it will not spoil your control flow much (although it introduces many additional variables if you are not careful).

I regularly use instanceof , but if there are a lot of them, I would think that this is the smell of code. The trick is to come up with something better; if you can, then using instanceof is probably wrong. I would not know about the scheme to make sure that it is useful or bad for general cases. The listing after instanceof probably hurts more than the keyword.

+3
source

Source: https://habr.com/ru/post/1397708/


All Articles