avoid instanceof in Java

前端 未结 9 2250
清歌不尽
清歌不尽 2021-02-12 20:40

I have been told at some stage at university (and have subsequently read in upteen places) that using instanceof should only be used as a \'last resort\'. With this

9条回答
  •  抹茶落季
    2021-02-12 21:13

    EDIT

    There are two primary things you can do here to relieve yourself of this specific instance of instanceof. (pun?)

    1. Do as my initial answer suggested and move the method you are targeting up to the class you are iterating. This isn't ideal in this case, because the method doesn't make sense to the parent object, and would be polluting as Ted has put it.

    2. Shrink the scope of the objects you are iterating to just the objects that are familiar with the target method. I think this is the more ideal approach, but may not be workable in the current form of your code.

    Personally, I avoid instanceof like the plague, because it makes me feel like I completely missed something, but there are times where it is necessary. If your code is laid out this way, and you have no way to shrink the scope of the objects you are iterating, then instanceof will probably work just fine. But this looks like a good opportunity to see how polymorphism can make your code easier to read and maintain in the future.

    I am leaving the original answer below to maintain the integrity of the comments.

    /EDIT

    Personally, I don't think this is a good reason to use instanceof. It seems to me that you could utilize some polymorphism to accomplish your goal.

    Have you considered making setUITweenManager(...) a method of GameObject? Does it make sense to do this?

    If it does make sense, you could have your default implementation do nothing, and have your GameGroup override the method to do what you want it to do. At this point, your code could just look like this then:

    private void allocateUITweenManager() {
       for(GameObject go:mGameObjects){
           go.setUITweenManager(mUITweenManager);
       }
    }
    

    This is polymorphism in action, but I am not sure it would be the best approach for your current situation. It would make more sense to iterate the Collection of UITweenable objects instead if possible.

提交回复
热议问题