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: Cudder !MhMRSATORI!fR8duoqGZdD/iE5 2012-08-10 6:21

Java bytecode has a direct indexed jump instruction which is what a switch would compile to.

The JIT should be able to compile that to an indirect jump, so your initial solution would be the most efficient.

>>6
This is the verbose (and "OOP") way to do it, taking advantage of the fact that you can have variables of class type and storing different objects with methods in them, but I recommend against that unless those actions have their own independent state.

But if you really want to use function pointers, switch to a language that has them!

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