instanceof keyword usage

后端 未结 8 2257
野性不改
野性不改 2021-02-14 10:44

Is using the instanceof keyword against the essence of object oriented programming? I mean is it a bad programming practice? I read somewhere that us

8条回答
  •  北海茫月
    2021-02-14 11:01

    The key is to not see instanceof as being part of common "normal practice". Like introspection in general, instanceof is a special tool for use in particular, atypical circumstances. Whenever you do use 'instanceof', you may also find yourself using other 'special' parts of the platform such as reflection more generally.

    So long as whenever you find yourself using it you accept that what you're doing is a kludge in the absence of a more elegant/practical alternative, then that's fine.

    That said, the most typical circumstances in everyday programs are probably:

    • implementing equals()
    • reading serialized objects
    • a few other cases where you're given an array/collection of items, e.g. enumerating JComponents in a frame/container and then taking action depending on type.

    A rule of thumb you could try and stick to is to not require users of a library to have to use 'instanceof', but rather have any cases of 'instanceof' internal to the library.

    Or put another way, you should re-frame your question: "What are the cases that 'intsanceof' is a workaround for?"

提交回复
热议问题