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 11:13

I don't know Java well, but can't you do something like the following (in CLOS)?
(defclass action () ())
(defclass idle (action) ())
(defclass move-right (action) ())
(defclass jump (action) ())

(defclass entity ()
  ((action :type action :initform (make-instance 'idle))))

(defgeneric perform-update (entity action))
(defmethod perform-update ((entity entity) (action idle)))
(defmethod perform-update ((entity entity) (action move-right))
  ;; Move right
)
(defmethod perform-update ((entity entity) (action jump))
  ;; Jump
)

(defgeneric on-update (entity))
(defmethod on-update ((entity entity))
  (perform-update entity (slot-value entity 'action)))


Before some LISPPER gets offended, I want to write: of course, it would look cleaner with eql specialisers or functions, but I assume Java doesn't have that.

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