Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (133)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Instanceof issues  (Read 5559 times)
0 Members and 1 Guest are viewing this topic.
Offline K.I.L.E.R

Senior Devvie




Java games rock!


« Posted 2005-12-26 13:24:12 »

I've been discussing with a friend about how to avoid using instanceof.
The most obvious answer is to have a proper design in the first place.
However the previous argument on these forums over instanceof was about why Java needs it and not how to overcome the issue through proper design.

I've pretty much tried to come up with a paper solution on how to remove dependency on instanceof, one of the assumptions is that both classes (Board and MagicUser) absolutely must know the class type of the BoardPiece.

http://members.optusnet.com.au/ksaho/designs/avoidInstanceof.png

Can someone offer an alternative on how to avoid instanceof in this situation.

Vorax:
Is there a name for a "redneck" programmer?

Jeff:
Unemployed. Wink
Offline Jeff

JGO Coder




Got any cats?


« Reply #1 - Posted 2005-12-26 20:00:30 »

SImple. Im goign t odo this in java5 cause ist cleanest but simairlt echniques work for earleir kidsn of Java

Boardpiece, which i assume is an Interface (but coudl also be an abstract class) defines the following:

enum PIECE_TYPE {PAWN, KNIGHT, MAGIC_KNIGHT}

public PIECE_TYPE getPieceType();

Each peice type then over-rides getPieceType to return the apporpriate enum.

If BoardPiece is an abstract class then  getPieceType() is defined as an abstract method.

If you arent udner Java 5, you use int and public static final int constants ( or Josh Bloch's "secure enumeration" pattern) instead of the enum.

JK

Edit:  Its shoudl be noted that this really doenst solve the REAL problem.  The user is still likely going to start doing switches on the returned peice type which is almost always wrong.  It usually indicates incorrect object design.

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline K.I.L.E.R

Senior Devvie




Java games rock!


« Reply #2 - Posted 2005-12-27 03:10:17 »

Nice.
Thanks.

Design has always been an issue. I would like to know when Java will incorporate a fully functional OO design so that things like instanceof are deprecated.
I've avoided using instanceof for a long time now however it still must be used when overriding the equals method.

Vorax:
Is there a name for a "redneck" programmer?

Jeff:
Unemployed. Wink
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline aldacron

Senior Devvie


Medals: 9
Exp: 16 years


Java games rock!


« Reply #3 - Posted 2005-12-27 10:31:30 »

Design has always been an issue. I would like to know when Java will incorporate a fully functional OO design so that things like instanceof are deprecated.
I've avoided using instanceof for a long time now however it still must be used when overriding the equals method.

I don't understand why you think inststanceof is so bad. What do you mean by 'fully functional OO design'?

The instanceof operator is useful in several 'OO' design scenarios. I use it extensively in an action validation system I implemented in my current project. I use it there because it makes sense. I'm not using it in any other systems in my project. Does that mean my project, or at least that particular system, is poorly designed? Does that mean my project is not 'full OO' (whatever that means)? Not even.

I've heard people say that using instanceof is indicative of a bad design, but that's rubbish. It's like the goto argument in C. Abusing the instanceof operator is bad design. And by abuse I mean designing your code around it, or using it when where it doesn't make sense to. In those cases where it does make sense it is an elegant solution. I'll be happy to give you an example of what I mean.
Online Riven
« League of Dukes »

« JGO Overlord »


Medals: 845
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #4 - Posted 2005-12-27 12:09:54 »

For me the only part of the program where I should not use instanceof is in tight-loops, because it quite a heavy operations. Everywhere else may be perfectly justified to use instanceof and should not be discarded as non-OO or not-fully-functional-OO (whatever that means...!). It's just one of the tools that Java allows you to use, one should not avoid it just for the sake of it.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #5 - Posted 2005-12-27 12:12:52 »

surely one preferes compile time checking over runtime checking, however deprecating instanceof is a whole other step. sure you can stuff and should stuff instanceof as low/early in your code as possible I can't see going without it.

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline kevglass

« JGO Spiffy Duke »


Medals: 212
Projects: 24
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #6 - Posted 2005-12-27 15:58:53 »

"instanceof" is a tool like the rest of java. Use it where it makes sense. Deprecating would be a mistake. Implementing the equals() method would be very annoying without it Smiley

However, surely the real solution is not to check the type of the object externally at all. Wherever you decide you need to check the type externally and perform some type specific functionality, put that functionality where it actually belongs - in the class in question (i.e. type specific functionality for maintainability should be kept with the specific type Smiley)

Poor example:

Interface Fruit. Two implementations Apple and Orange. Using instanceof (or any other external type check) you might have done:

1  
2  
3  
4  
5  
6  
public void eatSomeFruit(Fruit fruit) {
if (myFruit instanceOf  Apple) {
    System.out.println("Yum Yum!");
} else if (myFruit instanceof Orange) {
    System.out.println("Yucky!");
}


The response is specific to the type so put it where it should be, with the type. So we'd add eat() to the interface Fruit and implement appropriately in the types.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
public interface Fruit {
    public void eat();
}

public class Apple implements Fruit {
   public void eat() {
      System.out.println("Yum Yum!");
   }
}

public class Orange implements Fruit {
   public void eat() {
      System.out.prinltn("Yucky!");
   }
}


and finally our icky instanceof utility fruit eating method becomes:

1  
2  
3  
public void eatSomeFruit(Fruit fruit) {
    fruit.eat();
}


HTH,

Kev

Offline darkprophet

Senior Devvie




Go Go Gadget Arms


« Reply #7 - Posted 2005-12-27 16:46:41 »

Quote
For me the only part of the program where I should not use instanceof is in tight-loops, because it quite a heavy operations
When I was doing my entity framework and some AI stuff, i was worried about instanceof stuff, and changed to using getType() stuff, and I noticed that in a very crap microbenchmark, instanceof was 2 - 3 times FASTER than a method call...

http://www.java-gaming.org/forums/index.php?topic=5359.0

Alot of usefull advice is in that thread

DP

Friends don't let friends make MMORPGs.

Blog | Volatile-Engine
Offline aldacron

Senior Devvie


Medals: 9
Exp: 16 years


Java games rock!


« Reply #8 - Posted 2005-12-28 01:11:53 »

When I was doing my entity framework and some AI stuff, i was worried about instanceof stuff, and changed to using getType() stuff, and I noticed that in a very crap microbenchmark, instanceof was 2 - 3 times FASTER than a method call...

I used to be under the impression that instanceof was slow. Then I saw the source for <a href="http://sourceforge.net/projects/seda">SEDA</a> a few years ago (a high performance, non-blocking, networking library - pre NIO stuff). Somewhere in the codebase there was an even handling mechanism which used instanceof to route events. I was surprised to see it at first. Now I know it's not so bad.
Offline Jeff

JGO Coder




Got any cats?


« Reply #9 - Posted 2005-12-28 05:57:19 »

Nice.
Thanks.

Design has always been an issue. I would like to know when Java will incorporate a fully functional OO design so that things like instanceof are deprecated.
I've avoided using instanceof for a long time now however it still must be used when overriding the equals method.

instanceof will never be remnoved because it has legitimate uses.  You can do the same things with reflection ops but instnceof is easier and produces cleaner lookign code for the msot commonc ases such information is necessary.

Those uses, btw, are typically in very special cases involving run-time loaded code where the class hirearchy is not known apriori.

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Jeff

JGO Coder




Got any cats?


« Reply #10 - Posted 2005-12-28 05:59:54 »

Really, instanceof isn;t the issue.

switch is the issue.  98% of the time when you see a swtich statement it means a crew up in the OO design as all such code-switchign decisions aught to be handled by your inegritance structure.

There are expections ther too, though.  Packet handling woudl be *seriously* annoying without switch.  Similarly some other linds of data parsing are really adied by it (like writing recursive descent parsers.)

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline K.I.L.E.R

Senior Devvie




Java games rock!


« Reply #11 - Posted 2005-12-28 06:56:36 »

Thanks for the information.
I read Bla^3 rant about instanceof being there due to Java not being a full OO design so I had taken his position on instanceof and further advanced it as being evil.

Vorax:
Is there a name for a "redneck" programmer?

Jeff:
Unemployed. Wink
Offline Jeff

JGO Coder




Got any cats?


« Reply #12 - Posted 2005-12-28 22:14:27 »

Thanks for the information.
I read Bla^3 rant about instanceof being there due to Java not being a full OO design so I had taken his position on instanceof and further advanced it as being evil.

Things are seldom as simple or cut and dried as a good rant makes them out to be,


Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline Vorax

Senior Devvie


Projects: 1


System shutting down in 5..4..3...


« Reply #13 - Posted 2005-12-28 23:03:12 »


Those uses, btw, are typically in very special cases involving run-time loaded code where the class hirearchy is not known apriori.


The work I do in my day job depends HIGHLY on instanceof for this exact reason.  We would have to change thousands of lines of code if it was removed.

Offline Jeff

JGO Coder




Got any cats?


« Reply #14 - Posted 2005-12-29 01:37:32 »


Those uses, btw, are typically in very special cases involving run-time loaded code where the class hirearchy is not known apriori.


The work I do in my day job depends HIGHLY on instanceof for this exact reason.  We would have to change thousands of lines of code if it was removed.

FWIW there are a few key areas of the SGS that depend on instanceof for similar reasons Smiley

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline Markus_Persson

JGO Wizard


Medals: 16
Projects: 19


Mojang Specifications


« Reply #15 - Posted 2005-12-31 14:10:33 »

switch is the issue.  98% of the time when you see a swtich statement it means a crew up in the OO design as all such code-switchign decisions aught to be handled by your inegritance structure.

Unfortunately, telling bad programmers that will only result in them doing the same thing with an else if ladder instead, then spending the rest of their careers fearing the "horrible switch statement".

What really NEEDS to be removed, however, is the do {...} while statement. It's almost as evil as come from.

Play Minecraft!
Online Riven
« League of Dukes »

« JGO Overlord »


Medals: 845
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #16 - Posted 2005-12-31 16:07:29 »

I used do{...}while() like 2 times in 6 years. It's just:

1  
2  
3  
4  
5  
6  
boolean first = true;
while(first || <original condition>)
{
   first = false;
   <original code>;
}


And what's so extremly evil about it? It has its uses, once every 3 years...

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline woogley
« Reply #17 - Posted 2005-12-31 16:24:33 »

do...while is only good if you want to run the code inside the loop one time before checking the condition. can't think of any useful examples though ... o_O;;
Offline Mark Thornton

Senior Devvie





« Reply #18 - Posted 2005-12-31 16:43:56 »

do...while is only good if you want to run the code inside the loop one time before checking the condition. can't think of any useful examples though ... o_O;;
Usually where you have special case code for the zero case, so that you know the loop will run at least once but don't want to redundantly repeat the test on that first iteration.
Offline swpalmer

JGO Coder


Exp: 12 years


Where's the Kaboom?


« Reply #19 - Posted 2005-12-31 16:45:34 »

do...while is only good if you want to run the code inside the loop one time before checking the condition. can't think of any useful examples though ... o_O;;

I use it in my 4k game loop.

do {
  game initialization
....
  main game loop
....
  game over
} while (wants to play again);

Offline Anon666

Junior Devvie




aka Abuse/AbU5e/TehJumpingJawa


« Reply #20 - Posted 2005-12-31 18:32:16 »

absolutely!

works out at ~3 less bytecodes =)
Offline Markus_Persson

JGO Wizard


Medals: 16
Projects: 19


Mojang Specifications


« Reply #21 - Posted 2005-12-31 18:57:06 »

I know what it's good for, but the syntax is just horrible.
All other blocks have their flow control defined at the top. When reading code with a do {...} while block, you have to look down (or even worse, SCROLL down) to know what the block is about.

1  
2  
3  
4  
5  
do
{
  banana();
}
while (!isDone());


vs

1  
2  
3  
4  
5  
6  
boolean done = false;
while (!done)
{
   banana();
   done = isDone();
}


Sure, it's slightly more verbose, and it requires an extra variable, but at least it reads right. Wink

Play Minecraft!
Offline swpalmer

JGO Coder


Exp: 12 years


Where's the Kaboom?


« Reply #22 - Posted 2005-12-31 20:28:19 »

I know what it's good for, but the syntax is just horrible.
All other blocks have their flow control defined at the top. When reading code with a do {...} while block, you have to look down (or even worse, SCROLL down) to know what the block is about.

It makes sense though... the flow control is checked only after executing the body of the block, so the code is "where it should be" in that sense.

You have to scroll down to see what it is going to do AFTER running the body, not so you can see "what the block is about".

Maybe we should just get rid of while, do, and for, and use if and goto exclusively Smiley

loop:
   do stuff();
   if (!done)
       goto loop;

Is that better? Smiley

Offline Markus_Persson

JGO Wizard


Medals: 16
Projects: 19


Mojang Specifications


« Reply #23 - Posted 2005-12-31 21:38:45 »

Well, that's kinda my point. Wink

I think

1  
2  
3  
4  
5  
do
{
  stuff();
}
while (!done)


is just as evil as

1  
2  
3  
4  
loop:
  stuff();
  if (!done)
    goto loop;



Don't get me started on break and continue. Wink


[size=7pt](By the way, just to make this clear: I use do {...} while, break and continue in my code when it's needed. I just don't think they're "pure". This is all mostly tongue in cheek.)[/size]

Play Minecraft!
Offline swpalmer

JGO Coder


Exp: 12 years


Where's the Kaboom?


« Reply #24 - Posted 2005-12-31 22:42:00 »

Don't get me started on break and continue. Wink

One of my favourite additions that Java has that C/C++ is missing is the labelled break and labelled continue.  I find they make the code much cleaner than introducing extra variables and logic in inner loops.

So I guess I prefer do..while to introducing that extra variable, and that "special case" init code outside the loop to "set things up so it works right for the first pass"... to me do..while is the cleaner solution.  Though I do get where you are coming from with respect to the consitency of having all of the loop logic at the beginning loop statement.  It's all about personal preference really... there is nothing scientifically right or wrong about either approach.

Quote
This is all mostly tongue in cheek.
ditto. Wink

Online Riven
« League of Dukes »

« JGO Overlord »


Medals: 845
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #25 - Posted 2005-12-31 23:56:28 »

1  
2  
3  
4  
whileButAtLeastOnce(!done)
{
   stuff();
}


!!!



do{..}while just sounds plain wrong...:

"do your thing while the dog is out"

does that imply that I should do my thing at least once... nope.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline princec

« JGO Spiffy Duke »


Medals: 436
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #26 - Posted 2006-01-01 14:13:38 »

The correct construct should have been lifted from BASIC's "repeat....until" which makes far, far more sense.

Too late now. The milk puddle evaporated 10 years ago...

Cas Smiley

Offline Ask_Hjorth_Larsen

Junior Devvie




Java games rock!


« Reply #27 - Posted 2006-01-02 20:58:44 »

I think we have all heard lots of warnings about these things. instanceof, break, continue, multiple return statements, and so on. But these all have (few) legitimate uses, where they simplify matters a lot. The one syntactical feature of java which I cannot say this about, is the following:

1  
2  
int[] a; //An int-array called a
int b[]; //An int called b, or, well, make that, like, a whole array of them now that we're at it, because now the caret is all the way over to the right of the identifier and I can't be bothered to use my left arrow key to go back and change it.

Offline swpalmer

JGO Coder


Exp: 12 years


Where's the Kaboom?


« Reply #28 - Posted 2006-01-03 02:06:22 »

I prefer the Java way:
1  
int[] a;


But I assume this was left in so the transition for C programmers would be easier
1  
int b[];


I agree, it is lame.

Offline Jeff

JGO Coder




Got any cats?


« Reply #29 - Posted 2006-01-03 04:27:13 »

I prefer the Java way:
1  
int[] a;


But I assume this was left in so the transition for C programmers would be easier
1  
int b[];


I agree, it is lame.

I think you hit it  on the head.  To most of us, and to the Java designers, int[] makes eminently mreo sense but if you tink back to the beginnign  of Java one of the reasons Java succeeded where any other simialr new languages failed is that transiton from C or C++ was realtively easy.  Im sure this was to head of resistance to the chnage of syntax on arrays,

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (38 views)
2014-12-15 09:26:44

Mr.CodeIt (31 views)
2014-12-14 19:50:38

BurntPizza (62 views)
2014-12-09 22:41:13

BurntPizza (99 views)
2014-12-08 04:46:31

JscottyBieshaar (60 views)
2014-12-05 12:39:02

SHC (74 views)
2014-12-03 16:27:13

CopyableCougar4 (77 views)
2014-11-29 21:32:03

toopeicgaming1999 (138 views)
2014-11-26 15:22:04

toopeicgaming1999 (127 views)
2014-11-26 15:20:36

toopeicgaming1999 (38 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!