Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Function pointers

Name: Brunch 2012-08-09 9:20

Heya /prog/. I'm programming in java and there's something that really bothers me about my code. I'll write pseudocode so it's easier to see what I mean so don't get picky on syntax.


class entity {
   int action = IDLE;

   void idle() { void; };
   void moveRight() { ... };
   void jump() { ... };

   void onUpdate() {
      switch(action) {
           case IDLE: idle(); break;
           case JUMPING: jump(); break;
           case MOVINGRIGHT: moveRight(); break;
          
           ...
      }
  }
}


Now this really bothers me because you have this pile of ifs depending on status. It would, in my opinion, look much better if action was a pointer to a function.

class entity {
   function_pointer action = idle;

   void idle() { void; };
   void moveRight() { ... };
   void jump() { ... };

   void onUpdate() {
       function_pointer();
  }

But apparently java doesn't have this functionality. Or does it?
What do you think? Have any solutions to this?

Name: Anonymous 2012-08-09 9:36

It's possible, but you're going to have to do a lot of exception handling (or rethrow them packed in RuntimeException) and if you refactor your methods, then the refactoring tool won't pick up this stuff without some additional work. Take a look at java.lang.reflection.

I don't know the parameter list by heart, but something similar should do:

class Entity{

Method reflectiveMethod;

static {
m = Entity.class.getMethod("idle");
}

void setAction(String mName) {
m = getClass().getMethod(mName);
}

void onUpdate() {
m.invoke(this);
}

}

Generally, java.lang.reflection can do anything that a more dynamic language could do, but it can be quite a hassle to handle it. Also, in this particular case, you're probably better off just using an internal state instance and dynamic binding or (since your code looks like it is going to be used for a game) do it the way you do, because it's pretty fast and does not waste memory or CPU time on state change.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List