In order for me to get better and create more desired code, I would like to find out if the following situation is bad or acceptable.
I am creating an animation that gets triggered by two buttons, one on the left of a JPanel
and the other on the right. Depending on which button is pressed, the animation starts from the button position.
Now it can be quite some work working out the different calculations with a lot of internal if
and else
statements (to know which button is clicked) on the Method that handles the animation (I have done so).
If I clone the method and modify it to be suitable for one button (so each button calls a different method), which saves a lot of hassle, is that good or bad practise?
private void moveImage(){
if(xpos < imagewidth && ypos < imageheight) {
if(buttonA){
image.setX(image.getX() - xmove);
} else {
image.setX(image.getX() + xmove);
}
image.setY(image.getY() + ymove);
}
//other codes here
}
Or I could do this for button A and the same for button B:
private void moveImageA(){
if(xpos < imagewidth && ypos < imageheight) {
image.setX(image.getX() - xmove);
image.setY(image.getY() + ymove);
}
//other codes here
}
1 Answer 1
Depends on application design. What is "more important" - image, or button?
It could be something like move(Image image)
method in the buttons (decalred in interface of the buttons), or it may be reactOn(Button button)
in Image.
It is hard to recommend something with the presented information. Generally, code reuse is always a good move.
-
\$\begingroup\$ well from what your asking, i should say the image. I use one action performed method which subsequently means one paintComponent Method which draws an image. so if i press button A and later Button B. the animation might be messed up for Button B if you know what i mean since the position of the image might have changed. \$\endgroup\$irobotxx– irobotxx2012年04月11日 11:43:32 +00:00Commented Apr 11, 2012 at 11:43
-
\$\begingroup\$ Anyway, hard to recommend something certain. May be, en.wikipedia.org/wiki/Visitor_pattern may give you an idea. \$\endgroup\$Michael– Michael2012年04月11日 13:04:06 +00:00Commented Apr 11, 2012 at 13:04