views:

70

answers:

3

I have to use a GUI Element that draws a picture at a specific screen position. If the user selects this picture there is a border drawn around the Image. Now we want to include another border that identifies pictures with a specific value for the user.

At the moment the Element looks at his internal state if it is selected and then decides how to draw itself.

graphic.drawImage(icon, x, y, null);
if (selected) {
    drawBorder();
}

I don't like the idea of adding another if else to this drawing method. I thought about creating a new class that inherits the behavior of the element and overwrites the draw method but that means duplicating the whole selected code in every inherited class. Is there a nice possibility so solve this problem without creating a subclass?

A: 

What do you have against if-else?

It makes less sense to me to create a whole new object for the selected item than to check a flag in the drawing function.

Jimbo
A: 

one possibility is to allow your drawBorder() method to take parameters:

private void drawBorder(boolean isSelected, boolean hasSpecialValue);

this method can determine which type of border to draw.

akf
+1  A: 

Since you tagged this with design-patterns and you seem to be looking for a pattern-oriented approach, I'd suggest taking a look at the state pattern. The example on the wikipedia page even mentions keeping state while drawing a GUI. Unfortunately, this would mean you'd have to create another class with subclasses and overridden methods.

Is this going to be something that is likely to change? I.e. do you realistically think you're going to be adding new behavior to the drawing (e.g. if the user double clicks, draw a different type of border; if the user right clicks, change the color of the border), or is this it? If you see more behavior being added, I think going ahead and taking a more OO approach is wise. If it's just these two cases, I'd say just add and else if statement.

Hooray Im Helping
I think you are right. Subclassing this for only two or three different behaviors is a overhead and if this will change later it can be changed to a more advanced approach. For now I'm trying to change the if else to a switch and the boolean selected to an enum indicating which behavior should be used for the drawing
Janusz
That sounds like a pretty wise idea. Once it starts getting too unmanageable, you can easily refactor the switch statement to use a more advanced OO approach.
Hooray Im Helping