Sunday, 15 September 2013

java - Am I using instanceof "wrong"? -



java - Am I using instanceof "wrong"? -

so in simple game engine of mine utilize interface "updatedgameelement" signal object having interface has updated every frame through implementation of update() method.

now in "main"(not main) class iterate through list of gameelement 's , check if these instanceof updatedgameelement. if case cast them, , phone call .update().

now thing is, read using instanceof sign of bad coding; , in cases classes used markers when replaced variable, agree. i'm not sure case.

i guess allow gameelement class implement updatedgameelement, , define standard empty update() method needs overridden something, i'm not sure if , why improve have now.

what say?

edit: code main class:

public void process() { if (active) { (gameelement ge: elements) { if (!ge.istoberemoved()) { //relevant part if (ge instanceof updatedgameelement) { ((updatedgameelement) ge).update(); } } else { prepareremoval(ge); } } processremovals(); } }

following invitation if op:

if utilize of interface has no other reason add together marker plus update method ges, , if type uge isn't used except after single instanceof, weak reason having these types. when capability of beingness updated can extended other ges, noop.

an abstract method in base of operations class forces programmer decide whether update needs coded particular subclass. approach rather "safe" "defensive design" point of view. but, of course, write more code.

in contrast previous technique: if forget interface there's no alarm.

also, if code noop update method in base of operations class , rely on programmers' alacrity override necessary: convenient, risky when forget it.

summarizing: there few subtle pro's , con's - not instanceof "smell".

java oop instanceof code-smell

No comments:

Post a Comment