Instanceof : (almost) always harmful
I looked at all the answers to your post and tried to understand what you are doing. And I came to the conclusion that Instanceof exactly what you want, and your original code sample was fine.
You explained that:
You do not violate the Liskov substitution principle, since none of the Box codes cancels the Sprite code.
You are not to deploy the Instanceof answer code. This is why people say instanceof is bad; because people do this:
if(shape instanceof Circle) { area = Circle(shape).circleArea(); } else if(shape instanceof Square) { area = Square(shape).squareArea(); } else if(shape instanceof Triangle) { area = Triangle(shape).triangleArea(); }
This is why people shun instance. But that is not what you do.
There is a one-to-one relationship between Box and winning the game (no other Sprites can win the game). This way, you don’t need an additional abstraction of the “winner” sprite (because Boxes == Winners).
You simply check the board to make sure that each top element is a field. This is exactly what Instanceof needs to do.
Everyone else will answer (including my own), adds an extra mechanism to check if Sprite is a field. However, they do not add any stability. In fact, you use functions that are already supplied by the language and override them in your own code.
Tomas Narros argues that you must distinguish between "semantic types" and "Java types" in your code. I do not agree. You have already established that you have a java type, Box , which is a subclass of Sprite . Thus, you already have all the necessary information.
In my opinion, the presence of a second independent mechanism, which also reports “I am a box,” violates DRY (Do not Repeat Yourself). This means the absence of two independent sources for the same information. Now you need to save the enumeration and structure of the class.
The so-called "benefit" is the ability to pirouette around a keyword that completely fills the target and is harmful when used in more malicious ways.
Golden Rule Use your head . Do not obey the rules as a difficult fact. Ask them, find out why they are there, and bend them when necessary.
Chris burt-brown
source share