Is there a shorter way that does the same thing

Started by
5 comments, last by SimonForsman 10 years, 8 months ago

The code is actually much longer but I decided to post a small snippet to avoid posting repetitive code. The idea is that the game detects which of the 26 alphabets was pressed and does a certain action upon key press. Code is in Java.

    public void keyTyped(KeyEvent e) {
 
    if(e.getKeyCode() == KeyEvent.VK_A)
        {
            
        }
        else if( e.getKeyCode() == KeyEvent.VK_B)
        {
            
        }
    }
 
Advertisement
Did you try switch?

Did you try switch?

Is it okay to have 26 cases using switch? Or do I just have to live with it?

Yes, a switch with 26 cases is perfectly fine, and it's possibly the clearest and fastest way to do it. Another valid alternative is using an array of function pointers (are there function pointers in Java?).

Is it okay to have 26 cases using switch? Or do I just have to live with it?

Aside from a lookup table, using a switch statement is probably the most efficient option. The compiler might actually rewrite the switch statement to use a lookup table, but it's not required to. However, using a lookup table would require a lot of boilerplate unless the switch statement is just mapping key codes to character values, which doesn't seem to be the case, so I'd go with the switch statement unless this code became a major bottleneck (which is quite unlikely).

Edit:

Looks like Álvaro got to it before me.

Thanks guys

Yes, a switch with 26 cases is perfectly fine, and it's possibly the clearest and fastest way to do it. Another valid alternative is using an array of function pointers (are there function pointers in Java?).

Java has neither pointers nor first class functions.

an array of objects with a suitable interface would be the closest you'd get in Java unless you use reflection. (You'd have to write one class for each mappable action though)

If you use reflection you can access a method by its name and a mapping from keycode to a string containing the method name is fairly clean but you'd get a bit of overhead on the method call itself.

[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

This topic is closed to new replies.

Advertisement